启动一个第三方APP

0

我们知道了另一个应用的包名和MainActivity的名字之后便可以直接通过如下代码来启动:
Intent intent =new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = newComponentName(packageName, className);
intent.setComponent(cn);
startActivity(intent);
更多的时候,我们一般都不知道应用程序的启动Activity的类名,而只知道包名,我们可以通过ResolveInfo类来取得启动Acitivty的类名:
privatevoid openApp(String packageName) {
PackageInfo pi = getPackageManager().getPackageInfo(packageName, 0);
Intent resolveIntent = newIntent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(pi.packageName);
List 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 = newIntent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = newComponentName(packageName, className);
intent.setComponent(cn);
startActivity(intent);
}
}

1

桌面软件点击app的时候是不会重新打开一个软件或者出现引导页。我就去找了桌面启动app的代码,实现了所需的效果:
Intent intent = new Intent();
intent = getAppOpenIntentByPackageName(MainActivity.this,"目标软件package");
startActivity(intent);

public static Intent getAppOpenIntentByPackageName(Context context, String packageName){
String mainAct = null;
PackageManager pkgMag = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED|Intent.FLAG_ACTIVITY_NEW_TASK);
List list = pkgMag.queryIntentActivities(intent,
PackageManager.GET_ACTIVITIES);
for (int i = 0; i < list.size(); i++) {
ResolveInfo info = list.get(i);
if (info.activityInfo.packageName.equals(packageName)) {
mainAct = info.activityInfo.name;
break;
}
}
if (TextUtils.isEmpty(mainAct)) {
return null;
}
intent.setComponent(new ComponentName(packageName, mainAct));
return intent;
}
目标主Activity的LaunchMode最好设为“singletop”

2

你可能感兴趣的:(启动一个第三方APP)