知道包名启动应用程序

我如何启动一个新的应用程序使用其包名称?我没有关于什么活动是主要活动的信息。

93120 次浏览

Try using PackageManager and getLaunchIntentForPackage()

Just use these following two lines, so you can launch any installed application whose package name is known:

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.example.abc");
startActivity( launchIntent );

If you don't know the package name of application that you wanted to launch then try your hand on:

PackageManager pm;
pm = getPackageManager();
//  get a list of installed apps.
packages = pm.getInstalledApplications(0);

For more information, refer to this link: Using Package Manager.

You can get the launch intent through the PackageManager class:

PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.example.package");
context.startActivity(launchIntent);

Note that getLaunchIntentForPackage returns null if the package isn't found. So you might want to add a null check:

if (launchIntent != null) {
context.startActivity(launchIntent);
} else {
Toast.makeText(context, "Package not found", Toast.LENGTH_SHORT).show();
}
Intent intent;
PackageManager pm = getActivity().getPackageManager();


intent = pm.getLaunchIntentForPackage("com.package.name");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


startActivity(intent);
    Intent intent = getPackageManager().getLaunchIntentForPackage("app.package.name");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (intent != null) {
startActivity(intent);
} else {
Toast.makeText(context, "Package not found", Toast.LENGTH_SHORT).show();
}
val packageName = "com.google.android.youtube"
var intent = activity!!.packageManager.getLaunchIntentForPackage(packageName)


if (intent == null) {
if (intent == null) {
intent = try {
Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))
} catch (e: Exception) {
Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName"))
}
}
startActivity(intent)

For Android 11 (API level 30) or higher, in AndroidManifest.xml,

<queries>
<package android:name="com.google.android.youtube" />
<package android:name="com.example.app" />
</queries>

Or simply we can allow for all packages (not recommended)

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />

References

Package visibility filtering on Android