android 關於提高第三方app的service優先順序

來源:互聯網
上載者:User

本部落格只要沒有註明“轉”,那麼均為原創,轉貼請註明本部落格網站連結接


基本上大家都知道提高service優先順序可以在很大程度上讓你的service免於因為記憶體不足而被kill,當然系統只是在此時先把優先順序低的kill掉,如果記憶體還是不夠,也會把你的service幹掉的。不過現在的機器不像幾年前了,基本上不會發生那種情況。


先來看看網上常見的錯誤方法:


1.android:persistent="true"

對第三方app無效,下面是官方說明

android:persistentWhether or not the application should remain running at all times — " true" if it should, and " false" if not. The default value is " false". Applications should not normally set this flag; persistence mode is intended only for certain system applications.

2.onDestroy中重啟service

service被系統殺死的時候並不一定會執行onDestroy,拿什麼重啟

3.android:priority

service根本沒有這屬性

4.setForeground

這個是有效,但是網上的例子卻都是無效的原因是參數錯誤

讓service免於非難的辦法是提高它的重要性,在官方文檔中已經說明進程有五個層級,其中前台進程最重要,所以最後被殺死。

如何使之變成前台進程可以參閱官方文檔。

http://developer.android.com/guide/components/processes-and-threads.html

http://su1216.iteye.com/blog/1591699

這裡只說如何使用setForeground將service設定為前台進程

Notification notification = new Notification();notification.flags = Notification.FLAG_ONGOING_EVENT;notification.flags |= Notification.FLAG_NO_CLEAR;notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;service.startForeground(1, notification);
上面的三個屬性放到一起,值為0x62。
    /**     * Bit to be bitwise-ored into the {@link #flags} field that should be     * set if this notification is in reference to something that is ongoing,     * like a phone call.  It should not be set if this notification is in     * reference to something that happened at a particular point in time,     * like a missed phone call.     */    public static final int FLAG_ONGOING_EVENT      = 0x00000002;    /**     * Bit to be bitwise-ored into the {@link #flags} field that should be     * set if the notification should not be canceled when the user clicks     * the Clear all button.     */    public static final int FLAG_NO_CLEAR           = 0x00000020;    /**     * Bit to be bitwise-ored into the {@link #flags} field that should be     * set if this notification represents a currently running service.  This     * will normally be set for you by {@link Service#startForeground}.     */    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
最後,我們可以使用下面命令看看手機中的哪些應用這麼幹了,你在平時使用的時候是不是他們存活時間最長,最不容易被系統幹掉
dumpsys notification

轉貼請保留以下連結

本人blog地址

http://su1216.iteye.com/

http://blog.csdn.net/su1216/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.