I’ve created a simple Activity class for an audio example. But the problem is the the audio file keeps running even if I leave the app. I just want to stop the ACTIVITY by pressing the ‘OK/DONE” button in middle of any phone. Which method should I override in the activity class?
public class Audio extends Activity {
private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_audio, menu);
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int resId;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
resId = R.raw.up;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
resId = R.raw.down;
break;
default:
return super.onKeyDown(keyCode, event);
}
// Release any resources from previous MediaPlayer
if (mp != null) {
mp.release();
}
// Create a new MediaPlayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
// Indicate this key was handled
return true;
}
}/// end class
You can handle what you want in onPause() method. Or you can also implement
onDestroy() method. When you press home button or when you close the application, it goes to onPause() and then onDestroy().