Android development sometimes requires launching another app in one app, such as launcher loading a list of all installed programs, and then launching another app when the icon is clicked.
In general, we know that another app's package name and mainactivity name can be started directly from the following code:
| 12345 |
Intent intent = newIntent(Intent.ACTION_MAIN);intent.addCategory(Intent.CATEGORY_LAUNCHER); ComponentName cn = newComponentName(packageName, className); intent.setComponent(cn);startActivity(intent); |
But more often, we do not know the application's Startup activity class name, but only know the package name, we can use the Resolveinfo class to get the class name of the startup Acitivty.
Here is the implementation code:
| 1234567891011121314151617181920212223 |
private void openApp(String packageName) {PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);resolveIntent.setPackage(pi.packageName); List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);ResolveInfo ri = apps.iterator().next();if (ri != null ) {String packageName = ri.activityInfo.packageName;String className = ri.activityInfo.name;Intent intent = new Intent(Intent.ACTION_MAIN);intent.addCategory(Intent.CATEGORY_LAUNCHER); ComponentName cn = new ComponentName(packageName, className);intent.setComponent(cn);startActivity(intent);}} |
Open another application in an Android program