Android 8.0 (Oreo) 前後ショートカット作成方法の違い - Android Studio

Android 8 (O) API26 からショートカットの作成方法が変わったのでメモ

  1. String shortcutName = "Shortcut Name";  
  2. Intent  shortcutIntent = new Intent(Intent.ACTION_MAIN);  
  3.         shortcutIntent.setClassName(this"com.example.myApplication"); // 呼び出すActivity  
  4.         shortcutIntent.putExtra("key1""value1"); // 渡す情報()  
  5.         shortcutIntent.putExtra("key2""value2");  
  6.   
  7. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  
  8.     // Android 8 O API26 以降  
  9.     Icon icon = Icon.createWithResource(getApplicationContext(), R.mipmap.ic_shortcut);  
  10.     ShortcutInfo shortcut = new ShortcutInfo.Builder(getApplicationContext(), shortcutName)  
  11.             .setShortLabel(shortcutName)  
  12.             .setLongLabel(shortcutName)  
  13.             .setIcon(icon)  
  14.             .setIntent(shortcutIntent)  
  15.             .build();  
  16.   
  17.     ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);  
  18.                     shortcutManager.requestPinShortcut(shortcut, null); // フツーのショートカット  
  19.                     // shortcutManager.addDynamicShortcuts(Arrays.asList(shortcut)); // ダイナミックショートカット  
  20. else {  
  21.     // Android 7 Nougat API25 以前  
  22.     Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.mipmap.ic_shortcut);  
  23.     Intent  intent = new Intent();  
  24.             intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);  
  25.             intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);  
  26.             intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");  
  27.             this.sendBroadcast(intent);  
  28. }  

ダイナミックショートカットは、アプリアイコンをうにゅっと押し続けて4つくらいまで表示されるショートカットの事です(iPhoneでいう3D Touch のクイックアクション)

requestPinShortcut の第2引き数はショートカット作成後のイベントらしいです、エミュレータでは requestPinShortcut 処理後にOSからショートカット作成確認のダイアログが出てましたので、作成が完了したかどうかなんかが受け取れるのかも(未確認)

  1. // 一覧取得  
  2. ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);  
  3. List<shortcutinfo> shortcutList = shortcutManager.getDynamicShortcuts();  
  4. for (int i = 0; i < shortcutList.size(); i++) {  
  5.  shortcutList.get(i);  
  6. }  
  7.   
  8. // 削除  
  9. ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);  
  10.     shortcutManager.removeDynamicShortcuts(Arrays.asList("ショートカット名"));  
  11.   
  12. </shortcutinfo>  
ダイナミックショートカットを操作できるのは該当アプリケーションのみです
また、(操作の話ですが)ダイナミックショートカットを長押しして、フツーのショートカットとしてコピーする事が出来ます

コメント