【Android】App Shortcuts

Android 7.1 (API level 25)以降で、 アプリアイコンを長押しすると設定したショートカットを表示できるようになり、 ショートカットの項目をドラッグするとアイコンのショートカットを追加できます。 長押しの状態でドラッグすると通常のアイコン操作(Remove, Uninstall)になります。

f:id:chocolattips:20170219101948j:plain

設定できるショートカットは以下の2種類になります。

  • Static Shortcuts
    • xmlで記述
    • 設定すると常に表示される
    • 変更はアプリのアップデート
  • Dynamic Shortcuts
    • 設定するにはコード上で行う
    • 追加/削除/更新ができる

実装

設定する項目は以下の通り

  • shortcutId
  • icon
  • ショートカットのテキスト(short, long)
  • 無効時のメッセージ
  • ショートカットをタップした時のIntent

shortcutShortLabelがアイコン用、shortcutLongLabelが一覧用になります。 f:id:chocolattips:20170219101949j:plain

無効にするとショートカットの一覧から表示されなくなり、 アイコンはグレーになり、タップするとshortcutDisabledMessageがToastで表示されます。

Static Shortcuts

AndroidManifestに記述し、Mainの<activity>内に<meta-data>を記述。 resourceにはショートカットを定義したxmlを指定します。

<activity>
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <meta-data android:name="android.app.shortcuts"
               android:resource="@xml/shortcuts" />
</activity>

res/xml/shortcuts

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
  <shortcut
    android:shortcutId="compose"
    android:enabled="true"
    android:icon="@drawable/compose_icon"
    android:shortcutShortLabel="@string/compose_shortcut_short_label1"
    android:shortcutLongLabel="@string/compose_shortcut_long_label1"
    android:shortcutDisabledMessage="@string/compose_disabled_message1">
    <intent
      android:action="android.intent.action.VIEW"
      android:targetPackage="com.example.helloworld"
      android:targetClass="com.example.helloworld.HelloActivity" />
    <categories android:name="android.shortcut.conversation" />
  </shortcut>
</shortcuts>

enabledで有効/無効を設定できます。 intentやshortcutは複数設定できます。

Dynamic Shortcuts

SystemServiceでShortcutManagerを取得し、 ShortcutInfoを作成してShortcutManagerに渡すことで設定できます。

例えば、ショートカットをタップするとブラウザで指定したURLにアクセスする場合

ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, "shortcutId")
    .setShortLabel("SHORT")
    .setLongLabel("LONG")
    .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))
    .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")))
    .build();

shortcutManager.setDynamicShortcuts(Arrays.asList(shortcutInfo));

Dynamicの場合、ShortcutManager#enableShortcutsにshortcutIdを指定すると有効, disabledShortcutsで無効になります。

参考