Android 添加、移除和判断 桌面快捷方式图标


思路:

  Launcher为了应用程序能够定制自己的快捷图标,就注册了一个 BroadcastReceiver 专门接收其他应用程序发来的快捷图标定制信息。所以只需要根据该 BroadcastReceiver 构造出相对应的Intent并装入我们的定制信息,最后调用 sendBroadcast 方法就可以创建一个快捷图标了。

效果:

android 添加桌面小部件 安卓 添加桌面图标_android 添加桌面小部件

步骤:

  1. 创建快捷方式必须要有权限;
  2. 创建快捷方式的广播的 Intent 的 action 设置 com.android.launcher.action.INSTALL_SHORTCUT
  3. 删除快捷方式的广播的 Intent 的 action 设置 com.android.launcher.action.UNINSTALL_SHORTCUT
  4. 设置快捷方式的图片和名称等信息放在 Intent 中;

  需要添加的权限如下:

<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"/>


  核心代码为:


/**
 * 添加当前应用的桌面快捷方式
 *
 * @param context
 */
public static void addShortcut(Context context, int appIcon, String title) {
    Intent shortcut = new Intent(
            "com.android.launcher.action.INSTALL_SHORTCUT");

    Intent shortcutIntent = context.getPackageManager()
            .getLaunchIntentForPackage(context.getPackageName());
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    // 快捷方式名称
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
    // 不允许重复创建(不一定有效)
    shortcut.putExtra("duplicate", false);
    // 快捷方式的图标
    Parcelable iconResource = Intent.ShortcutIconResource.fromContext(context,
            appIcon);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);


    context.sendBroadcast(shortcut);
}

移除


/**
 * 删除当前应用的桌面快捷方式
 * !!!小米系统暂时没有效果!!!
 *
 * @param context
 */
public static void delShortcut(Context context, String title) {
    Intent shortcut = new Intent(
            "com.android.launcher.action.UNINSTALL_SHORTCUT");
    // 快捷方式名称
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
    Intent shortcutIntent = context.getPackageManager()
            .getLaunchIntentForPackage(context.getPackageName());
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    context.sendBroadcast(shortcut);
}