ComponentName:可以启动其他应用的Activity、Service.
ComponentName chatActivity =new ComponentName(param1,param2);
param1:Activity、Service所在应用的包名
param2:Activity、Service的包名+类名
Activity:
ComponentName chatActivity =new ComponentName("com.npf.chat", "com.npf.chat.ui.ChatActivity");
Intent intent =new Intent();
intent.setComponent(chatActivity);
startActivity(intent);
Service:
ComponentName chatService =new ComponentName("com.npf.chat", "com.npf.chat.ui.ChatService");
Intent intent =new Intent();
intent.setComponent(chatService );
startService(intent);
注意:
如果该Activity非应用入口(入口Activity默认android:exported="true"),
则需要再清单文件中添加 android:exported="true"。
Service也需要添加android:exported="true"。允许外部应用调用。
<activity android:name="com.npf.chat.ui.ChatActivity"
android:exported="true"/>
<service android:name="com.npf.chat.ui.ChatService"
android:exported="true"/>
比如调用方法如下:
/**
* 打开app
*
* @param context 上下文
* @param packageName 包名
* @param activity 启动activity路径
* @return true打工成功,false打开失败
*/
public static boolean openPackage(Context context, String packageName, String activity) {
try {
Context pkgContext = getPackageContext(context.getApplicationContext(), packageName);
Intent intent = new Intent();
// a应用启动b应用
ComponentName cn = new ComponentName(packageName, activity);
intent.setComponent(cn);
// 此处应与B程序中Data中标签一致
Uri uri = Uri.parse(packageName);
intent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (pkgContext != null && intent != null) {
pkgContext.startActivity(intent);
return true;
}
return false;
} catch (Exception e) {
return false;
}
}