[英]How to make a service sticky in memory even if activity is destroyed?
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. 我有一个Mediaplayer,它是在服务内部实现的,并且从我的android应用中的活动中调用startSerivce(),而且我还显示了来自服务的通知以使用户保持更新。
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. 这是问题所在:当我按返回按钮并关闭活动并打开手机屏幕时,音乐播放器服务将播放1〜2分钟,然后它将关闭该服务并停止音乐。
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 : 在我的服务中,我有以下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? 如何防止android杀死我的服务?
note : my MediaPlayer is Vitamio just in case if Vitamio is the problem. 注意:我的MediaPlayer是Vitamio,以防万一Vitamio出了问题。
add permission in manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />
and your onStartCommand method should look like this: 在清单中添加权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
,您的onStartCommand方法应如下所示:
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 有关https://developer.android.com/training/scheduling/wakelock.html#cpu的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.