给应用添加shortcut功能

本文的例子使用的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以上,可惜的是国内的手机厂商更新较慢,还没有大量普及,不过我相信这两年就会有大量的应用提供这个功能。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值