Oreo創(chuàng)建app快捷方式兩種方式:
v7包:appcompat-v7:26.0.2
ShortcutManager requestPinShortcut()
LauncherActivity:點擊快捷方式啟動的Activity
shortcutId:快捷方式id
bitmap:Shortcut圖標(biāo)
shortcutTitle:Shortcut名稱
注意: 如果快捷方式已存在饰剥,則ShortcutInfo對象應(yīng)僅包含快捷方式的ID殊霞。否則,新的ShortcutInfo對象必須包含新快捷方式的ID汰蓉,意圖和短標(biāo)簽绷蹲。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//1
ShortcutManager shortcutManager = (ShortcutManager) mContext.getSystemService(Context.SHORTCUT_SERVICE);
if (shortcutManager.isRequestPinShortcutSupported()) {
Intent launcherIntent= new Intent(mContext, LauncherActivity.class);
launcherIntent.setAction(Intent.ACTION_VIEW);
ShortcutInfo info = new ShortcutInfo.Builder(mContext, shortcutId)
.setIcon(Icon.createWithBitmap(bitmap))
.setShortLabel(shortcutTitle)
.setIntent(launcherIntent)
.build();
//當(dāng)添加快捷方式的確認(rèn)彈框彈出來時,將被回調(diào)
PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext, ShortcutReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
}
//2
if (ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
Intent launcherIntent = new Intent(mContext, LauncherActivity.class);
launcherIntent.setAction(Intent.ACTION_VIEW);
ShortcutInfoCompat info = new ShortcutInfoCompat.Builder(mContext, shortcutId)
.setIcon(bitmap)
.setShortLabel(shortcutTitle)
.setIntent(launcherIntent)
.build();
//當(dāng)添加快捷方式的確認(rèn)彈框彈出來時古沥,將被回調(diào)
PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext, ShortcutReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
ShortcutManagerCompat.requestPinShortcut(mContext, info, shortcutCallbackIntent.getIntentSender());
}
ShortcutReceiver:回調(diào)
清單聲明的接收器來接收回調(diào)瘸右,android:exported="false"
public class ShortcutReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
/**
* Android 7.1及以下 添加桌面
*/
public static final String ACTION_ADD_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
public void addShortcutBelowAndroidN(Context context) {
Intent addShortcutIntent = new Intent(ACTION_ADD_SHORTCUT);
// 不允許重復(fù)創(chuàng)建,不是根據(jù)快捷方式的名字判斷重復(fù)的
addShortcutIntent.putExtra("duplicate", false);
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Name");
//圖標(biāo)
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.mipmap.ic_shortcut));
// 設(shè)置關(guān)聯(lián)程序
Intent launcherIntent = new Intent();
launcherIntent.setClass(context, ShortcutActivity.class);
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
// 發(fā)送廣播
context.sendBroadcast(addShortcutIntent);
}