假定两个App,分别是A和B,当A运行某个功能需要启动B,一种是启动B应用,一种直接进入B的某个Activity。搜了很多资料,没有一个完整的。下面就A--Android5.1.1、B--Android7.1.1,实际华为平板Android5.1.1,EMUI3.1,分辨率1280*800进行测试。关键是Manifest文件设置及启动代码参数设置。
1、A启动整个B(代码来自:http://blog.csdn.net/mad1989/article/details/38090513)
doStartApplicationWithPackageName("B的包完整命名");
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);
}
}
2、A启动B中某一个Activity,B中参数设置
需要在Manifest中对该Activity进行详细设置,如下:
<activity
android:name="com.example.XXXXActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.example.intent.action.XXXX_ACTION" />
<category android:name="com.example.intent.category.XXXX_CATEGORY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
标红处非常关键,在A中需要引用
3、A启动B中某一个Activity,A中代码
Intent intent1 = new Intent();
intent1.setAction("com.example.intent.action.XXXX_ACTION");
intent1.addCategory("com.example.intent.category.XXXX_CATEGORY");
startActivity(intent1);
4、需要给B中的Activity传递参数,如下:
intent1.putExtra("res_w", 1280);
intent1.putExtra("res_h", 800);
5、B中获得这些参数,如下:
mWidth = getIntent().getIntExtra("res_w", 1280);
mHeight = getIntent().getIntExtra("res_h",800);