在Android 7.1(API 25)之后添加的新功能,這里就暫且翻譯成:快捷方式,簡單地理解:在長按應用圖標的情況下,在應用圖標上顯示的快捷方式,該快捷方式可以點擊進入Activity,長按拖動創(chuàng)建一個在Launcher上的圖標。
現(xiàn)在市場上已經(jīng)是有很多應用增加了這項功能,如:印象筆記、支付寶、嗶哩嗶哩、IT之家、知乎、美團,以上是我的手機安裝的應用中看到的,其他的就暫時沒了解到,可以看一下效果。
實現(xiàn)有兩種方式
- 靜態(tài)方式,通過在xml中配置快捷方式,配置名稱、圖標、意圖這些必須的參數(shù),最后在應用啟動的Activity配置一下就可以了。
- 動態(tài)方式,通過Android7.1新添加的ShortcutManager進行管理,可以對快捷方式進行添加、刪除、更新,也可以修改上面的靜態(tài)方式顯示的快捷方式。
靜態(tài)方式
靜態(tài)方式就是通過xml文件進行配置,就像ActionBar的選項一樣。
先配置快捷方式的選項:
res/xml/static_shortcuts.xml 下面配置的參數(shù)也是比較清晰的,有:id、圖標、標題、意圖,還有分類,是否可用。
<!--離線視頻-->
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_download"
android:shortcutDisabledMessage="@string/lable_shortcut_static_download_disable"
android:shortcutId="shortcut_id_download"
android:shortcutLongLabel="@string/lable_shortcut_static_download_long"
android:shortcutShortLabel="@string/lable_shortcut_static_download_short">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.young.demo.launchershortcut.StaticShortcutDownload"
android:targetPackage="com.young.demo.launchershortcut" />
<!--當前只有這個分類-->
<categories android:name="android.shortcut.conversation" />
</shortcut>
配置完圖標的之后,再打開AndroidManiFest.xml配置啟動的Activity
AndroidManiFest.xml
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!--add static shortcut-->
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/static_shortcut" />
</activity>
那么靜態(tài)方式就配置好了,上面快捷方式配置的Activity的就不貼上來了,就是一個簡單的Activity而已。
看一下效果圖:
動態(tài)方式
那么動態(tài)方式,是通過ShortcutManager實現(xiàn)快捷方式的增加、刪除、更新的操作,google的大神都配置好了方法,使用起來很簡單。下面就放一下簡單的配置代碼。
/**
* 先生成一個一個的快捷方式的對象
* 對象需要配置:圖標、標題、意圖,其他的配置具體可以到官網(wǎng)查看
*/
ShortcutInfo likeShortcut = new ShortcutInfo.Builder(this, SHORTCUT_ID_LIKE)
.setShortLabelResId(R.string.lable_shortcut_dynamic_like_short)
.setLongLabelResId(R.string.lable_shortcut_dynamic_like_long)
.setIcon(Icon.createWithResource(this, R.drawable.ic_shortcut_like))
.setIntent(new Intent(this, DynamicShortcutLike.class))
.build();
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
//這樣就可以通過長按圖標顯示出快捷方式了
shortcutManager.setDynamicShortcuts(Arrays.asList(likeShortcut));
上面兩個是通過動態(tài)方式添加的。
移除快捷方式
void removeDynamicShortcuts(@NonNull List<String> shortcutIds);
移除快捷方式,并且拖到launcher上的圖標會變灰,這個方法底層最終調用的方法跟removeDynamicShortcuts一樣
void disableShortcuts(@NonNull List<String> shortcutIds);
使拖到launcher的圖標可用。 靜態(tài)添加的快捷方式不能使用該方法,使用會報錯
void enableShortcuts(@NonNull List<String> shortcutIds);
更新快捷方式,例如圖標、標題
boolean updateShortcuts(List<ShortcutInfo> shortcutInfoList);
顯示的順序問題:添加在前的顯示在下方,后面添加的顯示在上面。
這個類的使用還是比較簡單的。添加了這項功能的APP,長按的效果跟iOS的3D touch差不多的視覺體驗。
這是完整代碼地址:https://github.com/daynearby/LauncherShortcut
最后附上官網(wǎng)地址:
https://developer.android.google.cn/reference/android/content/pm/ShortcutManager.html