怎样通过一APP打开另一个APP

我们在开发android时,有时会遇到在一个APP中打开另一个APP,比如将多个APP整合在一个APP中时,这时就需要这样的功能,先上代码:

Intent intent = new Intent(Intent.ACTION_MAIN);  
intent.addCategory(Intent.CATEGORY_LAUNCHER);   
// ComponentName中第一个参数代表包名,这里的包名指的是AndroidManifest.xml文件 里面的包名,第二个参数是主activity类的包全路径,及为className				
ComponentName cn = new ComponentName("com.ybb_new_client", "com.ybb_new_client.ui.SplashActivity");              
intent.setComponent(cn);  
startActivity(intent);

有时,我们只知道包名,而不知道类时,可以通过下面的方式来打开app

private void doStartApplicationWithPackageName(String packagename) {  
		  
	    // 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等  
	    PackageInfo packageinfo = null;  
	    try {  
	        packageinfo = getPackageManager().getPackageInfo(packagename, 0);  
	    } catch (NameNotFoundException e) {  
	        e.printStackTrace();  
	    }  
	    if (packageinfo == null) {  
	        return;  
	    }  
	  
	    // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent  
	    Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);  
	    resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
	    resolveIntent.setPackage(packageinfo.packageName);  
	  
	    // 通过getPackageManager()的queryIntentActivities方法遍历  
	    List<ResolveInfo> resolveinfoList = getPackageManager()  
	            .queryIntentActivities(resolveIntent, 0);  
	  
	    ResolveInfo resolveinfo = resolveinfoList.iterator().next();  
	    if (resolveinfo != null) {  
	        // packagename = 参数packname  
	        String packageName = resolveinfo.activityInfo.packageName;  
	        // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式:packagename.mainActivityname]  
	        String className = resolveinfo.activityInfo.name;  
	        // LAUNCHER Intent  
	        Intent intent = new Intent(Intent.ACTION_MAIN);  
	        intent.addCategory(Intent.CATEGORY_LAUNCHER);  
	  
	        // 设置ComponentName参数1:packagename参数2:MainActivity路径  
	        ComponentName cn = new ComponentName(packageName, className);  
	  
	        intent.setComponent(cn);  
	        startActivity(intent);  
	    }  
	}

相关推荐