Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android App 黑白名單機制實現

編輯:關於 Android 程式設計

Android 設備正常工作時,很多 Service 運行在後台,只有在系統記憶體不足時才會自動 kill 掉後台 Service。在 Android OTT 盒子專案中,由於網絡機頂盒運行內存僅 512M/1G,為提高系統流暢性,會在編譯固件時加入 App 黑白名單功能。

Android 系統開機後會發出開機廣播,我們可以在 App 中註冊一個 BootCompletedReceiver 來接收,並在 onReceive 中完成各項黑白名單的初始化配置:

 public class BootCompletedReceiverAML extends BroadcastReceiver {
    public static final String TAG = "BootCompletedReceiverAML";

    public void onReceive(Context context, Intent intent) {
        initScreenSaver();                     // 設置進入屏保的黑白名單
        initEnableRunningBackgroudComponents(); // 使能後台運行的 Service 白名單
        initEnableAutoRunningComponents();      // 開機自動運行的白名單
        initLauncherComponents();               // 開機 Launcher 白名單
    }

    // 設置進入屏保的黑白名單
    private void initScreenSaver() {
        Settings.System.putInt(mContext.getContentResolver(),
            Settings.System.BOOT_GUIDE_COMPLETED, 1);
        IDreamManager mDreamManager = IDreamManager.Stub.asInterface(
            ServiceManager.getService(DreamService.DREAM_SERVICE));
        ComponentName dream = new ComponentName("com.mipt.screensaver",
            "com.mipt.screensaver.ScreenSaverService");
        try {
            ComponentName[] dreams = { dream };
            mDreamManager.setDreamComponents(dream == null ? null : dreams);
        } catch (RemoteException e) { }
        String dreamEnableComponentNames =
            "com.skyworthdigital.filexplorer/com.skyworthdigital.weather.main";
        Settings.System.putString(mContext.getContentResolver(),
            Settings.System.DREAM_ENABLE_COMPONENT, dreamEnableComponentNames);
    }

    // 使能自動運行在後台的 Service 白名單
    private void initEnableRunningBackgroudComponents() {
        Settings.Secure.putString(mContext.getContentResolver(),
            Settings.Secure.ENABLE_RUNNING_BACKGROUD_COMPONENTS,
            "android/system/com.mipt/com.skyworth/com.google.android");
    }

    // 開機自動運行的白名單
    private void initEnableAutoRunningComponents() {
        Settings.Secure.putString(mContext.getContentResolver(),
            Settings.Secure.ENABLE_AUTO_LAUNCH_COMPONENTS,
            "com.android/android/system/com.mipt/com.skyworth");
    }

    // 開機 Launcher 白名單
    private void initLauncherComponents() {
        Settings.Secure.putString(mContext.getContentResolver(),
            Settings.Secure.ENABLE_LAUNCHER_COMPONENTS, "com.mipt.metro.launcher");
    }
}

其原理是:透過 Settings.System 與 Settings.Secure 中的自定義鍵值,把允許後台運行、開機自啟、進入屏保的應用包名配置成白名單。這些配置由定制固件中的系統服務讀取並據此管理應用,从而在內存有限的機頂盒上保證系統流暢。需要注意,這類 Settings.Secure 自定義項依賴定製 ROM 的支持,並非 Android 原生標準接口。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved