天天看點

App Shortcuts實作長按圖示顯示快捷入口

文章目錄

      • App Shortcuts
      • 使用Shortcut
        • 動态使用
        • 靜态使用

App Shortcuts

App Shortcuts是Android7.1上推出的新功能,可以實作點選Launcher上圖示彈出快捷入口:

App Shortcuts實作長按圖示顯示快捷入口

使用Shortcut

使用App Shortcuts有兩種形式,類似廣播有動态注冊和靜态注冊,App Shortcuts也有兩種形式,分别是動态使用和靜态使用。

動态使用

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            // android 7.1
            ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
            ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, "id1")
                    .setShortLabel("測試")
                    .setLongLabel("測試測試")
                    .setIcon(Icon.createWithResource(this, R.mipmap.ic_launcher))
                    .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com")))
                    .build();
            shortcutManager.setDynamicShortcuts(Arrays.asList(shortcutInfo));
        }
    }
}
           
App Shortcuts實作長按圖示顯示快捷入口
  1. 通過擷取ShortcutManager來動态設定Shortcut.
  2. 通過build建構一個shortcutInfo對象
  3. 調用shortcutManager#setDynamicShortcuts更新

下面列出可能會用到的API

方法 作用
setDynamicShortcuts 更新整個Shortcut清單
addDynamicShortcuts 添加新的條目
updateShortcuts 更新清單
removeDynamicShortcuts 移除指定條目
removeAllDynamicShortcuts 移除全部的條目

靜态使用

在清單檔案入口Activity添加meta标簽

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <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>
           

添加xml目錄,建立shortcuts xml配置檔案

<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">

    <shortcut
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="id1"
        android:shortcutLongLabel="@string/app_name"
        android:shortcutShortLabel="@string/app_name">
        <intent
            android:action="android.intent.action_VIEW"
            android:targetPackage="com.welcom.shortcut.shortcutdemo">
        </intent>
    </shortcut>
</shortcuts>