Android开发之BroadcastReceiver

BroadcastReceiver:广播接收者。用来接收系统或应用中的广播。

在Android系统中,广播体现在方方面面,例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能;当网络状态改变时系统会产生一条广播,接收到这条广播就能及时地做出提示和保存数据等操作;当电池电量改变时,系统会产生一条广播,接收到这条广播就能在电量低时告知用户及时保存进度,等等。

Android中的广播机制设计的非常出色,很多事情原本需要开发者亲自操作的,现在只需等待广播告知自己就可以了,大大减少了开发的工作量和开发周期。而作为应用开发者,就需要数练掌握Android系统提供的一个开发利器,那就是BroadcastReceiver。下面我们就对BroadcastReceiver逐一地分析和演练,了解和掌握它的各种功能和用法。

静态注册:

1 <receiver android:name=".MyReceiver">
2             <intent-filter>
3                 <action android:name="android.intent.action.MY_BROADCAST" />
4                 <category android:name="android.intent.category.DEFAULT" />
5             </intent-filter>
6         </receiver>

广播接收者:

 1 package com.example.hxdn.broadcastreceivertest;
 2 
 3 import android.content.BroadcastReceiver;
 4 import android.content.Context;
 5 import android.content.Intent;
 6 import android.util.Log;
 7 
 8 /**
 9  * Created by hxdn on 2015/9/17.
10  */
11 public class MyReceiver extends BroadcastReceiver {
12     private static  final String TAG="MyReceiver";
13     @Override
14     public void onReceive(Context context,Intent intent)
15     {
16         String msg=intent.getStringExtra("msg");
17         Log.i(TAG,msg);
18     }
19 }

Activity:

 1 package com.example.hxdn.broadcastreceivertest;
 2 
 3 import android.content.Intent;
 4 import android.content.IntentFilter;
 5 import android.support.v7.app.AppCompatActivity;
 6 import android.os.Bundle;
 7 import android.view.Menu;
 8 import android.view.MenuItem;
 9 import android.view.View;
10 import android.widget.Button;
11 
12 public class MainActivity extends AppCompatActivity {
13 
14 
15     MyReceiver myReceiver=null;
16     IntentFilter intentFilter=null;
17     private Button btn1=null;
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_main);
22         init();//动态注册时加入
23         btn1=(Button)findViewById(R.id.btn1);
24         btn1.setOnClickListener(new View.OnClickListener() {
25             @Override
26             public void onClick(View v) {
27                 send();
28             }
29         });
30 
31     }
32     public  void  init()
33     {
34 
35         myReceiver=new MyReceiver();
36         intentFilter=new IntentFilter();
37         intentFilter.addAction("android.intent.action.MY_BROADCAST");
38         registerReceiver(myReceiver,intentFilter);
39     }
40 
41     @Override
42     public boolean onCreateOptionsMenu(Menu menu) {
43         // Inflate the menu; this adds items to the action bar if it is present.
44         getMenuInflater().inflate(R.menu.menu_main, menu);
45         return true;
46     }
47 
48     @Override
49     public boolean onOptionsItemSelected(MenuItem item) {
50         // Handle action bar item clicks here. The action bar will
51         // automatically handle clicks on the Home/Up button, so long
52         // as you specify a parent activity in AndroidManifest.xml.
53         int id = item.getItemId();
54 
55         //noinspection SimplifiableIfStatement
56         if (id == R.id.action_settings) {
57             return true;
58         }
59 
60         return super.onOptionsItemSelected(item);
61     }
62     public  void send()
63     {
64         Intent intent=new Intent("android.intent.action.MY_BROADCAST");
65         intent.putExtra("msg","Hello Receiver");
66         sendBroadcast(intent);
67     }
68     @Override
69     public void onDestroy()
70     {
71         super.onDestroy();
72         unregisterReceiver(myReceiver);
73     }
74 }

动态注册:

 public  void  init()
33     {
34 
35         myReceiver=new MyReceiver();
36         intentFilter=new IntentFilter();
37         intentFilter.addAction("android.intent.action.MY_BROADCAST");
38         registerReceiver(myReceiver,intentFilter);
39     }
需要解绑:
 public void onDestroy()
70     {
71         super.onDestroy();
72         unregisterReceiver(myReceiver);
73     }
否则会抛出异常。

广播主要分为三种:

普通广播(Normal Broadcasts):

1、所有广播接收者都可以接收到的广播,同级别的接收者接收顺序随机不确定。

2、不能拦截广播的继续传播也不能处理处理广播

3、同级别动态注册高于静态注册

 

有序广播(Ordered Broadcasts):

1、按照接收者的优先级接收,优先级可以在intnt-filter里的priority里设置,值越大,优先级越高。

2、可以拦截广播的继续传播,高级别的广播接收器可以决定低级别的广播接收器是否能接收到广播。可以处理广播。

3、同级别动态注册高于静态注册

 

黏性广播(Sticky Broadcasts):

1、不能处理广播传递给下一个接收者,而且广播一直存在,不销毁。(不常用)


在AndroidManifest.xml的广播注册时加上<intent-filter android:priority="1000"
  1. <receiver android:name=".FirstReceiver">  
  2.     <intent-filter android:priority="1000">  
  3.         <action android:name="android.intent.action.MY_BROADCAST"/>  
  4.         <category android:name="android.intent.category.DEFAULT" />  
  5.     </intent-filter>  
  6. </receiver>  
android:priority的值从-1000到1000值越大权限越大。

  1. public void send(View view) {  
  2.     Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  3.     intent.putExtra("msg", "hello receiver.");  
  4.     sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION");  //第二参数不为null则需要权限
  5. }  


使用sendOrderedBroadcast方法发送有序广播时,需要一个权限参数,如果为null则表示不要求接收者声明指定的权限,如果不为null,则表示接收者若要接收此广播,需声明指定权限。这样做是从安全角度考虑的,例如系统的短信就是有序广播的形式,一个应用可能是具有拦截垃圾短信的功能,当短信到来时它可以先接受到短信广播,必要时终止广播传递,这样的软件就必须声明接收短信的权限。

设置权限则发出的广播只有当你有权限时才能收到。

android:priority值越大则代表这个接受者优先级越高。优先级越高可先处理广播。

优先级高的广播可用abortBroadcast();终止这个广播。


posted @ 2015-09-19 23:35  h_shy  阅读(149)  评论(0编辑  收藏  举报