当前位置: 代码迷 >> Android >> Android自学札记-17-广播接收者(BroadcastReceiver)
  详细解决方案

Android自学札记-17-广播接收者(BroadcastReceiver)

热度:60   发布时间:2016-04-28 05:52:38.0
Android自学笔记-17-广播接收者(BroadcastReceiver)

广播接收者是Android的四大组件之一,对于这个的定义也是很贴切,在Android系统中,当系统发生了一些状态的改变,系统会向所有的程序广播这个状态的变化。但是这些广播不是所有的我们都接收的,我们只会接收我们关注的广播,这里可以类比广播台,许多个广播台都在发送着不同的广播,我们可以用收音机根据调频接收我们想要听的广播,这里广播台发送的不同的广播,就相当于Android中发送的不同广播,这里的收音机就相当于我们的程序,我们通过设置我们的程序,就能接收到对应的广播。

对于广播接收者,我们想要使用它需要按照如下步骤:

1 自定义一个类并且继承BroadcastReceiver类,实现onReceive方法,这个方法会在接收到广播的时候调用

1 在AndroidMainfest.xml注册该BroadcastReceiver,并且配置相应的参数

下面定义一个广播接收者用于接收短信到来的广播,首先创建一个java类:

import java.text.SimpleDateFormat; import java.util.Date; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage;  public class SmsReceiver extends BroadcastReceiver {     public void onReceive(Context context, Intent intent) {         Object[] pdus = (Object[]) intent.getExtras().get("pdus");         for (Object pdu : pdus) {             //创建一个短信             SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);             //获取发送手机号             String address = sms.getOriginatingAddress();                          //获取短信的内容             String body = sms.getMessageBody();             //获取短信的时间             String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(sms.getTimestampMillis()));             System.out.println(time);             System.out.println(address);             System.out.println(body);         }         //中断手机接收操作         abortBroadcast();     } } 

然后在AndroidMainfest.xml注册该BroadcastReceiver,

 <receiver android:name=".SmsReceiver">             <intent-filter android:priority="999">                 <action android:name="android.provider.Telephony.SMS_RECEIVED" />             </intent-filter>         </receiver> 
对于广播分为两种:有序广播和无序广播,

无序广播所有的广播接收者都可以接收到

有序广播会按照接收者优先级的顺序挨个的接收到,接收者可以使用abortBroadcast();方法随时停止该广播的继续传递

既然有广播的接收者,那么一定也有广播的发送者,在Android发送广播也是需要使用Intent,首先使用Intent创建一个意图,然后使用sendBroadcast(无序广播)或者sendBroadcast(有序广播)方法将广播发送出去。

看下面例子代码,创建了两个广播,并且按照两种方式发送出去了。

package com.mxy;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.View;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }        /**     * 无序广播所有的广播接收者都可以接收到     * 有序广播会按照接收者优先级的顺序挨个的接收到,接收者可以随时停止该广播的继续传递     * @param view     */    public void click(View view) {    	Intent intent = new Intent();    	intent.setAction("com.mxy.broadcastReceiver");    	intent.putExtra("data", "测试数据");    	this.sendBroadcast(intent);    	    	Intent intent1 = new Intent();    	intent1.setAction("com.mxy.OrderedBroadcastReceiver");    	intent1.putExtra("data", "测试数据");    	this.sendOrderedBroadcast(intent1, null);	}    }
下面看一下AndroidMainfest.xml中的相关配置:
 <receiver android:name=".MyBroadcastReceiver">            <intent-filter>                <action android:name="com.mxy.broadcastReceiver"></action>            </intent-filter>        </receiver>                <receiver android:name=".MyBroadcastReceiver1">            <intent-filter android:priority="1000">                <action android:name="com.mxy.OrderedBroadcastReceiver"></action>            </intent-filter>        </receiver>        <receiver android:name=".MyBroadcastReceiver2">            <intent-filter android:priority="10">                <action android:name="com.mxy.OrderedBroadcastReceiver"></action>            </intent-filter>        </receiver>
由上面可以看出无序广播由MyBroadcastReceiver接收,有序广播由MyBroadcastReceiver1和MyBroadcastReceiver2接收,但是他们两个的优先级不同,下面是这三个类的代码:

MyBroadcastReceiver.java

package com.mxy;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyBroadcastReceiver extends BroadcastReceiver {	@Override	public void onReceive(Context context, Intent intent) {		String data = intent.getStringExtra("data");		Log.i("mxy", "获取到data=" + data );	}}

MyBroadcastReceiver1.java

package com.mxy;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyBroadcastReceiver1 extends BroadcastReceiver {	@Override	public void onReceive(Context context, Intent intent) {		String data = intent.getStringExtra("data");		Log.i("mxy", "MyBroadcastRecevier1获取到data=" + data );		//停止广播了		abortBroadcast();	}}

MyBroadcastReceiver2.java

package com.mxy;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyBroadcastReceiver2 extends BroadcastReceiver {	@Override	public void onReceive(Context context, Intent intent) {		String data = intent.getStringExtra("data");		Log.i("mxy", "MyBroadcastRecevier2获取到data=" + data );	}}

对于有序广播来说MyBroadcastReceiver2并不会接收到该广播,因为MyBroadcastReceiver1的优先级比较高,所以广播先呗MyBroadcastReceiver1接收到,并且MyBroadcastReceiver1在接收到后处理完调用了abortBroadcast方法,中断了广播的继续传播,所以优先级小MyBroadcastReceiver2并不能接收到该广播。

例子代码下载地址:http://download.csdn.net/detail/mengxiangyue/7278217

  相关解决方案