Disabling Android when exiting the application

I am creating a game application with background music. I used the Android service to play background music because I wanted to start BGM when changing actions. my problem is that I declared finish () in the onPause method in every action (I don't want the user to return and want to kill the action).

therefore, when I intend to use another activity, it calls onDestroy and stops the service. I want the service to completely leave the application (by clicking the "home" button), and you want to perform actions with BGM and complete () in onPause (). Is it 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" /> 
+8
java android
source share
3 answers

put this line in yout activity

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

in onDestroy () when you press the home button.

+15
source share

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

add this to your onPause() method and onDestroy() method in your main action. Because if you press the Home button, the application will be in the background for random time, and the onDestroy() method will not be called as soon as you hide the application. The best way to do this is to introduce the onPause() method. onPause() method is called when your application activity is not the main activity.

+2
source share

Override the onUnbind (Intent intenet) method in the service

0
source share

All Articles