Android开发:应用启动后自动创建桌面快捷方式(三星机常见)

public class ShortcutUtil {

    public static void createShortCut(Activity act, int iconResId,
                                      int appnameResId) {
        // com.android.launcher.permission.INSTALL_SHORTCUT
        boolean installShortcut = hasShortcut(act);
        Log.i("main", "installShortcut:" + installShortcut);
        if (installShortcut) {
            return;
        }
        Intent shortcutintent = new Intent(
                "com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允许重复创建
        shortcutintent.putExtra("duplicate", false);
        // 需要现实的名称
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                act.getString(appnameResId));
        // 快捷图片
        Parcelable icon = Intent.ShortcutIconResource.fromContext(
                act.getApplicationContext(), iconResId);
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        // 点击快捷图片,运行的程序主入口
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                new Intent(act.getApplicationContext(), act.getClass()));
        // 发送广播
        act.sendBroadcast(shortcutintent);
    }

    public static boolean hasShortcut(Activity activity) {
        String url = "";
        url = "content://" + getAuthorityFromPermission(activity, "com.android.launcher.permission.READ_SETTINGS")
                + "/favorites?notify=true";
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse(url), new String[] { "title", "iconResource" }, "title=?", new String[] { activity.getString(R.string.app_name).trim() }, null);
        if (cursor != null && cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        return false;
    }

    private static String getAuthorityFromPermission(Activity context, String permission) {
        if (permission == null)
            return null;
        List packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs != null) {
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission))
                            return provider.authority;
                        if (permission.equals(provider.writePermission))
                            return provider.authority;
                    }
                }
            }
        }
        return null;
    }
}

权限

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

感谢:http://www.51itong.net/android-9787.html

你可能感兴趣的:(Android,学习笔记)