如何在Android上创建快捷方式 O,当定位不到的时候呢?

How to create shortcuts on Android O, when targetting less than it?

背景

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

The com.android.launcher.action.INSTALL_SHORTCUT broadcast no longer has any effect on your app, because it is now a private, implicit broadcast. Instead, you should create an app shortcut by using the requestPinShortcut() method from the ShortcutManager class.

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

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)。它只是什么都不做,甚至对 Google 的启动器也是如此。

问题

虽然我非常反对 API 的这一变化(并写下了它 here, here) and here,但我想知道如何才能让它继续发挥作用。

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

我的问题是: 假设您的应用针对 Android API 25,您如何在 Android O 上创建快捷方式?是否可以使用更新的 API 的反射?如果是,怎么做?

正确的方法是调用requestPinShortcut方法。你不需要target android O但是你至少需要编译SDK到26。编译SDK和target SDK是两个不同的东西。

看来我一直在打败这个,但是...

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 中有一些变化,不知道这是否适用于他们,我不知道上面提到的启动器问题。
这是在 Samsung Galaxy Tab S3 运行 Android 8.0.0.

上测试的

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