1、,二、广播接收器编写方法,编写步骤,1.编写类继承BroadcastReceiver,复写 onReceiver()方法 2. 注册BroadcastReceiver 3.构建Intent对象 4.调用sendBroadcast()方法发送广播,2.1 编写类继承BroadcastReceiver,复写onReceiver()方法,package com.eoeAndroid.broadcastReceiver;import android.content.BroadcastReceiver; import android.content.Context; import android.con
2、tent.Intent; import android.util.Log;public class MyReceiver extends BroadcastReceiver private static final String TAG = “MyReceiver “; /定义日志标签Overridepublic void onReceive(Context context, Intent intent) Log.i(TAG,“MyReceive onReceive-“); / 输出日志信息 ,2.2 注册BroadcastReceiver的方法,方式一:静态的在AndroidManifest
3、.xml中用标签声明注册,并在标签内用标签注册过滤器。特点:即使应用程序已经被关闭,那么这个BroadcaseReceive依然能接收到广播出来的对象。(常驻型),在AndroidManifest.xml文件中注册Broadcast Receiver,Receiver标签的android:name属性表示将哪一个BroadcastReceiver注册到操作系统上面 filter标签上表示当前BroadcastReceiver是处理哪一类的事件动作的。 Action指的是当前操作是什么类型,即处理数据的方法。如果广播不具备这种特性,不响应。,方式二:动态的在应用程序的代码中进行注册 。先定义并设
4、置好一个IntentFilter对象 注册:Context.registerReceiver(receiver,filter)方法 取消注册:Context.unregisterReceiver(receiver)方法特点:应用程序关闭后,就不再进行监听;可以根据程序的生命周期来做相应的操作。如果一个BroadcastReceiver用于更新UI,通常采用这种方法进行注册。,registerReceiver=(Button)findViewById(R.id.btnregisterReceiver);/创建事件监听器registerReceiver.setOnClickListener(new
5、 OnClickListener() Override public void onClick(View v) receiver=new MyReceiver();IntentFilter filter=new IntentFilter();filter.addAction(ACTION);/动态注册BroadcastReceiverregisterReceiver(receiver, filter); );,unregisterReceiver=(Button)findViewById(R.id.btnunregisterReceiver); /创建事件监听器 unregisterRecei
6、ver.setOnClickListener(new OnClickListener() Override public void onClick(View v) /注销BroadcastReceiver unregisterReceiver(receiver); ); ,public class MainActivity extends Activity /定义action常量protected static final String ACTION = “com.eoeAndroid.broadcastReceiver.RECEIVER_ACTION“;private Button btnB
7、roadcast; /定义Button对象Overridepublic void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.main);btnBroadcast=(Button)findViewById(R.id.btnBroadcast); btnBroadcast.setOnClickListener(new OnClickListener()/为按钮设置单击监听器Override public void onClick(View v)Inte
8、nt intent=new Intent(); /实例化Intentintent.setAction(ACTION); /设置Intent的action属性 sendBroadcast(intent); /发出广播 ); ,MainActivity.java,2.3 构建Intent对象,btnBroadcast=(Button)findViewById(R.id.btnBroadcast);/创建事件监听器 btnBroadcast.setOnClickListener(new OnClickListener()Overridepublic void onClick(View v) Inte
9、nt intent=new Intent(); /实例化Intentintent.setAction(ACTION); /设置Intent的action属性sendBroadcast(intent); /发出广播 );,2.4调用sendBroadcast()方法发送广播,main.xml,效果图当我们点击“注销广播接收器”按钮的时候,这时程序会注销BraodcastReceiver,再点击“发送广播”,LogCat没有输出任何信息。,当我们首先点击“发送广播”按钮的时候,因为程序没有注册BraodcastReceiver,所以LogCat没有输出任何信息。当我们先点击“注册广播接收器”再点击“发送广播”按钮的时候,这时程序会动态的注册BraodcastReceiver,之后会调用onReceive()方法,LogCat输出信息如下:,