Android Service—在前台運行服務

來源:互聯網
上載者:User

前台服務是哪些被認為使用者知道的並且在記憶體低的時候不允許系統殺死的服務。前台服務必須給狀態列提供一個通知,他被放到了“進行中中(Ongoing)”標題之下,這就意味著直到這個服務被終止或從前台刪除通知才能被解除。

例如,一個播放音樂的音樂播放器服務應該被設定在前台運行,因為使用者明確的知道它們的操作。狀態列中的通知可能指明了當前的歌曲,並且使用者啟動一個跟這個音樂播放器互動的Activity。

要讓你的服務在前台運行,需要調用startForeground()方法,這個方法需要兩個參數:一個唯一標識通知的整數和給狀態列的通知,如:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);

要從前台刪除服務,需要調用stopForeground()方法,這個方法需要一個布爾型參數,指示是否刪除狀態列通知。這個方法不終止服務。但是,如果你終止了正在啟動並執行前台服務,那麼通知也會被刪除。

注意:startForeground()和stopForeground()方法是在Android2.0(API Level 5)中引入的。為了在比較舊的平台版本中運行你的服務,你必須使用以前的setForeground()方法---關於如何提供向後的相容性,請看startForeground()方法文檔。

關於通知的更多資訊,請看“建立狀態列通知(Creating Status Bar Notifications)”

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.