App Shortcut功能
最近手機在升級Android 7.1之后,長按某些APP圖標就會彈出菜單。
看了系統更新的文檔才知道該功能叫做App Shortcut,目前只有少部分的應用支持這個功能,之后隨著Android版本的更新,將會有大批APP適配該功能。那我們就來看一下該功能是如何實現的:
實現App Shortcuts有兩種形式:
動態形式:在運行時,通過ShortcutManager API來進行注冊。通過這種方式,你可以在運行時,動態的發布,更新和刪除Shortcut。
靜態形式:在APK中包含一個資源文件來描述Shortcut。這種注冊方法將導致:如果你要更新Shortcut,你必須更新整個應用程序
目前,每個應用最多可以注冊5個Shortcuts,無論是動態形式還是靜態形式。
動態形式
通過動態形式注冊的Shortcut,通常是特定的與用戶使用上下文相關的一些動作。這些動作在用戶的使用過程中,可能會發生變化。
ShortcutManager提供了API來動態管理Shortcut,包括:
新建:方法setDynamicShortcuts() 可以添加或替換所有的shortcut;方法addDynamicShortcuts() 來添加新的shortcut到列表中,超過最大個數會報異常
更新:方法updateShortcuts(List shortcutInfoList) 更新已有的動態快捷方式;
刪除:方法removeDynamicShortcuts(List shortcutIds) 根據動態快捷方式的ID,刪除已有的動態快捷方式;方法removeAllDynamicShortcuts() 刪除掉app中所有的動態快捷方式;
下面是一段代碼示例:
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "id1")
.setShortLabel("Web site")
.setLongLabel("Open the web site")
.setIcon(Icon.createWithResource(context, R.drawable.icon_website))
.setIntent(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.mysite.example.com/")))
.build();
shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));
靜態形式
靜態Shortcut應當提供應用程序中比較通用的一些動作,例如:發送短信,設置鬧鐘等等。
開發者通過下面的方式來設置靜態Shortcuts:
App Shortcuts是在Launcher上顯示在應用程序的入口上的,因此需要設置在action為“android.intent.action.MAIN”,category為“ android.intent.category.LAUNCHER”的Activity上。通過添加一個 <meta-data> 子元素來并指定定義Shortcuts資源文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application>
<activity android:name="Main">
<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>
</application>
</manifest>
在res/xml/shortcuts.xml這個資源文件中,添加一個 根元素,根元素中包含若干個 子元素,每個 描述了一個Shortcut,其中包含:icon,description labels以及啟動應用的Intent。
<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.myapplication"
android:targetClass="com.example.myapplication.ComposeActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
<!-- Specify more shortcuts here. -->
</shortcuts>
Shortcuts的簡單作用
每個Shortcut可以關聯一個或多個intents,每個intent啟動一個指定的action; 官方給出了幾個可以作為shortcut的例子,比如:
在地圖類app中,指導用戶到特定的位置;
在社交類app中,發送消息給一個朋友;
在媒體類app中,播放視頻的下一片段;
在游戲類app中,下載最后保存的要點;
APP Shortcut功能很實用,能在自己的APP是適配該功能,用戶體驗將會進一步提高。