BroadcastReceiver(广播接收者)

来源:互联网 发布:网络创意广告分析报告 编辑:程序博客网 时间:2024/04/28 16:04

广播接收者(BroadcastReceiver):用于接收异步广播Intent.

广播Intent的发送:
主要是通过调用Context.sendBroadcast()、Context.sendOrderedBroadcast()、Context.sendStickyBroadcast()或者Context.sendStickyBroadcast()来实现的。

通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收.


实现一个广播接收者方法如下:
1)第一步:继承BroadcastReceiver,并重写onReceive()方法。

public class IncomingSMSReceiver extends BroadcastReceiver {    public void onReceive(Context context, Intent intent)     {    }}

eg:

public class StaticReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) { //在onReceive里面实现自己想要做的        String msg = intent.getStringExtra("msg");        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();    }}

2)广播注册方式

第二步:注册感兴趣的广播Intent,注册方法有两种:静态注册和动态注册。
静态注册:也就是在AndroidManifest.xml文件中进行注册。
/packages/apps/BasicSmsReceiver/AndroidManifest.xml

 <receiver android:name=".SmsMessageReceiver">39            <intent-filter>40                <action android:name="android.provider.Telephony.SMS_RECEIVED" />41            </intent-filter>42        </receiver>

eg:

<application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.broadcastdemo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <!-- 注册自定义静态广播接收器 -->        <receiver android:name=".StaticReceiver"> <!-- .StaticReceiver是一个java类文件 --!>            <intent-filter>                <action android:name="com.bn.lfx.staticreceiver"/> <!--com.bn.lfx.staticreceiver是自己定义的 --!>            </intent-filter>        </receiver>    </application>

MainActivity.java

public class MainActivity extends Activity {    private Button sendStaticButton;    private Button sendDynamicButton;    private static final String STATICACTION = "com.bn.lfx.staticreceiver";     private static final String DYNAMICACTION = "com.bn.lfx.dynamicreceiver";     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sendStaticButton = (Button) findViewById(R.id.StaticId);        sendDynamicButton = (Button) findViewById(R.id.DynamicId);        sendStaticButton.setOnClickListener(new DIYOnClickListener());        sendDynamicButton.setOnClickListener(new DIYOnClickListener());    }    class DIYOnClickListener implements OnClickListener {        @Override        public void onClick(View v) {            if (v.getId() == R.id.StaticId) {                Intent intent = new Intent();                intent.setAction(STATICACTION);                intent.putExtra("msg", "接收静态广播成功");                sendBroadcast(intent);            } else if(v.getId() == R.id.DynamicId) {                Intent intent = new Intent();                intent.setAction(STATICACTION);                intent.putExtra("msg", "接收动态广播成功");                sendBroadcast(intent);            }          }    }    protected void onStart() {        super.onStart();        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction(DYNAMICACTION);        registerReceiver(DynamicReceiver, intentFilter);    }    private BroadcastReceiver DynamicReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            if (intent.getAction()==DYNAMICACTION) {                String msg = intent.getStringExtra("msg");                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();            }        }    };}

动态注册:

使用代码进行注册

    IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");    IncomingSMSReceiver receiver = new IncomingSMSReceiver();    registerReceiver(receiver, filter);

eg:

 protected void onStart() {        super.onStart();        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction(DYNAMICACTION);        registerReceiver(DynamicReceiver, intentFilter);    }

广播的类型

1.普通广播(Normalbroadcasts):
发送一个广播,所有监听该广播的广播接收者都可以监听到改广播。完全异步的,接收者不能将处理结果传递给下一个接收者,并且无法终止广播Intent的传播;

2.有序广播(Orderedbroadcasts):
按照接收者的优先级顺序接收广播,优先级别在intent-filter中的priority中声明,-1000到1000之间,值越大,优先级越高.可以终止广播意图的继续传播.接收者可以篡改内容.广播Intent的传播一旦终止,后面的接收者就无法接收到广播。如:A的级别高于B,B的级别高于C,那么,广播先传给A,再传给B,最后传给C。A得到广播后,可以往广播里存入数据,当广播传给B时,B可以从广播中得到A存入的数据。

广播接收者的响应性

在Android中,每次广播消息到来时都会创建BroadcastReceiver实例并执行onReceive方法,在onReceive()方法执行完后,广播接收者的实例就会被销毁。当onReceive()方法在10s内没有执行完毕,Android会认为该程序无响应。所以在广播接收者里不能做一些比较耗时的操作,否则会弹出ANR错误。
如果需要完成一项比较耗时的工作,应该通过发送Intent给Service,由Service来完成。这里不能通过子线程来解决,因为广播接收者的生命周期很短,子线程可能还没结束,广播接收者就结束了。此时,广播接收者所在的进程很容易在系统需要内存时被优先杀死,因为它属于空进程,如果它的进程被杀死,那它的子线程也会被杀死。

public class IncomingSMSReceiver extends BroadcastReceiver {    public void onReceive(Context context, Intent intent)     {  //发送Intent启动服务,由服务来完成比较耗时的操作        Intent service=new Intent(context,Intent intent);        context.startService(service);        }}

其他广播:短信到来广播、开机启动、电池电量变化、时间已经改变等广播Intent。还有很多广播。

//电池电量变化<intent-filter>     <action android:name="android.intent.action.BATTERY_CHANGED"/></intent-filter>
//开机启动<intent-filter>    <action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

广播发送

send.setOnClickListener(new OnClickListener(){    @Override    public void onClick(View v)    {        // 创建Intent对象        Intent intent = new Intent();        // 设置Intent的Action属性        intent.setAction("org.crazyit.action.CRAZY_BROADCAST");        intent.putExtra("msg", "简单的消息");        // 发送广播        sendBroadcast(intent);    }});

广播接收

<uses-permission android:name="android.permission.RECEIVE_SMS"/><receiver android:name=".SMSBroadcastReceiver">    <intent-filter android:priority="1000">  //权限,数值越大,权限越高        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>    </intent-filter></receiver>
0 0
原创粉丝点击