给应用添加shortcut功能

来源:互联网 发布:网店加实体店加盟知乎 编辑:程序博客网 时间:2024/06/12 01:30

本文的例子使用的google的sample, 源码地址

从Android N开始谷歌Launcher提供了shortcut功能,方便用户能更快的使用应用提供的功能服务(比如下图),当你每次支付的时候都要打开应用,找到支付的按钮,是不是这种方式更便捷呢。这里就要详细说说第三方应用如何添加和管理自己的shortcut。
这里写图片描述
Android对shortcut是有权限要求的,不是所有的Launcher都能展示应用的shortcut,源码里对权限是这么说明的

Only the default launcher can access the shortcut information.

只有被设置为默认Launcher的桌面才有获取shortcut的权限。如何让非默认桌面也获取shortcut权限呢 也是有办法的,后面再研究。

静态shortcut
Android支持静态shutcut和动态shortcut,对于动态的shortcut不需要在manifest里做任何的 配置,对于静态的只需要声明一下meta-data即可

<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts"/>

shortcuts.xml文件:

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >    <shortcut        android:shortcutId="add_website"        android:icon="@drawable/add"        android:shortcutShortLabel="@string/add_new_website_short"        android:shortcutLongLabel="@string/add_new_website"        >        <intent            android:action="com.example.android.appshortcuts.ADD_WEBSITE"            android:targetPackage="com.example.android.appshortcuts"            android:targetClass="com.example.android.appshortcuts.Main"            />    </shortcut></shortcuts>

shortcuts.xml文件声明了shortcut的名字,图标及intent,这里的intent配置决定了在桌面点击该shortcut的时候要跳转的目标。

动态的shortcut
framework提供了ShortcutManager来管理shortcut, 获取ShortcutManager的方法如下

mShortcutManager = mContext.getSystemService(ShortcutManager.class);

获取到ShortcutManager后调用它的addDynamicShortcuts方法添加新的shortcut就好了。

Intent intent = new Intent(); intent.setAction("com.example.android.appshortcuts.ADD_WEBSITE");intent.setClassName("com.example.android.shortcutsample",                "com.example.android.appshortcuts.Main");ShortcutInfo.Builder builder = new ShortcutInfo.Builder(this, "dynamic shortcut")                .setIntent(intent)                .setShortLabel("This is a dynamic shortcut")                .setLongLabel("This is a dynamic shortcut with long label")                .setIcon(Icon.createWithResource(this, R.drawable.link));ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);shortcutManager.addDynamicShortcuts(Arrays.asList(builder.build()));

最新添加的shortcut总是在最上面。

shortcut的更新
如果用户切换语言,shortcut该如何更新呢?可能你早就猜到了,ShortcutManager肯定提供了更新的接口,需要重新获取一遍资源并set遍,最后调用下面的接口更新就好了。

public boolean updateShortcuts(List<ShortcutInfo> shortcutInfoList) {        ...    }

shortcut功能为应用提供了快捷的入口,应用不但可以设置静态的shortcut,也可以设置动态的,也可以使能或者禁止shortcut,还可以根据用户的使用行为,为不同的用户提供不同的shortcut。shortcut功能需要android系统 sdk要在25以上,可惜的是国内的手机厂商更新较慢,还没有大量普及,不过我相信这两年就会有大量的应用提供这个功能。

原创粉丝点击