天天看點

android 關于提高第三方app的service優先級

本部落格隻要沒有注明“轉”,那麼均為原創,轉貼請注明本部落格連結連結

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

最後,我們可以使用下面指令看看手機中的哪些應用這麼幹了,你在平時使用的時候是不是他們存活時間最長,最不容易被系統幹掉

dumpsys notification
           

轉貼請保留以下連結

本人blog位址

http://su1216.iteye.com/

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