I am a newbie to Android and have got stuck at stopping media player within the same activity .
I want to create an app that plays different music for different activities.
I am unable to stop the music once the first activity is created.
Even when I quit my app, the music is still playing.
Here is my code:
public class LayoutThreeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_three);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.layout_three, menu);
return true;
}
public void openNewActivity(View view) {
// Do something in response to button
Intent intent = new Intent(this, LayoutOneActivity.class);
startActivity(intent);
MediaPlayer mp = MediaPlayer.create(this, R.raw.song2);
mp.start();
}
You have to release the player OnPause or OnDestroy method.
@Override
public void onDestroy() {
if (mp!= null) mp.release();
}
I want to create an app that plays different music for different activities.
Then Put this thing above your onCreate method & below class Name In each Activity you want to play MediaPlayer:
MediaPlayer mp=null;
In your onCreate() method start your music & remove this code from openNewActivity() method:
mp = MediaPlayer.create(this, R.raw.song2);
mp.start();
I am unable to stop the music once the first activity is created. Even when I quit my app, the music is still playing.
Then put this in your each activity in which You have Start the MediaPlayer:
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mp.stop();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.stop();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.