Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 桌面快捷方式原理與多 ROM 適配全解

編輯:Android 資訊

桌面快捷方式是 Android 設備上極具價值的流量入口,也正因如此,各種應用都在爭奪這塊陣地,甚至不惜以「流氓」手段佔據用戶桌面。

疊加上國內各大定制 ROM 與第三方 Launcher 的崛起,這場桌面之爭變得更加激烈。每傢伙都想把用戶留在自己的生態裡,於是應用不僅要搶入口,還得與各家 ROM 斗智斗勇。本文將從原理層面拆解快捷方式的完整生命週期,並給出適配多 ROM 的整合思路。

文中不少實現思路參考了這份分享:https://gist.github.com/waylife/437a3d98a84f245b9582,特此致謝。

一、標準做法:系統官方方案

先說前提:不同 Launcher 的形態差異很大。原生 Launcher 是兩層結構,桌面放快捷方式,進去後的應用列表放 Launch Icon;而以小米為代表的一批定制 ROM 參考 iOS 風格,把 Launcher 改為一層,直接展示所有應用圖標。這個差異直接影響了後面的適配策略。

1.1 權限聲明

<!-- 添加快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<!-- 移除快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
<!-- 讀取桌面配置 -->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />

1.2 創建快捷方式

對應的 Action 常量:

public static final String ACTION_ADD_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";

通過發送廣播完成創建:

public static void addShortcut(Context context, Intent actionIntent, String name,
                               boolean allowRepeat, Bitmap iconBitmap) {
    Intent addShortcutIntent = new Intent(ACTION_ADD_SHORTCUT);
    // 是否允許重複創建
    addShortcutIntent.putExtra("duplicate", allowRepeat);
    // 快捷方式標題
    addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
    // 快捷方式圖標
    addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, iconBitmap);
    // 點擊後要啟動的 Intent
    addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, actionIntent);
    context.sendBroadcast(addShortcutIntent);
}

參數含義一目了然,但有一點務必留意:duplicate 這個字段本該用來控制是否允許重複創建,然而很多定制 ROM 並不識別它——這正是桌面上出現大量重複圖標的根源。

1.3 刪除快捷方式

public static final String ACTION_REMOVE_SHORTCUT = "com.android.launcher.action.UNINSTALL_SHORTCUT";

public static void removeShortcut(Context context, Intent actionIntent, String name) {
    Intent intent = new Intent(ACTION_REMOVE_SHORTCUT);
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
    intent.putExtra("duplicate", false);
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, actionIntent);
    context.sendBroadcast(intent);
}

關鍵約束是:EXTRA_SHORTCUT_INTENT 必須與創建時使用的完全一致,否則無法刪除成功。

二、從存儲原理理解適配

官方方案在國內環境下常常水土不服。要真正解決問題,得先弄清快捷方式的存儲機制。

2.1 快捷方式存在哪裡

所有快捷方式都記錄在 Launcher 的數據庫中。用 SQLite 工具打開 Launcher 的數據庫文件就能看到。

打開 Launcher.db 的 favorite 表,這裡就是快捷方式數據的落腳點:

幾個核心字段基本一看就懂:title 是名稱,intent 是點擊動作,iconResource 是圖標資源來源,icon 是圖標的二進制數據。

2.2 如何判斷快捷方式已存在

既然 duplicate 屬性在很多 ROM 上失效,那就換一條路:直接查詢 Launcher 數據庫。

public static boolean isShortCutExist(Context context, String title) {
    boolean result = false;
    try {
        ContentResolver cr = context.getContentResolver();
        Uri uri = getUriFromLauncher(context);
        Cursor c = cr.query(uri, new String[]{"title"}, "title=?",
                            new String[]{title}, null);
        if (c != null && c.getCount() > 0) {
            result = true;
        }
        if (c != null && !c.isClosed()) {
            c.close();
        }
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
    }
    return result;
}

上面這個版本只按標題匹配。更精確的做法是把 intent 也納入條件——因為不同應用完全可能生成同名快捷方式:

