Search code examples
androidbackandroid-videoview

Problem with back button in VideoView


I am having difficulty getting the back button to actually finish my activity when pressed. I am running a very simple videoview, using a progressdialog to show loading dialog and onpreparedlistener, etc etc. simple stuff. Anyways, currently when I press the back button, it will just cancel the progressdialog, and leave a black screen, and pressed again, the progressdialog restarts!!! and then when I click the back button again, it displays an alert dialog, "video cannot be played." very annoying. Thanks for your help.

public class VideoActivity extends Activity {

    private VideoView mVideoView;

    private static ProgressDialog progressdialog;
    private String path;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videoview);


        progressdialog = ProgressDialog.show(this, "", " Video Loading...", true);
        progressdialog.setCancelable(true);

        mVideoView = (VideoView) findViewById(R.id.surface_view);
        mVideoView.setMediaController(new MediaController(this));
        Bundle b = this.getIntent().getExtras();
        path = b.getString("path");
        mVideoView.setVideoURI(Uri.parse(path));


        mVideoView.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {
                progressdialog.dismiss();
                mVideoView.requestFocus();
                mVideoView.start();

            }
        });

    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();

        super.finish();

    }

}

Solution

  • You can simply write: (No need to create new class for MediaController)

    mVideoView.setMediaController(new MediaController(this){
            public boolean dispatchKeyEvent(KeyEvent event)
            {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                    ((Activity) getContext()).finish();
    
                return super.dispatchKeyEvent(event);
            }
        });