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" />
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.
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.
To start the service, call startService(intent) and to stop the service, call stopService(intent) .
put this line in yout activity
stopService(new Intent(this, BackgroundMusicService.class));
in onDestroy() method where you pressing the home button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With