随着Android O的到来Android系统又焕然一新了带来了许多方便好玩的新东西,今天就来玩玩新功能中的一个——AppShortcuts
1⃣️来欣赏一下官方给出的效果图:长按桌面图标就可以在应用上方弹出我们的快捷方式(类似ios的3d-touch),当然长按快捷方式和还可以拖动到桌面上 这样下次就可以直接点击进入不用继续长按了是不是感觉方便了许多。
2⃣️下面就来实现让自己的app也实现这个如此方便的功能吧(必须要下载最新api 26的sdk哦)
- 创建一个新项目将
compileSdkVersion
targetSdkVersion
buildToolsVersion
都设置为26就可以了 - 这里创建这个快捷方式可以动态创建也可以静态配置生成,我们先来通过静态配置
- 在res/xml 下创建一个shortcuts.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="@drawable/logo"
android:shortcutId="msg"
android:shortcutLongLabel="@string/msg_title"
android:shortcutShortLabel="@string/msg_title">
<!--shortcutLongLabel 标题-->
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.azhon.appshortcuts.MessageActivity"
android:targetPackage="com.azhon.appshortcuts" />
</shortcut>
<!--这是第二个快捷方式-->
<shortcut
android:enabled="true"
android:icon="@drawable/logo"
android:shortcutId="code"
android:shortcutLongLabel="@string/msg_code"
android:shortcutShortLabel="@string/msg_code">
<!--shortcutLongLabel 标题-->
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.azhon.appshortcuts.ScanCodeActivity"
android:targetPackage="com.azhon.appshortcuts" />
</shortcut>
<!-- 下面可以继续添加多个shortcut -->
</shortcuts>
< shortcut>中可以配置< intent>也就是点击过后你需要跳转到的指定页面,记住一定要给< intent>配置action。
3⃣️啥都创建好了,那就可以直接使用了;直接在Mainfest中引用即可。
直接在程序主入口应用刚才创建的xml就可以了
<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>
4⃣️实现的效果
有了这个功能就可以快速跳转到指定页面了,就不用打开app一步一步点击了瞬间觉得生命延长了有木有。
5⃣️下面就来通过代码动态创建这两个快捷方式吧
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取ShortcutManager服务
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
ArrayList<ShortcutInfo> list = new ArrayList<>();
ShortcutInfo shortcut1 = new ShortcutInfo.Builder(this, "msg")
//当快捷方式拖拽出来显示的标题
.setShortLabel("消息")
.setLongLabel("消息")
//一定要设置action
.setIntent(new Intent(this, MessageActivity.class).setAction(Intent.ACTION_VIEW))
.build();
ShortcutInfo shortcut2 = new ShortcutInfo.Builder(this, "code")
.setShortLabel("扫码")
.setLongLabel("扫码")
.setIcon(Icon.createWithResource(this, R.drawable.logo))
.setIntent(new Intent(this, MessageActivity.class).setAction(Intent.ACTION_VIEW))
.build();
list.add(shortcut1);
list.add(shortcut2);
shortcutManager.setDynamicShortcuts(list);
}
好了到这里就结束感兴趣的可以自己尝试一下,app需要在Android o上运行哦!当然还有许多新功能各位也可以查看官方文档进行了解。