Как создать ярлык динамического приложения с помощью API ShortcutManager для приложения Android 7.1?

В Android 7.1 разработчик может создавать AppShortCut.

Мы можем создать ярлык двумя способами:

  1. Статические ярлыки с использованием файла ресурсов (XML).
  2. Динамические ярлыки с использованием ShortcutManager API.

Так как создать ярлык с помощью ShortcutManager динамически?

4 ответа

Решение

С помощью ShortcutManagerМы можем создать ярлык динамического приложения следующим образом:

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


    }

Строковые ресурсы:

<string name="str_shortcut_two">Shortcut 2</string>
<string name="str_shortcut_two_desc">Shortcut using code</string>

Разработчик также может выполнять различные задачи ярлыка приложения, используя ShortcutManager:

  • Публикация: используйте setDynamicShortcuts(List), чтобы переопределить весь список динамических ярлыков, или используйте addDynamicShortcuts(List), чтобы дополнить существующий список динамических ярлыков.
  • Обновление: используйте метод updateShortcuts(List).
  • Удалить: удалить набор динамических ярлыков, используя removeDynamicShortcuts (List), или удалить все динамические ярлыки, используя removeAllDynamicShortcuts ().

Ярлык приложения

Проверьте пример Github для ярлыка приложения

Проверьте https://developer.android.com/preview/shortcuts.html и ShortcutManager, чтобы получить больше информации.

Мы можем использовать 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));

мы можем использовать 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(webShortcut, dynamicShortcut));

Идеальное решение для всех устройств (устройство Pre/Post Oreo).

createShortcut(CurrentActivity.this, ActivityToOpen.class, "app name", R.mipmap.ic_launcher);

Поместите это в свой Util.

 public static void createShortcut(@NonNull Activity activity, Class activityToOpen, String title, @DrawableRes int icon) {
        Intent shortcutIntent = new Intent(activity, activityToOpen);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // code for adding shortcut on pre oreo device 
            Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
            intent.putExtra("duplicate", false);
            Parcelable parcelable = Intent.ShortcutIconResource.fromContext(activity, icon);
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, parcelable);
            activity.sendBroadcast(intent);
            System.out.println("added_to_homescreen");
        } else { 
            ShortcutManager shortcutManager = activity.getSystemService(ShortcutManager.class);
            assert shortcutManager != null;
            if (shortcutManager.isRequestPinShortcutSupported()) {
                ShortcutInfo pinShortcutInfo =
                        new ShortcutInfo.Builder(activity, "browser-shortcut-")
                                .setIntent(shortcutIntent)
                                .setIcon(Icon.createWithResource(activity, icon))
                                .setShortLabel(title)
                                .build();

                shortcutManager.requestPinShortcut(pinShortcutInfo, null);
                System.out.println("added_to_homescreen");
            } else {
                System.out.println("failed_to_add");
            }
        }
    }

Динамические ярлыки: ShortcutManager используется для управления всеми динамическими ярлыками. ShortcutInfo представляет собой один ярлык, который затем будет добавлен в ShortcutManager через ShortcutInfo.Builder.

   //......................................* Java Dynamic Shortcuts
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

Intent thirdIntent = new Intent(this,ThirdActivity.class);
thirdIntent.setAction(Intent.ACTION_VIEW);

ShortcutInfo thirdScreenShortcut = new ShortcutInfo.Builder(this, "shortcut_third")
 .setShortLabel("Third Activity")
 .setLongLabel("This is long description for Third Activity")
 .setIcon(Icon.createWithResource(this, R.drawable.your_image))
 .setIntent(thirdIntent)
 .build();
 shortcutManager.setDynamicShortcuts(Collections.singletonList(thirdScreenShortcut));








  //......................................*  KOTLIN Dynamic Shortcuts
 val shortcutManager = getSystemService(ShortcutManager::class.java)


            val thirdIntent = Intent(this, ActivityThree::class.java)
            thirdIntent.action = Intent.ACTION_VIEW

            val dynamicShortcut = ShortcutInfo.Builder(this, "shortcut_third")
                .setShortLabel("Third Activity")
                .setLongLabel("This is long description for Third Activity")
                .setIcon(Icon.createWithResource(this, R.drawable.your_image))
                .setIntents(
                    arrayOf(
                        Intent(
                            Intent.ACTION_MAIN,
                            Uri.EMPTY,
                            this,
                            MainActivity::class.java
                        ).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK),
                        thirdIntent
                    )
                )
                .build()

  shortcutManager!!.dynamicShortcuts = listOf(dynamicShortcut)

Основные примечания:https://androidkeynotes.blogspot.com/2020/02/app-shortcuts.html

Мы должны установить ярлык "Целевая активность" вместо упоминания неявных намерений.

Например:

ShortcutManager shortcutManager = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
        shortcutManager =  getSystemService(ShortcutManager.class);
        Intent intent= new Intent(this, MainActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("weburl"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "shortcutId")
                .setShortLabel("dummy")
                .setLongLabel("dummy").setRank(0)
                .setIcon(Icon.createWithResource(this, R.drawable.ic_launcher_background))
                .setIntent(intent).build();

         shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));
}

И активность в моем Manifest.xml:

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
             <action android:name="android.intent.action.VIEW" />

        </intent-filter>
    </activity>

Прихожу в свой MainActivity при нажатии на динамический ярлык, который обрабатывает Action_VIEW .

Другие вопросы по тегам