App Shortcuts

Android 7.1 已经发布了一段时间了,但是对7.1的特性并没有去做了解,个人手机升级为7.1系统后才去关注,作为一个android开发人员有点不够前沿了.升级系统之后第一个非常直观的区别,发现多了快捷菜单功能,有些类似ios的3dTouch效果,也就是我们要说的App Shortcuts.

了解更多Android O新特性:

Android O 官方介绍

什么是App Shortcuts

App Shortcuts 其实就是一种快捷访问形式,长按应用图标出现的快捷菜单.可以为我们应用的关键功能提供一个快捷的入口.点击快捷菜单,可以打开应用内指定的页面,也可以拖拽到桌面上作为一个单独的快捷方式.

App Shortcuts有两种实现方式:

静态的:在xml中定义好,使用与一些通用的功能.

动态的:通过ShortManager在代码中动态添加,可以根据用户喜好以及业务需求动态更新.

每个应用动态和静态总共最多可以添加5个.

静态方式

静态的方式直接在xml中定义,只需要2步

在manifest中的启动activity声明下,配置:

android:name="android.app.shortcuts"
android:resource="@xml/shortcuts"
/>

在res/xml目录下创建shortcuts.xml文件,在这个文件中声明我们需要的静态shortcuts:

xmlns:android="http://schemas.android.com/apk/res/android">
android:enabled="true"
android:icon="@mipmap/ic_launcher"//此处是快捷菜单的icon
android:shortcutDisabledMessage="@string/short_cut_disabled_msg_static1"
android:shortcutId="1"//菜单的id
android:shortcutLongLabel="@string/short_cut_long_label_static1"//菜单的名称
android:shortcutShortLabel="@string/short_cut_short_label_static1"//菜单拖拽到桌面快捷方式的名称
>
//配置一个intent,点击打开对应页面,返回回退到桌面
//配置多个intent,点击打开最后一个intent的页面,前面的intent用来构建回退栈
android:action="android.intent.action.MAIN"
android:targetClass="com.demo.shortcutsdemo.MainActivity"
android:targetPackage="com.demo.shortcutsdemo"/>
//点击启动的intent
android:action="android.intent.action.VIEW"
android:targetClass="com.demo.shortcutsdemo.MainActivity"//点击启动的页面
android:targetPackage="com.demo.shortcutsdemo"/>

这样静态的方式就完成了.

动态方式

我们可以在我们的代码中使用ShortcutsManager进行操作:

添加:setDynamicShortcuts(),addDynamicShortcuts(List)

更新:updateShortcuts(List)

移除:removeDynamicShortcuts(List),removeAllDynamicShortcuts()

添加一个动态的shortcuts:

ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(this, MainActivity2.class);
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, "dynamic1")
.setShortLabel("动态")
.setLongLabel("动态")
.setShortLabel("动态")
.setRank(3)//弹出的排序,越大离应用图标越远,静态的比动态的离应用图标近
.setIcon(Icon.createWithResource(this, R.mipmap.ic_launcher))
.setIntent(intent)//设置一个intent就是点击启动的页面
.setIntents(new Intent[]{//设置多个intent时,将构建回退栈,最后一个是点击启动的页面
new Intent(),new Intent()
})
.build();
shortcutManager.addDynamicShortcuts(Arrays.asList(shortcutInfo));

App Shortcuts简单介绍使用,有什么问题和错误欢迎指正.