繁体   English   中英

即使活动被破坏,如何使服务保持在内存中?

[英]How to make a service sticky in memory even if activity is destroyed?

我有一个Mediaplayer,它是在服务内部实现的,并且从我的android应用中的活动中调用startSerivce(),而且我还显示了来自服务的通知以使用户保持更新。

这是问题所在:当我按返回按钮并关闭活动并打开手机屏幕时,音乐播放器服务将播放1〜2分钟,然后它将关闭该服务并停止音乐。

我的活动代码:

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

在我的服务中,我有以下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;
}

如何防止android杀死我的服务?

注意:我的MediaPlayer是Vitamio,以防万一Vitamio出了问题。

在清单中添加权限: <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;
}

有关https://developer.android.com/training/scheduling/wakelock.html#cpu的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM