本部落格只要沒有註明“轉”,那麼均為原創,轉貼請註明本部落格網站連結接
基本上大家都知道提高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/