2015-08-29 31 views
0

我有一個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 
} 

和我serivce裏面我有以下的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; 
} 

如何防止機器人殺死我的服務?

注意:如果Vitamio是問題,我的MediaPlayer是Vitamio以防萬一。在清單

+0

「服務將1〜2分鐘打那麼它會關閉該服務並停止音樂「 - 更可能的是,該設備只是進入睡眠模式。 – CommonsWare

+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

相關問題