如何在 Java 中以编程方式获取 android 2.3 及更高版本中当前启动器的包名称?
3 回答
我认为您应该能够使用PackageManager.resolveActivity(),以家庭意图。
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String currentHomePackage = resolveInfo.activityInfo.packageName;
With the package visibility changes introduced in Android 11, it is now necessary to add a queries element in your application's manifest file as below before you can query the PackageManager.resolveActivity(intent:flags:) method for the default home (a.k.a. launcher) activity that is installed on the device as described in the accepted answer in this thread:
<queries>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
</intent>
</queries>
If this queries element is omitted from your application's manifest, then the device will report the com.android.settings.FallbackHome
activity as its default home activity and that is most likely not what you want.
一般来说,我同意@JesusFreke使用 PM resolveActivity
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
但要获得正确的包名称,您应该使用
resolveInfo.loadLabel(packageManager).toString()
或者
resolveInfo.activityInfo.applicationInfo.loadLabel(packageManager).toString()
提示:如果没有默认设置,这可能会变成“Android System”或“open”,就像一般的 System Intent Receiver
提示:如果您正在寻找网络浏览器,您可以使用net.openid.appauth.browser.BrowserSelector#select()
( 0.7.1+ ) 来隐式获取默认浏览器,即使没有明确设置。