安卓启动静态应用快捷方式



在过去的几天里,我一直在试图弄清楚如何启动Android API 25中添加的应用程序快捷方式,并且取得了一定的成功。我猜开始一些快捷方式,例如Google Play音乐的工作没有问题,因为这些快捷方式正在通过行动开始活动。主要类别。启动器或导出,但其他活动抛出"java.lang.SecurityException: Permission Denial: start Intent">,这似乎也很合理。这似乎是注定的,因为像素启动器,芝麻快捷方式等应用程序可以做到这一点,必须有一些特殊的意图标志或其他东西。我什至尝试在我的应用程序中捕获快捷方式意图并复制它,但没有成功

以下是我如何为谷歌浏览器的"新标签"快捷方式执行此操作的示例:

val componentName = ComponentName("com.android.chrome", "org.chromium.chrome.browser.LauncherShortcutActivity")
val intent = Intent(action)
intent.component = componentName
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME)
startActivity(intent)

我从 activityInfo 元数据中获取了这些值,可以使用 PackageManager 获取这些值

以下是列出所有可用快捷方式的代码,然后启动第一个快捷方式(仅作为示例(:

val launcherApps = context.getSystemService(Context.LAUNCHER_APPS_SERVICE) as LauncherApps
val shortcutQuery = LauncherApps.ShortcutQuery()
// Set these flags to match your use case, for static shortcuts only,
// use FLAG_MATCH_MANIFEST on its own.
shortcutQuery.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
        or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST
        or LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
shortcutQuery.setPackage(packageName)
val shortcuts = try {
    launcherApps.getShortcuts(shortcutQuery, Process.myUserHandle())
} catch (e: SecurityException) {
    // This exception will be thrown if your app is not the default launcher
    Collections.emptyList<ShortcutInfo>()
}
// Lists all shortcuts from the query
shortcuts.forEach {
    Log.d(TAG, "Shortcut found ${it.`package`}, ${it.id}")
}
// Starts the first shortcut, as an example (this of course is not safe like this, 
// it will crash if the list is empty, etc).
val shortcut = shortcuts[0]
launcherApps.startShortcut(shortcut.`package`, shortcut.id, null, null, Process.myUserHandle())

此代码假定您有一个名为 context 的变量(类型为 Context(和一个名为 packageName 的变量(类型为 String

(。

学分:这都是基于Quan Vu在这个主题上的工作,他的文章在这里和相应的存储库在这里。

最新更新