public static boolean isShortCutExist(Context context, String title, Intent intent) {
    boolean result = false;
    try {
        ContentResolver cr = context.getContentResolver();
        Uri uri = getUriFromLauncher(context);
        Cursor c = cr.query(uri, new String[]{"title", "intent"},
                            "title=? and intent=?",
                            new String[]{title, intent.toUri(0)}, null);
        if (c != null && c.getCount() > 0) {
            result = true;
        }
        if (c != null && !c.isClosed()) {
            c.close();
        }
    } catch (Exception ex) {
        result = false;
        ex.printStackTrace();
    }
    return result;
}

而 getUriFromLauncher 的作用是為 ContentResolver 拼出正確的 Uri。這段代碼也真實反映了 Android 版本碎片化帶來的困擾:

private static Uri getUriFromLauncher(Context context) {
    StringBuilder uriStr = new StringBuilder();
    String authority = LauncherUtil.getAuthorityFromPermissionDefault(context);
    if (authority == null || authority.trim().equals("")) {
        authority = LauncherUtil.getAuthorityFromPermission(
            context,
            LauncherUtil.getCurrentLauncherPackageName(context) + ".permission.READ_SETTINGS");
    }
    uriStr.append("content://");
    if (TextUtils.isEmpty(authority)) {
        int sdkInt = android.os.Build.VERSION.SDK_INT;
        if (sdkInt < 8) {
            uriStr.append("com.android.launcher.settings");
        } else if (sdkInt < 19) {
            uriStr.append("com.android.launcher2.settings");
        } else {
            uriStr.append("com.android.launcher3.settings");
        }
    } else {
        uriStr.append(authority);
    }
    uriStr.append("/favorites?notify=true");
    return Uri.parse(uriStr.toString());
}

需要注意的是,這種查詢方式主要對系統自帶桌面有效。第三方桌面如果沒有實現系統的響應約定,就無法通過這個途徑判斷,比如 GO 桌面。

2.3 為任意應用添加快捷方式

理解上面的思路後,我們就能主動為指定包名的應用創建快捷方式。做法是先用 PackageManager 找到目標應用的啟動 Activity、名稱與圖標,再發送安裝廣播:

