Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android stop service when exit the app

Tags:

java

android

I'm creating a game application with background music.I used Android Service to play the background music because I wanted to run BGM while changing activities. my problem is,I have declared finish() in onPause method in each activity(I don't want to let the user to return & want to kill the activity).

so when I intent to other activity it calls onDestroy and stops the service. I want to stop the service exactly exit the app( pressing the home button )and want to go through activities with BGM and finish() in onPause().is this possible? or is there another solution?

public class BackgroundMusicService 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.topbgm);
        player.setLooping(true); // Set looping
        player.setVolume(100, 100);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;   
    }

    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();
        Log.i("service", "service killed");
    }

    @Override
    public void onLowMemory() {

    }
}

in manifest

<service android:name=".BackgroundMusicService" android:process=":remote" />
like image 842
Hassy31 Avatar asked Feb 13 '13 05:02

Hassy31


People also ask

How stop service when app is killed android?

First, the easiest way to do what you're trying to do is to launch an Android Broadcast when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart after that. Dear Dr Sabri Allani, If your Service is started by your app then actually your service is running on main process.

How do you stop a service app on android?

Therefore, the best way to stop the service is by calling stopService() in the onStop() method as shown below. You'll just need the context of the Activity to start service from a separate thread. Rest all implementation of Service will be the same.

How do I stop a service from activity?

To start the service, call startService(intent) and to stop the service, call stopService(intent) .


1 Answers

put this line in yout activity

stopService(new Intent(this, BackgroundMusicService.class));

in onDestroy() method where you pressing the home button.

like image 103
kyogs Avatar answered Sep 18 '22 15:09

kyogs