如何使用ShortcutManager API为Android 7.1应用程序创建动态应用程序快捷方式?

pRa*_*NaY 8 android android-7.1-nougat android-appshortcut

在Android 7.1中,开发人员可以创建AppShortCut.

我们可以用两种方式创建快捷方式:

  1. 使用资源(XML)文件的静态快捷方式.
  2. 使用ShortcutManagerAPI的动态快捷方式.

那么如何ShortcutManager动态创建快捷方式呢?

pRa*_*NaY 10

使用ShortcutManager,我们可以通过以下方式创建app动态应用程序快捷方式

ShortcutManager shortcutManager;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        shortcutManager = getSystemService(ShortcutManager.class);
        ShortcutInfo shortcut;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
            shortcut = new ShortcutInfo.Builder(this, "second_shortcut")
                    .setShortLabel(getString(R.string.str_shortcut_two))
                    .setLongLabel(getString(R.string.str_shortcut_two_desc))
                    .setIcon(Icon.createWithResource(this, R.mipmap.ic_launcher))
                    .setIntent(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://www.google.co.in")))
                    .build();
            shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));
        }


    }
Run Code Online (Sandbox Code Playgroud)

字符串资源:

<string name="str_shortcut_two">Shortcut 2</string>
<string name="str_shortcut_two_desc">Shortcut using code</string>
Run Code Online (Sandbox Code Playgroud)

开发人员还可以使用ShortcutManager以下方法执

应用快捷方式

检查应用程序快捷方式的 Github示例

检查https://developer.android.com/preview/shortcuts.htmlShortcutManager 以获取更多信息.


Sun*_*thy 6

我们可以使用ShortcutManager进行这样的意图操作

ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

ShortcutInfo webShortcut = new ShortcutInfo.Builder(this, "shortcut_web")
        .setShortLabel("catinean.com")
        .setLongLabel("Open catinean.com web site")
        .setIcon(Icon.createWithResource(this, R.drawable.ic_dynamic_shortcut))
        .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("https://catinean.com")))
        .build();

shortcutManager.setDynamicShortcuts(Collections.singletonList(webShortcut));
Run Code Online (Sandbox Code Playgroud)

我们可以使用ShortcutManager打开这样的活动

    ShortcutInfo dynamicShortcut = new ShortcutInfo.Builder(this, "shortcut_dynamic")
        .setShortLabel("Dynamic")
        .setLongLabel("Open dynamic shortcut")
        .setIcon(Icon.createWithResource(this, R.drawable.ic_dynamic_shortcut_2))
        .setIntents(
                new Intent[]{
                        new Intent(Intent.ACTION_MAIN, Uri.EMPTY, this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK),
                })
        .build();
shortcutManager.setDynamicShortcuts(Arrays.asList(dynamicShortcut, dynamicShortcut));
Run Code Online (Sandbox Code Playgroud)