本博客僅僅要沒有注明“轉”。那么均為原創,轉貼請注明本博客鏈接鏈接
基本上大家都知道提高service優先級能夠在非常大程度上讓你的service免於由於內存不足而被kill,當然系統僅僅是在此時先把優先級低的kill掉。假設內存還是不夠,也會把你的service干掉的。只是如今的機器不像幾年前了,基本上不會發生那種情況。
先來看看網上常見的錯誤方法:
1.android:persistent="true"
對第三方app無效,以下是官方說明
-
android:persistent
-
Whether 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;最后。我們能夠使用以下命令看看手機中的哪些應用這么干了,你在平時使用的時候是不是他們存活時間最長。最不easy被系統干掉
dumpsys notification
轉貼請保留以下鏈接
本人blog地址