My background music service in Android app keeps o

2019-09-14 00:24发布

问题:

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() {

}
}

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!

回答1:

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;
    }

Hope this helps you.