小知識-Android一個應用多個圖標的幾種實現方式

  • 引言

新需求我的應用將有多個ICON入口..最終選擇了 activity-alias , 其實實現多圖標有好幾種方式

1. 多Activity + intent-filter方式

因為launcher會掃描app中含有以下intent-filter屬性的標簽, 有的話就會將其添加到桌面.

所以只要在你想添加到桌面的activity下加上以下標簽即可.

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

2. activity-alias方式

上面第一種方式對于一個activity的要求是沒法做的, 只能通過多寫幾個入口Activity+ 跳轉參數的方式來解決, 而 activity-alias方式就可以很好解決該問題.

activity-alias中, android:name 就是你定義這個activity為什么名字, 你通過點擊這個圖標進入的話, 在代碼中

getIntent().getComponent().getClassName()

可以獲取到該名字, targetActivity 就是你點擊該圖標后的目標activity. 上面代碼是寫在目標activity里面的,獲取到的名字依然是我們定義的名字哦. 這樣就可以通過這個判斷是通過哪個入口進來的了.

<activity-alias
    android:name="@string/altman"
    android:exported="true"
    android:icon="@drawable/speech_01"
    android:label="@string/altman_app_name"
    android:screenOrientation="landscape"
    android:targetActivity="com.avatar.dialog.DialogActivity"
    android:theme="@style/DialogActivityTheme" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity-alias>

3. 網頁標簽-添加快捷方式

這只是針對特殊情形, 比如UC瀏覽器創建一個網頁標簽在桌面上,是向桌面應用(launcher)發送相關action的廣播,相關的action如下:

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

需要的權限:

<!-- 添加快捷方式 -->
<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" />

添加圖標

private void addShortcut(String name) {
       Intent addShortcutIntent = new Intent(ACTION_ADD_SHORTCUT);

       // 不允許重復創建
       addShortcutIntent.putExtra("duplicate", false);// 經測試不是根據快捷方式的名字判斷重復的
       // 應該是根據快鏈的Intent來判斷是否重復的,即Intent.EXTRA_SHORTCUT_INTENT字段的value
       // 但是名稱不同時,雖然有的手機系統會顯示Toast提示重復,仍然會建立快鏈
       // 屏幕上沒有空間時會提示
       // 注意:重復創建的行為MIUI和三星手機上不太一樣,小米上似乎不能重復創建快捷方式

       // 名字
       addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);

       // 圖標
       addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
               Intent.ShortcutIconResource.fromContext(MainActivity.this,
                       R.drawable.ic_launcher));

       // 設置關聯程序
       Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
       launcherIntent.setClass(MainActivity.this, MainActivity.class);
       launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

       addShortcutIntent
               .putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);

       // 發送廣播
       sendBroadcast(addShortcutIntent);
   }

本文作者:Anderson/Jerey_Jobs

博客地址 : http://jerey.cn/

簡書地址 : Anderson大碼渣

github地址 : https://github.com/Jerey-Jobs

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容