How to continue playing music in the background after the user uninstalls the application?

In Android, I use Service and MediaPlayer to play music. Music continues to play when I press the home button, but stops if I β€œbounce” the application.

How to continue playing music after debugging the application?

+7
android service android-service android-mediaplayer
source share
2 answers

Android media player code uses a service that contains a MediaPlayer object. This allows you to continue playing, even if activity is not in the foreground.

0
source share

You need to use Service.START_STICKY :

 public int onStartCommand(Intent intent, int flags, int startId) { mediaPlayer.start(); return Service.START_STICKY; } 

Service.START_STICKY : if this service process is killed while the system tries to recreate the service at startup.

Here is a complete example: https://github.com/Jorgesys/Android-Music-in-Background

 public class BackgroundSoundService extends Service { private static final String TAG = "BackgroundSoundService"; MediaPlayer player; public IBinder onBind(Intent arg0) { Log.i(TAG, "onBind()" ); return null; } @Override public void onCreate() { super.onCreate(); player = MediaPlayer.create(this, R.raw.jorgesys_song); player.setLooping(true); player.setVolume(100, 100); Toast.makeText(this, "Service started...", Toast.LENGTH_SHORT).show(); Log.i(TAG, "onCreate() , service started..."); } public int onStartCommand(Intent intent, int flags, int startId) { player.start(); return Service.START_STICKY; } public IBinder onUnBind(Intent arg0) { Log.i(TAG, "onUnBind()"); return null; } public void onStop() { Log.i(TAG, "onStop()"); } public void onPause() { Log.i(TAG, "onPause()"); } @Override public void onDestroy() { player.stop(); player.release(); Toast.makeText(this, "Service stopped...", Toast.LENGTH_SHORT).show(); Log.i(TAG, "onCreate() , service stopped..."); } @Override public void onLowMemory() { Log.i(TAG, "onLowMemory()"); } } 
0
source share

All Articles