开发有时需要在一个应用中启动另一个应用,比如Launcher加载所有的已安装的程序的列表,当点击图标时可以启动另一个应用。一般我们知道了另一个应用的包名和MainActivity的名字之后便可以直接通过如下代码来启动:
- Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.addCategory(Intent.CATEGORY_LAUNCHER);
- ComponentName cn = new ComponentName(packageName, className);
- intent.setComponent(cn);
- startActivity(intent);
但是更多的时候,我们一般都不知道目标应用程序的启动Activity的类名,而只知道包名,接下来就需要这么做了,我封装成了一个方法,如下所示:
- private void doStartApplicationWithPackageName(String packagename) {
-
-
- PackageInfo packageinfo = null;
- try {
- packageinfo = getPackageManager().getPackageInfo(packagename, 0);
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- if (packageinfo == null) {
- return;
- }
-
-
- Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
- resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
- resolveIntent.setPackage(packageinfo.packageName);
-
-
- List<ResolveInfo> resolveinfoList = getPackageManager()
- .queryIntentActivities(resolveIntent, 0);
-
- ResolveInfo resolveinfo = resolveinfoList.iterator().next();
- if (resolveinfo != null) {
-
- String packageName = resolveinfo.activityInfo.packageName;
-
- String className = resolveinfo.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);
- }
- }