public static boolean addShortcutByPackageName(Context context, String pkg) {
    String title = "unknown";
    String mainAct = null;
    int iconIdentifier = 0;

    PackageManager pkgMag = context.getPackageManager();
    Intent queryIntent = new Intent(Intent.ACTION_MAIN, null);
    queryIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    queryIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    queryIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);

    List<ResolveInfo> list = pkgMag.queryIntentActivities(queryIntent, PackageManager.GET_ACTIVITIES);
    for (int i = 0; i < list.size(); i++) {
        ResolveInfo info = list.get(i);
        if (info.activityInfo.packageName.equals(pkg)) {
            title = info.loadLabel(pkgMag).toString();
            mainAct = info.activityInfo.name;
            iconIdentifier = info.activityInfo.applicationInfo.icon;
            break;
        }
    }
    if (mainAct == null) {
        return false;   // 沒有找到啟動類
    }

    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
    shortcut.putExtra("duplicate", false);
    ComponentName comp = new ComponentName(pkg, mainAct);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, queryIntent.setComponent(comp));

    // 需要目標應用的上下文,才能按其資源 ID 找到圖標
    Context pkgContext = null;
    if (context.getPackageName().equals(pkg)) {
        pkgContext = context;
    } else {
        try {
            pkgContext = context.createPackageContext(pkg,
                Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    if (pkgContext != null) {
        Intent.ShortcutIconResource iconRes =
            Intent.ShortcutIconResource.fromContext(pkgContext, iconIdentifier);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
    }

    context.sendBroadcast(shortcut);
    return true;
}

三、權限兼容:不得不用的笨辦法

快捷方式的碎片化非常嚴重,照顧了這個 ROM 就顾不上另一個。原生 ROM 需要的是:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

而華為設備可能需要的是:

<uses-permission android:name="com.huawei.launcher3.permission.READ_SETTINGS" />
<uses-permission android:name="com.huawei.launcher3.permission.WRITE_SETTINGS" />

為了讓程序具備足夠的通用性,理論上只能把所有非原生 Launcher 的權限全部聲明一遍。聽起來荒謬,但這確實是過去一段時間裡最實際的辦法:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.launcher2.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher2.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.launcher3.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher3.permission.WRITE_SETTINGS" />
<uses-permission android:name="org.adw.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="org.adw.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="org.adwfreak.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="org.adwfreak.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="org.adw.launcher_donut.permission.READ_SETTINGS" />
<uses-permission android:name="org.adw.launcher_donut.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.htc.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.huawei.launcher2.permission.READ_SETTINGS" />
<uses-permission android:name="com.huawei.launcher2.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.huawei.launcher3.permission.READ_SETTINGS" />
<uses-permission android:name="com.huawei.launcher3.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.mylauncher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.mylauncher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.fede.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.fede.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.sec.android.app.twlauncher.settings.READ_SETTINGS" />
<uses-permission android:name="com.sec.android.app.twlauncher.settings.WRITE_SETTINGS" />
<uses-permission android:name="com.anddoes.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.anddoes.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.ebproductions.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.ebproductions.android.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.lge.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.lge.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.tencent.qqlauncher.permission.READ_SETTINGS" />
<uses-permission android:name="com.tencent.qqlauncher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.qihoo360.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.qihoo360.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="net.qihoo.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="net.qihoo.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.oppo.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.oppo.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="telecom.mdesk.permission.READ_SETTINGS" />
<uses-permission android:name="telecom.mdesk.permission.WRITE_SETTINGS" />
<uses-permission android:name="dianxin.permission.ACCESS_LAUNCHER_DATA" />

看到這一大串,你可能會擔心用戶安裝時會被權限列表嚇到。實際上不必過慮:這些大多數是各家 ROM 的私有權限,安裝時通常會被系統歸併顯示為原生 Launcher 的通用權限,例如「添加快捷方式」「修改桌面設置」,而不會逐條鋪開。

四、繞道方案:增加一個入口 Activity

既然快捷方式碎片化如此嚴重,還有另一條思路:在 Launcher 的應用列表中為 App 增加一個入口,本質上就是多註冊一個 Activity。

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name="com.hujiang.hj_shortcut_lib.HJShortcutActivity"
    android:theme="@style/Base.Theme.AppCompat.Dialog">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

問題在於:這個入口如何做到隨時顯示或隱藏?答案藏在 PackageManager 的組件開關裡。

public static void toggleFlowEntrance(Context context, Class launcherClass) {
    PackageManager packageManager = context.getPackageManager();
    ComponentName componentName = new ComponentName(context, launcherClass);
    int res = packageManager.getComponentEnabledSetting(componentName);
    if (res == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            || res == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
        // 隱藏圖標
        packageManager.setComponentEnabledSetting(componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
    } else {
        // 顯示圖標
        packageManager.setComponentEnabledSetting(componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
            PackageManager.DONT_KILL_APP);
    }
}

在 root 環境下,這套 API 可以修改任意應用的任意組件;而在普通情況下,對自身應用則擁有絕對權限。加上 DONT_KILL_APP 標志,切換過程不會殺死進程,用戶幾乎無感知。

五、開源封裝

前面梳理了幾條不同的入口引流的實現路徑。與其每個項目都重造一遍輪子,更實際的做法是把它們封裝成一個庫,讓上層業務盡可能忽略 ROM 差異。

項目地址:https://github.com/xuyisheng/ShortcutHelper

該庫當時仍在測試階段,還有若干適配問題待完善,歡迎提 issue 共同改進。

結語

需要清醒認識到的是:這種依賴私有約定與私有權限的玩法,本質上是在填補系統能力的空白,隨着 Android 版本演進與各家 ROM 收緊策略,其有效性會不斷下降。從長期看,把資源投入到常規的推送喚醒、深度鏈接與 Proper 的 shortcuts API 上,才是更穩妥的選擇。

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