Android创建桌面快捷方式(兼容Android 8.0)

在Android O原生桌面上,按照传统创建快捷方式的形式,是不会产生快捷方式的。

传统方式如下:

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);

    // 不允许重复创建,不是根据快捷方式的名字判断重复的
    addShortcutIntent.putExtra("duplicate", false);

    addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Name");

    //图标
    addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.mipmap.ic_shortcut));

    // 设置关联程序
    Intent launcherIntent = new Intent();
    launcherIntent.setClass(context, ShortcutActivity.class);
    addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);

    // 发送广播
    context.sendBroadcast(addShortcutIntent);
}

ShortCutManager

从Android 7.1(API 25)开始,新增了ShortcutManager,可以对桌面久按应用图标弹出的快捷方式进行管理。

但是,Android 7.1上直接往桌面上添加快捷方式依然是使用上面说到的这种旧方式,但是Android O上,Google应该是想通过比较统一的接口来管理桌面快捷方式了,所以摒弃了这种形式,转而使用ShortcutManager进行管理。所以API 26上,ShortcutManager进行管理。所以API 26上,ShortcutManager新增了对Pinned Shortcuts(固定快捷方式)的管理。

官文:
Apps can pin an existing shortcut (either static or dynamic) or an entirely new shortcut to a supported launcher programatically using requestPinShortcut(ShortcutInfo, IntentSender). You pass two arguments into this method:

A ShortcutInfo object – If the shortcut already exists, this object should contain only the shortcut’s ID. Otherwise, the new ShortcutInfo object must contain an ID, an intent, and a short label for the new shortcut.
A PendingIntent object – This intent represents the callback that your app receives if the shortcut is successfully pinned to the device’s launcher.

Note: If the user doesn’t allow the shortcut to be pinned to the launcher, the pinning process fails, and the Intent object that is passed into this PendingIntent object isn’t executed.

Note: Due to background execution limits introduced in Android O, it’s best to use a manifest-declared receiver to receive a callback.
Also, to prevent other apps from invoking the receiver, add the attribute assignment android:exported=”false” to the receiver’s manifest entry.

Note: As you add logic in your app to make requests to pin shortcuts, keep in mind that not all launchers support pinning of shortcuts. To determine whether your app can complete this process on a particular device, check the return value of isRequestPinShortcutSupported(). Based on this return value, you might decide to hide the option in your app that allows users to pin a shortcut.

Note: See also the support library APIs isRequestPinShortcutSupported(Context) and requestPinShortcut(Context, ShortcutInfoCompat, IntentSender), which works on Android versions lower than O by falling back to the deprecated private intent com.android.launcher.action.INSTALL_SHORTCUT.

译:
应用程序可以使用requestPinShortcut(ShortcutInfo,IntentSender)将现有的快捷方式(静态或动态)或全新的快捷方式固定到支持的启动器。你通过这个方法的两个参数:

ShortcutInfo对象 - 如果快捷方式已存在,则该对象应仅包含快捷方式的ID。否则,新的ShortcutInfo对象必须包含新快捷方式的ID,意图和短标签。
PendingIntent对象 - 此意图表示如果快捷方式成功固定到设备的启动器,您的应用程序将收到回调。

注意:如果用户不允许将快捷方式固定在启动器上,则固定进程将失败,并且未执行传入此PendingIntent对象的Intent对象。

注意:由于Android O中引入的后台执行限制,最好使用清单声明的接收器来接收回调。
另外,为了防止其他应用程序调用接收器,将属性赋值android:exported =“false”添加到接收者的清单条目中。

注意:当您在应用程序中添加逻辑以引导快捷方式时,请记住,并非所有启动器都支持固定快捷方式。 要确定您的应用程序是否可以在特定设备上完成此过程,请检查isRequestPinShortcutSupported()的返回值。 根据此返回值,您可以决定隐藏您应用程序中允许用户固定快捷方式的选项。

注意:另请参见支持库API isRequestPinShortcutSupported(Context)和requestPinShortcut(Context,ShortcutInfoCompat,IntentSender),它可以在低于O的Android版本上运行,因为它们回落到不推荐使用的私有意图com.android.launcher.action.INSTALL_SHORTCUT。

ShortcutManager类在API level 26上,增加了对isRequestPinShortcutSupported、requestPinShortcut、createShortcutResultIntent三个方法。说明如下:

1.isRequestPinShortcutSupported

官文:
Return TRUE if the app is running on a device whose default launcher supports requestPinShortcut(ShortcutInfo, IntentSender).

The return value may change in subsequent calls if the user changes the default launcher app.

