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

时间:2015-08-29 16:30:19

标签: android service vitamio

我有一个媒体播放器,我在服务中实现它,我从我的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杀死我的服务?

注意:如果Vitamio出现问题,我的MediaPlayer就是Vitamio。

1 个答案:

答案 0 :(得分:1)

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