Android--创建快捷方式

需要权限:

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

调用方法:

ShortCut.create(this);
ShortCut代码如下:
public class ShortCut {
    /**
     * 是否存在快捷方式
     * @param context
     * @return
     */
    private static boolean isAddShortCut(Context context) {

        boolean isInstallShortcut = false;
        final ContentResolver cr = context.getContentResolver();

        int versionLevel = android.os.Build.VERSION.SDK_INT;
        String AUTHORITY = "com.android.launcher2.settings";

        // 2.2以上的系统的文件文件名字是不一样的
        if (versionLevel >= 8) {
            AUTHORITY = "com.android.launcher2.settings";
        } else {
            AUTHORITY = "com.android.launcher.settings";
        }

        final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");
        Cursor c = cr.query(CONTENT_URI,
                new String[] { "title", "iconResource" }, "title=?",
                new String[] { context.getString(R.string.app_name) }, null);

        if (c != null && c.getCount() > 0) {
            isInstallShortcut = true;
        }
        return isInstallShortcut;
    }

    /**
     * 添加快捷方式
     * @param context
     */
    private static void addShortCut(Context context) {

        Intent shortcut = new Intent(
                "com.android.launcher.action.INSTALL_SHORTCUT");
        // 设置属性
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources()
                .getString(R.string.app_name));
        ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(
                context.getApplicationContext(), R.drawable.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, iconRes);

        // 是否允许重复创建
        shortcut.putExtra("duplicate", false);

        // 设置桌面快捷方式的图标
        Parcelable icon = Intent.ShortcutIconResource.fromContext(context,
                R.drawable.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

        // 点击快捷方式的操作
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClass(context, AppListActivity.class);

        // 设置启动程序
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

        // 广播通知桌面去创建
        context.sendBroadcast(shortcut);
    }

    /**
     * 外部调用  创建快捷方式
     * @param context
     */
    public static void create(Context context) {
        if(context != null)
        {
            if(!isAddShortCut(context))
            {
                addShortCut(context);
            }
        }
    }

 

posted @ 2014-11-09 17:37  crane13  阅读(163)  评论(0编辑  收藏  举报