创建方法:
/**@param context 当前content@param targetClass 快捷图标打开的界面@param backClass 打开后按返回键返回的界面@param shortCutId shortCut 唯一id@param shortCutIcon 桌面上显示的图标@param shortCutLabel 桌面图标下方显示的文字*/public static void AddShortCut(Context context, Class targetClass, Class backClass, String shortCutId, int shortCutIcon, String shortCutLabel) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported()) {Intent shortcutInfoIntent = new Intent(context, targetClass);shortcutInfoIntent.setAction(Intent.ACTION_VIEW); ShortcutInfo info = new ShortcutInfo.Builder(context, shortCutId).setIcon(Icon.createWithResource(context, shortCutIcon)) .setShortLabel(shortCutLabel) .setIntent(shortcutInfoIntent) .build(); PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, backClass), PendingIntent.FLAG_UPDATE_CURRENT); shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());}}else{ToastUtils.show("设备不支持在桌面创建快捷图标!");}}
调用:
//长按创建桌面快捷图标
dicBtn.setOnLongClickListener(v -> { Utils.AddShortCut(getContext(), DictionaryActivity.class, MainActivity.class, "shorcut_dictionary", R.drawable.shorcut_dictionary, getResources().getString(R.string.shorcut_dictionary));return true;
});