2015-10-19 118 views
0

我試圖開發一個Android應用程序,它在屏幕上繪製一個浮動覆蓋圖,因爲它是通過聊天頭的Facebook Messenger完成的。Android服務經常停止並重新啓動

我已經創建了一個處理UI的Android服務。一切運行良好,但在某些設備上,該服務非常頻繁地停止,有時會在超過60秒後再次啓動。

我知道這是一個由Android系統定義的行爲,但我想知道是否有辦法讓我的服務達到最高優先級。這可能嗎?這種行爲會因我執行過程中的錯誤而變差嗎?

回答

1

一種選擇是使您的服務成爲「前臺服務」,如簡要說明in Android documentation。這意味着它會在狀態欄中顯示一個圖標和可能的一些狀態數據。引用:

前臺服務是一個被認爲是東西 用戶正在積極瞭解並因此不能對系統 候選人殺時內存不足的服務。前景服務必須提供狀態欄,它被放置在「持續」 標題下,這意味着,該通知不能被解僱除非 服務是停止或從前景除去 通知。

實際上,您只需修改服務的onStartCommand()方法即可設置通知並致電startForeGround()。這個例子是從Android文檔:

// Set the icon and the initial text to be shown. 
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); 
// The pending intent is triggered when the notification is tapped. 
Intent notificationIntent = new Intent(this, ExampleActivity.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
// 2nd parameter is the title, 3rd one is a status message. 
notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); 
// You can put anything non-zero in place of ONGOING_NOTIFICATION_ID. 
startForeground(ONGOING_NOTIFICATION_ID, notification); 

這實際上是建立一個通知的方式已過時,但想法是一樣反正即使你使用Notification.Builder

相關問題