0

I have a mediaplayer which I implemented it inside service and I call startSerivce() from an activity in my android app, also I show a notification from my service to keep user updated.

Here is the problem : When I press back button and close activity and turn of the mobile's screen the musicplayer service will play for 1~2 minutes then it will close the service and stops the music.

my activity code :

public void onCreate(Bundle savedInstanceState) {
//some code above
Intent intentMPLS = new Intent(Splash.this, MediaPlayerLocalService.class);
    startService(intentMPLS);
    //some code below
}

and inside my serivce I have following for startForground :

public int onStartCommand(Intent intent, int flags, int startId) {

startForeground(PlayerNotification.NOTIFICATION_ID,
                PlayerNotification.getInstance(this, global).createServiceNotification(true));
//The PlayerNotification is cusotmized class to show notification
return START_STICKY;
}

How can I prevent android to kill my service?

note : my MediaPlayer is Vitamio just in case if Vitamio is the problem.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vahid Hashemi
  • 5,182
  • 10
  • 58
  • 88

1 Answers1

1

add permission in manifest: <uses-permission android:name="android.permission.WAKE_LOCK" /> and your onStartCommand method should look like this:

public int onStartCommand(Intent intent, int flags, int startId) {

startForeground(PlayerNotification.NOTIFICATION_ID,
                PlayerNotification.getInstance(this, global).createServiceNotification(true));
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyWakelockTag");
wakeLock.acquire();
//The PlayerNotification is cusotmized class to show notification
return START_STICKY;
}

more on https://developer.android.com/training/scheduling/wakelock.html#cpu

Yazazzello
  • 6,053
  • 1
  • 19
  • 21