Intent对象(组件间的通信原理)

Intent对象是一种可以在运行时动态绑定组件的关键技术,通过使用Intent对象,可以告诉系统你想要实现什么样的操作,也就是Intent对象里面包含的请求内容,请求再由Android操作系统接收到,然后到IntentFilter过滤器中找到已经注册的组件,再调用这个组件就完成了组件间通信的过程。

Intent对象描述的基本内容:1、componentName组件的名称; 2、Action动作名称; 3、Data数据;  4、Category类别; 5、Extra附加数据; 6、Flag标志位

1、显示调用:指定了componentName组件名称。两个Activity和两个xml。

Main.java:

Intent intent = new Intent();

intent.setClass(Main.this,Second.class);

Main.this.startActivity(intent);

 

2、隐式调用:没有明确指出目标组件名称的情况。Android系统要使用IntentFilter过滤器来寻找与隐式Intent相匹配的组件对象,匹配的成功与否与3个元素有关,分别是“action”,“category”,“data”。一个隐式的Intent调用必须通过这3个元素的匹配检查,如果检查成功则成功匹配,如果检查失败则不匹配。这个IntentFilter要在AndroidManifest.xml文件中进行注册,并且至少有一个<action>元素,如果没有则任何的Intent都不匹配。

1)Extra附加数据与静态广播BroadcastReceiver的Dome:

Main.java:

Intent intent = new Intent("test");(test为创建的项目名)

intent.putExtra("sendText","hello world");

Main.this.sendBroadcast(intent);

 

接受类:BroadcastReceiver.java:

void onReceive(Context arg0,Intent arg1)

Toast.makeText(arg0,arg1.getStringExtra("sendText"),Toast.LENGTH_LONG).show;

 

AndroidManifest.xml:

<receiver android:name = ".BroadcastReceiver">

<intent-filter>

  <action android:name = "test"></action>

</intent-filter>

</receiver>

2)Extra附加数据与动态广播BroadcastReceiver的Dome:

Main.java:

private IntentFilter myIntent = new IntentFilter();

private MyBroadCast MyBroadCast = new MyBroadCast();

 

public void onCreat(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

myIntent.addAction("BroadCast");

registerRecevier(MyBroadCast,myIntent);

Button button = (Button)findViewById(R.id.button);

button onClick:

Intent newIntent = new Intent();

newIntent.putExtra("username","hello world");

newIntent.setAction("BroadCast");

Main.this.sendBroadcast(newIntent);

 

protected void onStop(){

  unregisterReceiver(MyBroadCast);

}

 

3)不用广播的Intent隐式

两个Activity(Main,Second)两个xml(一个button)

Main.java:

button:onClick

Intent newIntent = new  Intent("ActionName");

Main.this.startActivity(newIntent);

第二个Activity没有添加内容。

Manifest.xml:

<activity android:name = ".Second" android:label = "@string/app_name">

<intent-filter>

  <action android:name = "ActionName"/>

  <category android:name = "android.intent.categroy.DEFAULT"/>

</intent-filter>

</activity>

4)使用系统自带的ActionName动作

略。(下面有)

注意在manifest中添加权限。

 

3、指定Action的动作名称和Data数据(这个是上面4)的详细版,加了数据)

Dome:

Uri uri = Uri.parse("http://www.baidu.com");

Intent intent = new Intent(Intent.ACTION_VIEW,uri);

Main.this.startActivity(intent);

(先到这儿)

 

转载于:https://www.cnblogs.com/yuxin299/p/4564022.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值