0121广播机制(一)

0121广播机制(一) 发送方不关心接收方是否接收到

比如来电话,短信等,向广播接收器进行广播,由广播接收器决定如何处理

Broadcast Reveicer A B C D 将他们注册到android上 当android产生一个事件 ABCD 先要判断是否是自己要处理的事件

编写继承BroadcastReceiver的类 复写onReceive()方法

决定哪个接受器接受 如果要注册Broadcast Receiver 即让Reciever能够接收到android发出的事件 要在AndroidManifest里面注册

<receiver android:name="接受的类名">

<intent-filter>//决定这样的receiver接受什么样类型的事件

<action android:name="android.intent.action.RDIT"/>//广播机制里面如果发送intent包含此信息,则这个receiver接受。就好像点到的姓名一样

</intent-filer>

</receiver>

BroadcastReceiver有一定的生命周期,当接受后此接收器(整个类)就会当垃圾扔掉,再次接

受时会重新创建

action 动作,比如洗,擦  包含很多内置的标准动作,详见api-Intent data 衣服,桌子 intent 发送数据,包括action ,data action就是处理数据的方法,data就是要被处理的数据

这里的intent和之前所学习的在两个Activity之间传送数据有点不一样

Intent intent=new Intent();

intent.setAction(Intent.ACTION_EDIT);设置Action属性,即广播出去要喊谁

TestActivity.this.sendBroadcast(intent);//发送广播

Test_BC.java

 1 package com.example.test_bc;
 2 
 3 import android.os.Bundle;
 4 import android.app.Activity;
 5 import android.content.Intent;
 6 import android.view.Menu;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 
11 public class Test_BC extends Activity {
12 
13     private Button broadCast;
14     @Override
15     protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.activity_test__bc);
18         broadCast=(Button)findViewById(R.id.broadCast);
19         broadCast.setOnClickListener(new BroadCastListener());
20     }
21 
22     public class BroadCastListener implements OnClickListener{
23 
24         @Override
25         public void onClick(View v) {
26             // TODO Auto-generated method stub
27             Intent intent=new Intent();
28             intent.setAction(intent.ACTION_EDIT);//;设置Action属性,即广播出去要喊谁
29             Test_BC.this.sendBroadcast(intent);//发送广播
30         }
31         
32     }
33 
34 }

intent.Action_EDIT的值就是manifest里面设置的andriod.intent.action.EDIT

sendBroadcast之后Test_Receiver里面的方法就会执行

Test_Receiver.java

 1 package com.example.test_bc;
 2 
 3 import android.content.BroadcastReceiver;
 4 import android.content.Context;
 5 import android.content.Intent;
 6 
 7 
 8 public class Test_Receiver extends BroadcastReceiver{
 9     public Test_Receiver()
10     {
11         System.out.println("Test_Receiver");
12     }
13 
14     @Override
15     public void onReceive(Context context, Intent intent) {
16         // TODO Auto-generated method stub
17         System.out.println("onReciever");
18         
19     }
20     
21     
22 }

AndroidManifest.xml

1 <receiver android:name="com.example.test_bc.Test_Receiver">
2             <intent-filter>
3                 <action android:name="android.intent.action.EDIT"/>
4             </intent-filter>
5         </receiver>
原文地址:https://www.cnblogs.com/kyxyes/p/2933645.html