BroadcastReceiver(广播)

 

在 Android 中使用 Activity, Service, Broadcast, BroadcastReceiver

活动(Activity) – 用于表现功能

服务(Service) – 相当于后台运行的 Activity

广播(Broadcast) – 用于发送广播

广播接收器(BroadcastReceiver) –  用于接收广播

Intent – 用于连接以上各个组件,并在其间传递消息

==========================================================================

BroadcastReceiver:

在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。而BroadcastReceiver是对发送出来的 Broadcast进行过滤接受并响应的一类组件。下面将详细的阐述如何发送Broadcast和使用BroadcastReceiver过滤接收的过程:

首先在需要发送信息的地方,把要发送的信息和用于过滤的信息(如Action、Category)装入一个Intent对象,然后通过调用 Context.sendBroadcast()、sendOrderBroadcast()或sendStickyBroadcast()方法,把 Intent对象以广播方式发送出去。

当Intent发送以后,所有已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiver的onReceive()方法。所以当我们定义一个BroadcastReceiver的时候,都需要实现onReceive()方法。

注册BroadcastReceiver有两种方式:

一种方式是,静态的在AndroidManifest.xml中用<receiver>标签生命注册,并在标签内用<intent- filter>标签设置过滤器。

 

<receiver android:name=".Test_Receiver" > 
    <intent-filter>               
        <action android:name="android.intent.action.sss" />         
    </intent-filter>     
 </receiver>

类文件里面的代码:

      Intent intent = new Intent(); 
      intent.setAction("android.intent.action.sss");  
      Test_BCActivity.this.sendBroadcast(intent);

 

 

另一种方式是,动态的在代码中先定义并设置好一个 IntentFilter 对象,然后在需要注册的地方调Context.registerReceiver()方法,如果取消时就调用 Context.unregisterReceiver()方法。如果用动态方式注册的BroadcastReceiver的Context对象被销毁时,BroadcastReceiver也就自动取消注册了。(特别注意,有些可能需要后台监听的,如短信消息)

另外,若在使用sendBroadcast()的方法是指定了接收权限,则只有在AndroidManifest.xml中用<uses- permission>标签声明了拥有此权限的BroascastReceiver才会有可能接收到发送来的Broadcast。同样,若在注册BroadcastReceiver时指定了可接收的Broadcast的权限,则只有在包内的AndroidManifest.xml中 用<uses-permission>标签声明了,拥有此权限的Context对象所发送的Broadcast才能被这个 BroadcastReceiver所接收。

绑定receiver:

public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; 
// 生成一个receiver对象 
    receiver = new Test_Receiver();    
 // 生成一个filter对象   
  IntentFilter intentFilter = new IntentFilter();    
 // 为filter添加一个action     
intentFilter.addAction(SMS_RECEIVED_ACTION);     
Test_BCActivity.this.registerReceiver(receiver, intentFilter);

解除绑定receiver:

Test_BCActivity.this.unregisterReceiver(receiver);

两者的主要区别是xml文件中注册的广播机制在应用程序关闭之后依然运行。一直运行。通过代码注册的广播是在应用程序关闭之后是关闭的及时生效。

 

关于receiver类的代码:

public class Test_Receiver extends BroadcastReceiver { 
 public Test_Receiver() { 
  Log.d("Test_Receiver", "构造函数");  }
  @Override  public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub   
Log.d("Test_Receiver", "OnReceive");  } }  

 

 

 

附一个完整的例子:

package com.zjt.innerreceiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class ServiceTest extends Service{

	public final static String TAG = "ServiceTest";
	
	private Receiver mReceiver;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		//注册Receiver
		mReceiver = new Receiver(this);  
		mReceiver.registerActionAndScheme(Intent.ACTION_MEDIA_EJECT, "file"); 
		mReceiver.registerActionAndScheme(Intent.ACTION_MEDIA_REMOVED, "file"); 
		mReceiver.registerActionAndScheme(Intent.ACTION_MEDIA_MOUNTED, "file"); 
		mReceiver.registerActionAndScheme(Intent.ACTION_PACKAGE_REMOVED, "package"); 
                mReceiver.registerActionAndScheme(Intent.ACTION_PACKAGE_ADDED, "package");
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		//注销Receiver
		unregisterReceiver(mReceiver);  
	}



	class Receiver extends BroadcastReceiver {    
        
		Context mContext;    
  
        public Receiver(Context context){    
            mContext = context;    
        }    
            
        //动态注册  
        public void registerAction(String action){    
            IntentFilter filter = new IntentFilter();    
            filter.addAction(action);        
            mContext.registerReceiver(this, filter);    
        }  
        
        public void registerActionAndScheme(String action, String dataScheme){    
            IntentFilter filter = new IntentFilter();    
            filter.addAction(action);        
            filter.addDataScheme(dataScheme);
            mContext.registerReceiver(this, filter);    
        } 
            
        @Override    
        public void onReceive(Context context, Intent intent) {    
        	String action = intent.getAction();
        	Log.d(TAG, "action:" + action);
        	
        	if(action.equals(Intent.ACTION_MEDIA_EJECT)) {
        		Log.d(TAG , "sdcard has been ejected");
        	} else if (action.equals(Intent.ACTION_MEDIA_REMOVED)) {
        		Log.d(TAG , "sdcard has been removed");
        	} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
        		Log.d(TAG , "sdcard has been mounted");
        	} else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
        		Log.d(TAG, "Intent.ACTION_PACKAGE_REMOVED");
        	} else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
        		Log.d(TAG, "Intent.ACTION_PACKAGE_ADDED");
        	}
             
        }    
            
    }    
}

 

    原文作者:fangchao3652
    原文地址: https://blog.csdn.net/fangchao3652/article/details/8703473
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