Android启动静态应用快捷方式

问题描述 投票:0回答:1

过去几天我一直试图弄清楚如何启动Android API 25中添加的应用程序快捷方式,并且我已经取得了一些成功。启动一些快捷方式,如Google Play Music的工作没有问题我猜测因为这些快捷方式正在启动action.MAIN和category.LAUNCHER或导出的活动,但其他活动抛出“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获取这些值

android android-intent kotlin android-package-managers android-static-shortcuts
1个回答
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的变量Context和一个名为packageName的变量,其类型为String


致谢:这完全基于Quan Vu关于这个主题的工作,他的文章here和相应的存储库here

© www.soinside.com 2019 - 2024. All rights reserved.