Android shortcut的使用及源码分析
最近遇到了一个切换国家码后部分应用的shortcut未更新的问题,就学习了shortcut的相关知识,在这里分享一下我了解的知识,希望能对大家有帮助。
shortcut简介
Android 7.1 新功能之一就是 App Shortcuts(应用快捷方式) ,该功能与 iPhone 上的 3D Touch 功能相似,通过长按应用图标,可弹出应用快捷方式,点击可以直接跳转到相应的界面。目前最多支持4 个快捷方式,可以 getMaxShortcutCountPerActivity() 查看 Launcher 最多支持几个快捷方式,不同的是 Android 支持通过拖拽将快捷方式固定到桌面。

shortcut的分类
静态创建快捷方式
1、在应用的res/xml目录下创建shortcuts.xml
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_add_contact_shortcut"
android:shortcutId="shortcut-add-contact"
android:shortcutShortLabel="@string/shortcut_add_contact">
<intent
android:action="android.intent.action.INSERT"
android:data="content://com.android.contacts/contacts"
android:targetPackage="com.android.contacts"
android:targetClass="com.android.contacts.activities.ContactEditorActivity"/>
</shortcut>
</shortcuts>
2、属性含义
- enabled:默认为true,用来区分当前快捷方式是否激活,值为false表示当前条目失效;
- icon:用来指定条目的图标;
- shortcutId:用来指定条目的唯一识别名;
- shortcutLongLabel:用来指定条目的长标签;
- shortcutShortLabel:用来指定条目短标签;
- shortcutDisabledMessage:用来指定条目未被激活时条目被点击时候的弹出信息;
- action:指定开启Activity的意图;
- targetClass:指定条目的目标类名;
- targetPackage:必须是当前应用的包名,否则会提示“未安装该应用”;
3、在清单文件中配置shortcuts.xml文件
在清单文件中添加权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
在应用启动的activity里面添加meta-data
<activity
android:name=".activities.PeopleActivity"
android:alwaysRetainTaskState="true"
android:launchMode="singleTop"
android:resizeableActivity="true"
android:theme="@style/LaunchScreenTheme"
android:visibleToInstantApps="true"
android:windowSoftInputMode="adjustPan"
>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name