我设法为我的应用添加背景音乐,但当我关闭它时,它不会停止。当我点击HOME
或BACK
按钮时,它仍会播放音乐。有谁知道如何解决这个问题?
MediaPlayer bsound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
MediaPlayer bsound = MediaPlayer.create(this, R.raw.sample);
bsound.setLooping(true); // Set looping
bsound.setVolume(100,100);
bsound.start();
TextView txt = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt.setTypeface(font);
TextView txt1 = (TextView) findViewById(R.id.button1);
Typeface font1 = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt1.setTypeface(font1);
}
public void list(View view) {
Intent intent = new Intent(this, Menus.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
答案 0 :(得分:2)
尝试暂停和恢复MediaPlayer:
MediaPlayer bsound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
bsound = MediaPlayer.create(this, R.raw.sample);
bsound.setLooping(true); // Set looping
bsound.setVolume(100, 100);
bsound.start();
TextView txt = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt.setTypeface(font);
TextView txt1 = (TextView) findViewById(R.id.button1);
Typeface font1 = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt1.setTypeface(font1);
}
@Override
protected void onPause() {
if (bsound.isPlaying()) {
bsound.pause();
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
bsound.start();
}
是的,您没有初始化MediaPlayer bsound
字段。改变这一行:
MediaPlayer bsound = MediaPlayer.create(this, R.raw.sample);
到此:
bsound = MediaPlayer.create(this, R.raw.sample);
答案 1 :(得分:0)
您应该为您的活动实施onStop()
并停止使用此方法播放音乐。只要您的活动结束,这将停止它。在这里查看更多信息
http://developer.android.com/training/basics/activity-lifecycle/pausing.html
答案 2 :(得分:0)
在activity中的onPause()中调用pause()方法,并从onStart()方法开始。
答案 3 :(得分:0)
复制下面的代码并将AndroidManifest.xml文件粘贴到First Activity Tag。
下<activity
android:name="com.FirstActivity"
android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
android:excludeFromRecents="true">
</activity>
此外,在AndroidManifest.xml文件
中的活动标记下的所有代码中添加以下代码 android:finishOnTaskLaunch="true"