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

版权声明:转载请注明出处。 https://blog.csdn.net/rentee/article/details/77005547

Android O正式版发布在即,公司的应用也开始适配Android O,测试发现,Android O原生桌面上,按照传统创建快捷方式的形式,是不会产生快捷方式的。

PS:以下示例的源码请参阅:https://github.com/OptimusPrimeRen/AndroidOShortcut


传统方式如下:

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,可以对桌面久按应用图标弹出的快捷方式进行管理。使用可以参见Loader’s Blog的这篇文章:http://blog.csdn.net/qibin0506/article/details/52878690

但是,Android 7.1上,直接往桌面上添加快捷方式(如:360清理往桌面上添加一个快捷清理内存的图标)依然是使用上面说到的这种旧方式,但是Android O上,Google应该是想通过比较统一的接口来管理桌面快捷方式了,所以摒弃了这种形式,转而使用ShortcutManager进行管理。所以API 26上,ShortcutManager新增了对Pinned Shortcuts(固定快捷方式) 的管理。
官文镇楼:https://developer.android.com/reference/android/content/pm/ShortcutManager.html
没法翻墙的童鞋,可以参见以下截取的相关选段。

官文:
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); //action必须设置,不然报错

        ShortcutInfo info = new ShortcutInfo.Builder(context, "The only id")
                .setIcon(Icon.createWithResource(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());
    }

}

在Android O模拟器上,调用此方法后,系统会弹出如图提示框:
添加桌面快捷方式提示框

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

桌面快捷方式图标

哈哈,快捷方式图标的右下角会添加上应用的图标。

回调用到的Receiver:

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

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

PS:使用市场上比较流行的第三方桌面,如果桌面端没有做适配,requestPinShortcut方法的调用不会出现弹框和onReceive的回调。


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

然后在Android O的模拟器上跑,发现没效果,Debug跟进一下,发现ShortcutManagerCompat.isRequestPinShortcutSupported直接给我返回了个false,于是跟进其源码实现:

public static boolean isRequestPinShortcutSupported(@NonNull Context context) {
    if (BuildCompat.isAtLeastO()) {
        return ShortcutManagerCompatApi26.isRequestPinShortcutSupported(context);
    }

    if (ContextCompat.checkSelfPermission(context, INSTALL_SHORTCUT_PERMISSION)
        != PackageManager.PERMISSION_GRANTED) {
        return false;
    }
    for (ResolveInfo info : context.getPackageManager().queryBroadcastReceivers(
            new Intent(ACTION_INSTALL_SHORTCUT), 0)) {
        String permission = info.activityInfo.permission;
        if (TextUtils.isEmpty(permission) || INSTALL_SHORTCUT_PERMISSION.equals(permission)) {
            return true;
        }
    }
    return false;
}

BuildCompat.isAtLeastO返回false。跟进此方法:

public static boolean isAtLeastO() {
    return !"REL".equals(VERSION.CODENAME)
            && ("O".equals(VERSION.CODENAME) || VERSION.CODENAME.startsWith("OMR"));
}

好吧,可能由于Android O还未出正式版本,模拟器的VERSION.CODENAME是REL……

虽然暂时无法通过Compact包偷点懒,但它的实现还是可以参考的。
具体每个方法的实现就不多说了,这里贴下另外两个方法的源码:

public static boolean requestPinShortcut(@NonNull final Context context,
        @NonNull ShortcutInfoCompat shortcut, @Nullable final IntentSender callback) {
    if (BuildCompat.isAtLeastO()) {
        return ShortcutManagerCompatApi26.requestPinShortcut(context, shortcut, callback);
    }

    if (!isRequestPinShortcutSupported(context)) {
        return false;
    }
    Intent intent = shortcut.addToIntent(new Intent(ACTION_INSTALL_SHORTCUT));

    // If the callback is null, just send the broadcast
    if (callback == null) {
        context.sendBroadcast(intent);
        return true;
    }

    // Otherwise send the callback when the intent has successfully been dispatched.
    context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                callback.sendIntent(context, 0, null, null, null);
            } catch (IntentSender.SendIntentException e) {
                // Ignore
            }
        }
    }, null, Activity.RESULT_OK, null, null);
    return true;
}
public static Intent createShortcutResultIntent(@NonNull Context context,
        @NonNull ShortcutInfoCompat shortcut) {
    Intent result = null;
    if (BuildCompat.isAtLeastO()) {
        result = ShortcutManagerCompatApi26.createShortcutResultIntent(context, shortcut);
    }
    if (result == null) {
        result = new Intent();
    }
    return shortcut.addToIntent(result);
}

至此,应用如何添加一个桌面快捷方式已经讲完。至于桌面类软件如何适配这些接口,有待进一步探讨。

猜你喜欢

转载自blog.csdn.net/rentee/article/details/77005547