添加桌面快捷方式

private static final String NOTREPETABLE=“tecentmap”; //防止重复

public static boolean existShortcut(Context context) {
    try {
        ShortcutManager existShortcutMgr = (ShortcutManager) context.getSystemService(SHORTCUT_SERVICE);
        if (existShortcutMgr != null) {
            List<ShortcutInfo> shortcutInfoList = existShortcutMgr.getPinnedShortcuts();
            for(ShortcutInfo pinnedShortcut : shortcutInfoList) {
                if(pinnedShortcut.getId().equals(NOTREPETABLE)) {
                    return true;
                }
            }
        }
    }catch (RuntimeException e) {
        LogUtil.i(TAG, "Add shortcut exception get service error");
    }
    return false;
}
public static void addShortcut(@NonNull Context context){
    try {
        ShortcutManager  shortcutMgr = (ShortcutManager) context.getSystemService(SHORTCUT_SERVICE);
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setClass(context, MainActivity.class);
        ShortcutInfo build = new ShortcutInfo.Builder(context, NOTREPETABLE)
            .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))
            .setShortLabel(getString(R.string.scene_add_custom_content))
            .setIntent(intent)
            .build();
        if (shortcutMgr != null) {
            shortcutMgr.requestPinShortcut(build, null);
        }
    }catch (RuntimeException e) {
        LogUtil.i(TAG, "Add shortcut exception get service error");
    }
}

猜你喜欢

转载自blog.csdn.net/hongranzuoxiang/article/details/120019542