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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.