Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 關於提高第三方app的service優先級

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

編輯:關於Android編程

本博客只要沒有注明“轉”,那麼均為原創,轉貼請注明本博客鏈接鏈接


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

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved