Android Studio Java开发:长按应用图标如何添加跳转Activity的快捷部件?
Android 长按应用图标跳转指定Activity功能实现方案
你需要实现的是Android 7.1(API 25)及以上版本支持的**应用快捷方式(App Shortcuts)**功能,Java语言下的实现步骤如下:
步骤1:创建快捷方式配置文件
在res目录下新建xml子目录,在该目录中创建shortcuts.xml配置文件,示例内容如下:
<?xml version="1.0" encoding="utf-8"?> <shortcuts xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 第一个快捷方式:跳转至搜索页 --> <shortcut android:shortcutId="search_shortcut" android:enabled="true" android:icon="@drawable/ic_search" android:shortcutShortLabel="@string/shortcut_search_short" android:shortcutLongLabel="@string/shortcut_search_long" android:shortcutDisabledMessage="@string/shortcut_search_disabled"> <intent android:action="android.intent.action.VIEW" android:targetPackage="com.your.package.name" android:targetClass="com.your.package.name.SearchActivity" /> <categories android:name="android.intent.category.LAUNCHER" /> </shortcut> <!-- 第二个快捷方式:跳转至设置页 --> <shortcut android:shortcutId="settings_shortcut" android:enabled="true" android:icon="@drawable/ic_settings" android:shortcutShortLabel="@string/shortcut_settings_short" android:shortcutLongLabel="@string/shortcut_settings_long" android:shortcutDisabledMessage="@string/shortcut_settings_disabled"> <intent android:action="android.intent.action.VIEW" android:targetPackage="com.your.package.name" android:targetClass="com.your.package.name.SettingsActivity" /> <categories android:name="android.intent.category.LAUNCHER" /> </shortcut> </shortcuts>
注意替换com.your.package.name为你的应用包名,替换目标Activity路径、图标、文案为你自己的业务配置。
步骤2:在Manifest中注册快捷方式
找到你应用的启动Activity(即配置了android.intent.action.MAIN和android.intent.category.LAUNCHER的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>
步骤3:可选实现动态快捷方式
如果需要根据用户行为动态修改、增删快捷方式,可以使用ShortcutManager实现,Java示例代码如下:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) { ShortcutManager shortcutManager = getSystemService(ShortcutManager.class); ShortcutInfo searchShortcut = new ShortcutInfo.Builder(this, "search_shortcut") .setShortLabel("搜索") .setLongLabel("打开应用搜索页") .setIcon(Icon.createWithResource(this, R.drawable.ic_search)) .setIntent(new Intent(Intent.ACTION_VIEW, null, this, SearchActivity.class)) .build(); shortcutManager.setDynamicShortcuts(Arrays.asList(searchShortcut)); }
注意事项
- 静态注册的快捷方式最多支持同时配置5个,加上动态快捷方式总数建议不超过10个,避免超出系统限制
- 该功能仅在Android 7.1及以上系统生效,低版本系统不会展示快捷方式,不影响应用正常运行
- 长按快捷方式可以拖动到桌面生成单独的快捷入口,不需要额外配置即可支持该特性
内容的提问来源于stack exchange,提问作者Binil George
相关产品推荐
相关产品推荐

