android 长按图标展示快捷方式
首先,这不是一个新功能了,在android 7.1的时候就已经支持创建快捷入口了。因为当时项目用不到也没关注过这块,现在很多应用都支持长按展示快捷入口了,确实有必要对这块了解下了。
1. 静态创建
静态创建比较适合常用的快捷方式不怎么变的情况。
- 在
AndroidManifest.xml 清单文件中找到应用程序的入口,也就是 intent 过滤器设置为 android.intent.action.MAIN 操作和 android.intent.category.LAUNCHER 类别的 Activity 。 - 向此
activity 添加 <meta-data> 元素,引用定义了快捷方式的资源文件。
<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>
- 在
res/xml 下创建shortcuts.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="money_in"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:shortcutShortLabel="@string/short_money_in">
<intent
android:action="android.intent.action.VIEW"
android:targetPackage="com.example.appshotcutssimple"
android:targetClass="com.example.appshotcutssimple.MoneyInActivity" />
<categories android:name="android.shortcut.conversation" />
<capability-binding android:key="actions.intent.CREATE_MESSAGE" />
</shortcut>
<shortcut
android:shortcutId="money_out"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:shortcutShortLabel="@string/short_money_out">
<intent
android:action="android.intent.action.VIEW"
android:targetPackage="com.example.appshotcutssimple"
android:targetClass="com.example.appshotcutssimple.MoneyOutActivity" />
<categories android:name="android.shortcut.conversation" />
<capability-binding android:key="actions.intent.CREATE_MESSAGE" />
</shortcut>
</shortcuts>
其中 shortcutId 为id shortcutShortLabel 为简短说明,也就是名字 icon 为图标 categories 为应用程序的快捷方式执行的操作类型提供分组,例如创建新的聊天消息 capability-binding 可选 声明与此快捷方式关联的功能。CREATE_MESSAGE 声明的功能,是与应用有关的 Action 内置 intent。用户可以结合使用语音指令与 Google 助理来调用此快捷方式。
来看下最终的效果: 
2. 动态创建
binding.btnAdd.setOnClickListener {
shortScan = ShortcutInfoCompat.Builder(this, "shortcut_scan")
.setShortLabel(getString(R.string.short_scan))
.setIcon(IconCompat.createWithResource(this, R.mipmap.ic_launcher))
.setIntent(Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java))
.build()
ShortcutManagerCompat.addDynamicShortcuts(this, mutableListOf(shortScan))
Toast.makeText(this, "创建成功", Toast.LENGTH_SHORT).show()
}
binding.btnRemove.setOnClickListener {
ShortcutManagerCompat.removeDynamicShortcuts(
this@MainActivity,
Collections.singletonList("shortcut_scan")
)
Toast.makeText(this, "移除成功", Toast.LENGTH_SHORT).show()
}
这样就可以动态实现添加快捷入口的功能。 最后附上项目地址: 点击此处
|