0

我有一个媒体播放器,我在服务中实现了它,我从我的 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,以防万一出现问题。

4

1 回答 1

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

于 2015-08-29T17:07:11.907 回答