android 關於提高app的進程service優先級

基本上大家都知道提高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

<!-- 爲了消去加上android:priority="1000"後出現的警告信息,可以設置android:exported屬性,指示該服務是否能夠被其他應用程序組件調用或跟它交互 -->
<service android:name="com.example.helloandroid.weatherforecast.service.UpdateWidgetService"
         android:exported="false" >
 <!-- 爲防止Service被系統回收,可以通過提高優先級解決,1000是最高優先級,數字越小,優先級越低 -->
     <intent-filter android:priority="1000"></intent-filter>
</service>

這個方法我用了,但是沒什麼卵用,不知道是不是那個地方需要一起配合,希望瞭解的大神能幫忙解釋一下。

4.setForeground

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

讓service免於非難的辦法是提高它的重要性,在官方文檔中已經說明進程有五個級別,其中前臺進程最重要,所以最後被殺死。
進程的oom_adj值也就代表了它的優先級。oom_adj值越高代表該進程優先級越低:
1.前臺進程( FOREGROUND_APP) 0
2.可視進程(VISIBLE_APP ) 1
3.次要服務進程(SECONDARY_SERVER ) 2
4.後臺進程 (HIDDEN_APP) 7
5.內容供應節點(CONTENT_PROVIDER) 14
6.空進程(EMPTY_APP) 15
這裏只說如何使用startForeground將service設置爲前臺進程
在service的onCreate中

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。

如果不需要一直存在的話
在service的onDestroy中加上 stopForeground(true); 不然一直佔着資源也不太合適哈。

另外值得注意的是這個方法是在版本1.0以後的,強制和 notification 綁定,網上有的說 startForeground的第一個參數置爲 0 就不顯示通知欄了,我想說的是,如果置爲0 ,這個方法就然並卵了,而且這樣寫完之後也不會出現通知欄。(親測)

然後用命令查一下adb shell cat/proc/你的進程號/oom_adj 切到後臺的程序果然變成了 1 有木有。

本文是根據http://www.2cto.com/kf/201406/311442.html 完善的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章