过去几天我一直试图弄清楚如何启动Android API 25中添加的应用程序快捷方式,并且我已经取得了一些成功。启动一些快捷方式,例如Google Play Music的工作没有问题,我猜是因为这些快捷方式正在启动 action.MAIN 和 category.LAUNCHER 或导出的活动,但其他活动抛出< em>“java.lang.SecurityException:Permission Denial:starting Intent”这似乎也是合理的。这似乎是可行的,因为像Pixel Launcher,Sesame Shortcuts等应用程序可以做到这一点,必须有一些特殊意图标志或其他东西。我甚至尝试在我的应用程序中捕获快捷方式并复制它但没有成功
以下是我为Google Chrome的“新标签”快捷方式执行此操作的示例:
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 metaData获取了这些值,可以使用 PackageManager
获取这些值答案 0 :(得分:1)
这里是列出所有可用快捷方式的代码,然后启动第一个快捷方式(仅作为示例):
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
的{{3}}类型的变量和一个名为packageName
的变量String
来自某个地方。