Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

    }

}
like image 600
benbeel Avatar asked Aug 26 '11 15:08

benbeel


People also ask

DO all Android devices have a back button?

All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI. Depending on the user's Android device, this button might be a physical button or a software button.


1 Answers

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);
        }
    });
like image 126
Serge Him Avatar answered Nov 09 '22 12:11

Serge Him