Note: See also the support library counterpart isRequestPinShortcutSupported(Context), which supports Android versions lower than O using the legacy private intent com.android.launcher.action.INSTALL_SHORTCUT.

译:
如果默认桌面支持requestPinShortcut(ShortcutInfo,IntentSender)方法,则返回TRUE。

如果用户更改默认启动程序应用程序,返回值可能会在后续调用中更改。

注意:另请参见支持库对应的isRequestPinShortcutSupported(Context),在低于O的Android版本,它支持使用旧的私有意图com.android.launcher.action.INSTALL_SHORTCUT。

2.requestPinShortcut

官文:
Request to create a pinned shortcut. The default launcher will receive this request and ask the user for approval. If the user approves it, the shortcut will be created, and resultIntent will be sent. If a request is denied by the user, however, no response will be sent to the caller.

Only apps with a foreground activity or a foreground service can call this method. Otherwise, it’ll throw IllegalStateException.

It’s up to the launcher to decide how to handle previous pending requests when the same package calls this API multiple times in a row. One possible strategy is to ignore any previous requests.

Note: See also the support library counterpart requestPinShortcut(Context, ShortcutInfoCompat, IntentSender), which supports Android versions lower than O using the legacy private intent com.android.launcher.action.INSTALL_SHORTCUT.

译:
请求创建固定的快捷方式。默认启动器将收到该请求,并要求用户批准。如果用户批准,将创建快捷方式,并且将发送resultIntent。但是,如果请求被用户拒绝,则不会向呼叫者发送任何响应。

只有具有前台活动或前台服务的应用程序才能调用此方法。否则,它将抛出IllegalStateException。

当同一个软件包连续多次调用该API时,由开发人员决定如何处理以前的待处理请求。一个可能的策略是忽略任何先前的请求。

注意:另请参见支持库对应件requestPinShortcut(Context,ShortcutInfoCompat,IntentSender),在低于O的Android版本,它支持使用旧的私有意图com.android.launcher.action.INSTALL_SHORTCUT。

3.createShortcutResultIntent

官文:
Returns an Intent which can be used by the default launcher to pin a shortcut containing the given ShortcutInfo. This method should be used by an Activity to set a result in response to ACTION_CREATE_SHORTCUT.

译:
返回默认启动器可以使用的Intent来固定包含给定的ShortcutInfo的快捷方式。 Activity应该使用此方法来设置响应ACTION_CREATE_SHORTCUT的结果。

@RequiresApi(api = Build.VERSION_CODES.O)
public static void addShortCut(Context context) {
      ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
      if(shortcutManager.isRequestPinShortcutSupported()) {
          Intent shortcutInfoIntent = new Intent(context, ShortcutActivity.class);
          shortcutInfoIntent.setAction(Intent.ACTION_VIEW);
          ShortcutInfo info = new ShortcutInfo.Builder(context, "The only id")
               .setIcon(Icon.createWithResources(context, R.mipmap.ic_shortcut))
               .setShortLabel("Short Label")
               .setIntent(shortcutInfoIntent);
               .build();
          //当添加快捷方式的确认弹框弹出来时,将被回调
          PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, MyReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
        shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
      }
}
image

根据弹窗提示可以看出,可以通过拖动这个图标往桌面上添加快捷方式,可以通过点击自动添加按键,系统给你在桌面的默认位置上添加。

添加后,桌面上会出现如图所示的图标:


image

回调用到的Receiver:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "onReceive: ");
    }
}

打印log发现,onReceive如图官方文档所说,点击弹框自动添加按键后,会得到回调。但实践发现,如果桌面上已经添加了图标,当再次调用requestPinShortcut进行添加时,onReceive会在调用requestPinShortcut的时候,直接被回调,而且弹框也会弹出来。

ShortcutManagerCompat

在以上三个方法官方介绍中,官方提示我们,可以使用Android support库的ShortcutManagerCompat进行快捷方式的版本适配。于是,在build.gradle中添加依赖进行尝试:

compile 'com.android.support:appcompat-v7:26.+'
public static void addShortCutCompact(Context context) {
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
        Intent shortcutInfoIntent = new Intent(context, ShortcutActivity.class);
        shortcutInfoIntent.setAction(Intent.ACTION_VIEW); //action必须设置,不然报错

        ShortcutInfoCompat info = new ShortcutInfoCompat.Builder(context, "The only id")
                .setIcon(R.mipmap.ic_shortcut)
                .setShortLabel("Short Label")
                .setIntent(shortcutInfoIntent)
                .build();

        //当添加快捷方式的确认弹框弹出来时,将被回调
        PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, MyReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
        ShortcutManagerCompat.requestPinShortcut(context, info, shortcutCallbackIntent.getIntentSender());
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270