componentname怎么用

这篇文章主要介绍componentname怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

  ComponentName,顾名思义,就是组件名称,通过调用Intent中的setComponent方法,我们可以打开另外一个应用中的Activity或者服务。

  如何实例化一个ComponentName

  实例化一个ComponentName需要两个参数,第一个参数是要启动应用的包名称,这个包名称是指清单文件中列出的应用的包名称:

  第二个参数是你要启动的Activity或者Service的全称(包名+类名),代码如下:

  启动一个Activity:

  Intentintent=newIntent();

     intent.setComponent(newComponentName("com.example.otherapp",

       "com.example.otherapp.MainActivity2"));

     startActivity(intent);

  ComponentName使用

  ComponentName:可以启动其他应用的Activity、Service.

  ComponentNamechatActivity=newComponentName(param1,param2);

  param1:Activity、Service所在应用的包名

  param2:Activity、Service的包名+类名

  Activity:

  ComponentNamechatActivity=newComponentName("com.npf.chat","com.npf.chat.ui.ChatActivity");

  Intentintent=newIntent();

  intent.setComponent(chatActivity);

  startActivity(intent);

  Service:

  ComponentNamechatService=newComponentName("com.npf.chat","com.npf.chat.ui.ChatService");

  Intentintent=newIntent();

  intent.setComponent(chatService);

  startService(intent);

  注:

  如果该Activity非应用入口(入口Activity默认android:exported="true"),则需要再清单文件中添加android:exported="true"。Service也需要添加android:exported="true"。允许外部应用调用。

以上是“componentname怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!