Music does not play after clicking back key and returning to activity in Android
I am trying to play Audio using videoView using MediaController. The Audio is playing well, when I click back key the controls returns to previous state. But when I select activity again from launch screen, activity appears but music doesnot play. Can anyone help me in sorting out this issue? The code is as follows:
public void onCreate(Bundle savedInstanceS开发者_Go百科tate) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video);
videoView = (VideoView)this.findViewById(R.id.videoView);
videoView.setVideoPath("http://www.pocketjourney.com/downloads/pj/video/famous.3gp");
final MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoURI(Uri.parse("http://www.pocketjourney.com/downloads/pj/tutorials/audio.mp3"));
videoView.requestFocus();
videoView.start();
videoView.setMediaController(new MediaController(this)
{
public void hide()
{
System.out.println("HIDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEHELLLOO");
mc.show();
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Thanks in AdvanceIf you are trying to play the music only when the activity is in the foreground, you want to start and stop the music in onResume
and onPause
, not onCreate.
Take a look at the Activity Lifecycle. OnCreate is only invoked once when the activity is created. If the activity goes into the background and then reappears, it may not be called.
# use this code...the song plays even if the user presses his back button #
public void playAudio(){
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("/sdcard/fileaudio.mp3");
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
//playAudio();
}
});
}
public void onBackPressed() {
Intent intent = new Intent();
intent
.setAction(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_HOME)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
精彩评论