ComponentName 启动第三方app的Activity或者Service

ComponentName

顾名思义,就是组件名称,通过调用intent.setComponent()方法,我们可以打开另一个应用的Activity或者Service

创建ComponentName 需要两个参数:

(1)第三方应用的包名

(2)要打开的Activity和Service的全名称(包名+类名)

public ComponentName(@NonNull String pkg, @NonNull String cls) {
        if (pkg == null) throw new NullPointerException("package name is null");
        if (cls == null) throw new NullPointerException("class name is null");
        mPackage = pkg;
        mClass = cls;
    }
  • 启动第三方Acitivity
ComponentName chatActivity =new ComponentName("com.feifei.example", "com.feifei.example.ChatActivity");

    Intent intent =new Intent();

    intent.setComponent(chatActivity);

    startActivity(intent);

  • 启动第三方Service
ComponentName chatService =new ComponentName("com.feifei.example", "com.feifei.example.ChatService");

    Intent intent =new Intent();

    intent.setComponent(chatService );

    startService(intent);

通过Component启动 系统应用
  • 启动媒体库
Intent i = new Intent();

ComponentName comp = new ComponentName("com.android.camera","com.android.camera.GalleryPicker");

i.setComponent(comp);

i.setAction("android.intent.action.VIEW");

startActivity(i);
  • 启动相机
Intent mIntent = new Intent();

ComponentName comp = new ComponentName("com.android.camera","com.android.camera.Camera");

mIntent.setComponent(comp);

mIntent.setAction("android.intent.action.VIEW");

startActivity(mIntent);
注意:
  • 如果该Activity非应用入口(入口Activity默认android:exported="true"),则需要再清单文件中添加 android:exported="true"。Service也需要添加android:exported="true"。允许外部应用调用。
  • 启动第三方app的Activity 的还有另一种方法:intent.setClassName
 Intent intent = new Intent();
        intent.setClassName("org.cvpcs.android.sensordump","org.cvpcs.android.sensordump.AListSensors");
        startActivity(intent);

你可能感兴趣的:(ComponentName 启动第三方app的Activity或者Service)