由于Android版本碎片導致各種兼容問題,遂直接使用Support包下兼容管理類ShortcutManagercomat即可
首先確保獲取全權(quán)限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
8.0以下系統(tǒng)可能出現(xiàn)應(yīng)用未安裝的問題,在AndroidManifest文件里快捷方式啟動的頁面acitivity標簽里添加android:exported="true"
public static void addShortCutCompact(Context context) {
if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
Intent shortcutInfoIntent = new Intent(context, ShortcutActivity.class);
shortcutInfoIntent.setAction(Intent.ACTION_VIEW); //action必須設(shè)置,不然報錯
ShortcutInfoCompat info = new ShortcutInfoCompat.Builder(context, "id")
.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_launcher))
.setShortLabel("name")
.setIntent(shortcutInfoIntent)
.build();
//當添加快捷方式的確認彈框彈出來時,將被回調(diào),自定義Receiver
PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, ShortcutReceiver.class),PendingIntent.FLAG_UPDATE_CURRENT);
ShortcutManagerCompat.requestPinShortcut(context, info,
shortcutCallbackIntent.getIntentSender());
}
}