Intent组件之间实现通信

来源:互联网 发布:阿里云服务器打开端口 编辑:程序博客网 时间:2024/06/05 22:30

Intent(意图)常见的就是用来绑定应用程序组件,并在应用程序间进行 通信.

一般用于启动Activity、启动服务、发送广播 (承担三大组件之间的通信)

启动组件常用方法

对Activity ——–》startActivity(Intent intent) / startActivityForResult(Intent intent)

对service ———-》ComponentName startService(Intent intent)

和boolean bindService(Intent service,ServiceConnection conn,int flags)

对BroadcastReceiver ———》sendBroadcast(Intent intent) /

和 sendBroad(Intent intent,String receiverPermission)

和sendorderedBroadcast(Intent intent,String receiverPermission)

Intent显式意图和隐式意图
显式:Intent intent = new Intent(this,Main2Activity.class);
startActivity(intent);

隐式:在androidMainifest.xml 中设定        例:

这里写图片描述

隐式是这么开启的
Intent intent = new Intent();
intent.setAction(“cn.itcast.xxx”);
将你所设的action和catagory copy copy到这
startActivity(intent);


可设置的有动作(action)类别(catagory)、数据(Uri和数据类型)

然后系统会根据你所定义的查找合适你的组件


通过Intent传递数据

例:Activity1
Intent intent = new Intent();
intent.putExtra(“key”,data);假设data为String型
startActivity(intent);

接收数据
Activity2
Intent Intent = new Intent();
String data = intent.getStringExtra(“key”);

那通过Intent回传数据给原Activity

Activity1:
Intent intent = new intent(this,Activity2.class);
startActivityForResult(intent,请求码);

重写onActivityResult方法
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(resultCode,resultCode,data)
if(resultCode == 请求码)
{
String data = data.getStringExtra(“key”);
}
}

Activity2:
Intent Intent = new intent();
intent.putExtra(“key”,data);
setResult(请求码,intent);
finish();销毁当前活动