即使关闭应用程序,我在Android应用程序中的背景音乐服务仍可以继续播放 [英] My background music service in Android app keeps on playing even when I close the app
问题描述
我正在使用后台服务在其所有活动中为我的应用程序运行背景音乐!问题是,当该应用运行时,它可以正常运行,但是当我关闭它时,它会继续播放音乐,直到从设备上将其卸载为止!
I'm using a background service to run a background music for my app in all of it's activities! The issue is that when the app run, it works fine but when I close it it keeps on playing the music until I uninstall it from the device!
您认为这里的问题是什么?
What do you think the problem here?
这是我的后台服务中的代码:
Here is The code In my Background service:
/**
* Created by Naira on 12/5/2016.
*/
public class Background_music extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(50,50);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
player = null;
}
@Override
public void onLowMemory() {
}
}
这是我在第一个活动中将其作为Intent运行的代码:
An here the code in my first activity to run it as an Intent:
Intent svc=new Intent(this, Background_music.class);
startService(svc);
当然,我确实在清单中声明了它) 预先感谢!
And, of course I did declare it in my manifest =) Thanks in advance!
推荐答案
在MainActivity的onDestroy()
方法中,您必须停止服务.
In the onDestroy()
method of your MainActivity you have to stop the service.
@Override
protected void onDestroy() {
super.onDestroy();
if(isMyServiceRunning(Background_music.class))
{
stopService(new Intent(this, Background_music.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
希望这对您有所帮助.
这篇关于即使关闭应用程序,我在Android应用程序中的背景音乐服务仍可以继续播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!