5

背景

Android O 对快捷方式的工作方式进行了各种更改:

https://developer.android.com/preview/behavior-changes.html#as

问题

根据 Android O 最近的变化,创建快捷方式的广播意图被完全忽略:

https://developer.android.com/reference/android/content/Intent.html#ACTION_CREATE_SHORTCUT https://developer.android.com/preview/behavior-changes.html#as

com.android.launcher.action.INSTALL_SHORTCUT 广播不再对您的应用产生任何影响,因为它现在是私有的隐式广播。相反,您应该使用 ShortcutManager 类中的 requestPinShortcut() 方法创建应用快捷方式。

例如,这意味着无论您制作了哪个应用程序或用户拥有哪个启动器,此代码都将不再工作:

private void addShortcut(@NonNull final Context context) {
    Intent intent = new Intent().putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(context, MainActivity.class).setAction(Intent.ACTION_MAIN))
            .putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut")
            .putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, ShortcutIconResource.fromContext(context, R.mipmap.ic_launcher))
            .setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    context.sendBroadcast(intent);
}

目前,即使是 Play 商店本身也无法创建应用程序的快捷方式(至少在当前版本中:80795200)。它只是没有做任何事情,即使对谷歌的启动器也是如此。

问题

虽然我非常反对 API 的这种更改(并在此处此处此处写过有关它的内容) ,但我想知道如何才能使其正常工作。

我知道有一个使用requestPinShortcut的 API ,但这需要应用程序以 Android O 为目标,这意味着必须进行更多更改以确保应用程序在那里工作。

我的问题是:假设您的应用程序以 Android API 25 为目标,您如何在 Android O 上创建快捷方式?是否可以通过使用较新 API 的反射来实现?如果是这样,怎么做?

4

2 回答 2

6

似乎我永远都在打败它,但是......

if(Build.VERSION.SDK_INT < 26) {
    ...
}
else {
    ShortcutManager shortcutManager
        = c.getSystemService(ShortcutManager.class);
    if (shortcutManager.isRequestPinShortcutSupported()) {
        Intent intent = new Intent(
            c.getApplicationContext(), c.getClass());
        intent.setAction(Intent.ACTION_MAIN);
        ShortcutInfo pinShortcutInfo = new ShortcutInfo
            .Builder(c,"pinned-shortcut")
            .setIcon(
                Icon.createWithResource(c, R.drawable.qmark)
            )
            .setIntent(intent)
            .setShortLabel(c.getString(R.string.app_label))
            .build();
        Intent pinnedShortcutCallbackIntent = shortcutManager
            .createShortcutResultIntent(pinShortcutInfo);
        //Get notified when a shortcut is pinned successfully//
        PendingIntent successCallback
            = PendingIntent.getBroadcast(
                c, 0
                , pinnedShortcutCallbackIntent, 0
            );
        shortcutManager.requestPinShortcut(
            pinShortcutInfo, successCallback.getIntentSender()
        );
    }
}

正在为我工​​作。我知道 7.1 中发生了变化,不知道这是否适用于他们,我不知道上面提到的启动器问题。
这是在运行 Android 8.0.0 的三星 Galaxy Tab S3 上测试的。

我在github的主页上放了一个简单的应用程序,它只在自己的主页上安装一个快捷方式。它适用于 Android 8 之前和之后的版本。Android 8 之前的版本使用 sendBroadcast 方法,之后创建固定快捷方式。

于 2018-09-17T18:34:05.287 回答
5

正确的方法是调用requestPinShortcut方法。您不需要以android O为目标,但您至少需要将SDK编译为26。编译SDK和目标SDK是两个不同的东西。

于 2017-06-25T12:09:13.683 回答