簡體   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