赵雅智_BroadcastReceiver

赵雅智_BroadcastReceiver

大家好,又见面了,我是全栈君。

BroadcastReceiver  用于接收程序(包含用户开放的程序和系统内建程序)所发出的Broadcast intent

  • 耗电量
  • 开机启动
  • 窃取别人短信
  • 窃取别人电话
开发:
  1. 创建须要启动的BroadcastReceiver(包含启动的Intent系统已经创建的)
    1. 继承BroadcastReceiver类而且重写onReceive()方法
    2. 注冊广播接收者
      • 静态注冊(配置文件)或者动态注冊(代码注冊)
  2. 调用Context的sendBroadcast或sendOrderBroadcast方法来启动指定的BroadcastReceiver

注意:当你启动广播的时候,全部匹配该Intent的BroadcastReceiver都有可能被启动

BroadcastReceiver本质上仅仅是一个系统级的监听器—>他专门负责监听各种程序所发出的的Broadcast


赵雅智_BroadcastReceiver

注冊广播接受者

静态注冊

静态注冊是在AndroidManifest.xml文件里配置的,我们就来为MyReceiver注冊一个广播地址:

        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.MY_BROADCAST"/>  
                <category android:name="android.intent.category.DEFAULT" />  
            </intent-filter>  
        </receiver> 

配置了以上信息之后,仅仅要是android.intent.action.MY_BROADCAST这个地址的广播。MyReceiver都可以接收的到。

注意,这样的方式的注冊是常驻型的,也就是说当应用关闭后,假设有广播信息传来。MyReceiver也会被系统调用而自己主动执行。


详细演示样例:

Myreceiver.java

/** * @author yazhizhao * 20142014-10-20上午10:20:20 */package com.example.android_receive;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;/** * BroadcastReceiver操作输出 *  * @author yazhizhao 20142014-10-20上午10:20:20 */public class Myreceiver extends BroadcastReceiver {	public String TAG = "Myreceiver";	public Myreceiver() {		// TODO Auto-generated constructor stub		Log.i(TAG, "Myreceiver构造方法");	}	@Override	public void onReceive(Context context, Intent intent) {		// TODO Auto-generated method stub		Log.i(TAG, "onReceive");	}}

在AndroidManifest.java注冊广播

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android_receive"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.android_receive.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="com.example.android_receive.Myreceiver" >
            <intent-filter>
                <action android:name="com.example.android_receive.myreceiver" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


MainActivity.java

package com.example.android_receive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

	//定义广播的暴露口
	public String ACTION_INTENT = "com.example.android_receive.myreceiver";
	private Myreceiver myreceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	 
	public void click(View v) {
		sendBroadcast(new Intent(ACTION_INTENT));
	}

	 

}

输出结果:

赵雅智_BroadcastReceiver

动态注冊

动态注冊须要在代码中动态的指定广播地址并注冊,通常我们是在Activity或Service注冊一个广播,以下我们就来看一下注冊的代码:

MyReceiver receiver = new MyReceiver();  
          
IntentFilter filter = new IntentFilter();  
filter.addAction("android.intent.action.MY_BROADCAST");  
          
registerReceiver(receiver, filter);  

注意。registerReceiver是android.content.ContextWrapper类中的方法,Activity和Service都继承了ContextWrapper,所以能够直接调用。在实际应用中。我们在Activity或Service中注冊了一个BroadcastReceiver。当这个Activity或Service被销毁时假设没有解除注冊,系统会报一个异常,提示我们是否忘记解除注冊了。

所以,记得在特定的地方运行解除注冊操作:

@Override  
protected void onDestroy() {  
    super.onDestroy();  
    unregisterReceiver(receiver);  
}  

运行这样行代码就能够解决这个问题了。注意。这样的注冊方式与静态注冊相反,不是常驻型的。也就是说广播会尾随程序的生命周期。


详细代码:

Myreceiver.java同上

MainActivity.java

package com.example.android_receive;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

	//定义广播的暴露口
	public String ACTION_INTENT = "com.example.android_receive.myreceiver";
	private Myreceiver myreceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	/**
	 * button点击事件。触发广播
	 * @author yazhizhao
	 * 20142014-10-20上午11:11:35
	 * @param v
	 */
	public void click(View v) {
		sendBroadcast(new Intent(ACTION_INTENT));
	}

	/**
	 * 在生命周期onResum中动态注冊广播
	 */
	@Override
	protected void onResume() {
		myreceiver = new Myreceiver();
		IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(ACTION_INTENT);
		registerReceiver(myreceiver, iFilter);
		super.onResume();

	}

	/**
	 * 在生命周期onResum中解除注冊广播
	 */
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(myreceiver);
		Log.i("Myreceiver", "unregisterReceiver");
	}

}

运行效果:
赵雅智_BroadcastReceiver

生命周期

赵雅智_BroadcastReceiver

我们能够依据以上随意一种方法完毕注冊。当注冊完毕之后,这个接收者就能够正常工作了。

我们能够用下面方式向其发送一条广播

public void send(View view) {  
    Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
    intent.putExtra("msg", "hello receiver.");  
    sendBroadcast(intent);  
}  

注意,sendBroadcast也是android.content.ContextWrapper类中的方法,它能够将一个指定地址和參数信息的Intent对象以广播的形式发送出去。

点击发送button,运行send方法。控制台打印例如以下:

赵雅智_BroadcastReceiver

看到这种信息打印。表明我们的广播已经发出去了。而且被MyReceiver准确无误的接收到了。


广播类型及广播的收发

普通广播 (Normal broadcasts)

 发送一个广播,所以监听该广播的广播接收者都能够监听到改广播。

异步广播 ,

当处理完之后的Intent ,依旧存在,这时候registerReceiver(BroadcastReceiver, IntentFilter) 还能收到他的值。直到你把它去掉 , 不能将处理结果传给下一个接收者 , 无法终止广播 .

 有序广播 (Ordered broadcasts)

依照接收者的优先级顺序接收广播 , 优先级别在 intent-filter 中的 priority 中声明 ,-1000 到

1000 之间 , 值越大 , 优先级越高 . 能够终止广播意图的继续传播 . 接收者能够篡改内容 .

普通广播(Normal Broadcast)

普通广播对于多个接收者来说是全然异步的,通常每一个接收者都无需等待即能够接收到广播,接收者相互之间不会有影响。对于这样的广播。接收者无法终止广播。即无法阻止其它接收者的接收动作。

为了验证以上论断。我们新建三个BroadcastReceiver。演示一下这个过程,FirstReceiver、SecondReceiver和ThirdReceiver的代码例如以下:

package com.scott.receiver;    import android.content.BroadcastReceiver;  import android.content.Context;  import android.content.Intent;  import android.util.Log;    public class FirstReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "FirstReceiver: " + msg);      }    }  

public class SecondReceiver extends BroadcastReceiver {  
      
    private static final String TAG = "NormalBroadcast";  
      
    @Override  
    public void onReceive(Context context, Intent intent) {  
        String msg = intent.getStringExtra("msg");  
        Log.i(TAG, "SecondReceiver: " + msg);  
    }  
  
}  

public class ThirdReceiver extends BroadcastReceiver {  
      
    private static final String TAG = "NormalBroadcast";  
      
    @Override  
    public void onReceive(Context context, Intent intent) {  
        String msg = intent.getStringExtra("msg");  
        Log.i(TAG, "ThirdReceiver: " + msg);  
    }  
  
}  

然后再次点击发送button。发送一条广播,控制台打印例如以下:

赵雅智_BroadcastReceiver

看来这三个接收者都接收到这条广播了,我们略微改动一下三个接收者。在onReceive方法的最后一行加入下面代码。试图终止广播:

abortBroadcast();  

再次点击发送button,我们会发现,控制台中三个接收者仍然都打印了自己的日志,表明接收者并不能终止广播。


1 ,他决定该广播的级别,级别数值是在 -1000 到 1000 之间 , 值越大 , 优先级越高;

2 。同级别接收是先后是随机的;级别低的收到广播;

3 ,在 android 系统中仅仅要监听该广播的接收者。都可以收到 sendBroadcast(intent) 发出的广播 ;

4 ,不能截断广播的继续传播。

5 ,实验现象,在这种方法发来的广播中。代码注冊方式中,收到的广播的先后和注明优先级最高的他们的先后是随机。假设都没有优先级,代码注冊收到为最先。

有序广播(Ordered Broadcast)

有序广播比較特殊,它每次仅仅发送到优先级较高的接收者那里。然后由优先级高的接受者再传播到优先级低的接收者那里,优先级高的接收者有能力终止这个广播。

为了演示有序广播的流程,我们改动一下上面三个接收者的代码,例如以下:

package com.scott.receiver;  
  
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.os.Bundle;  
import android.util.Log;  
  
public class FirstReceiver extends BroadcastReceiver {  
      
    private static final String TAG = "OrderedBroadcast";  
      
    @Override  
    public void onReceive(Context context, Intent intent) {  
        String msg = intent.getStringExtra("msg");  
        Log.i(TAG, "FirstReceiver: " + msg);  
          
        Bundle bundle = new Bundle();  
        bundle.putString("msg", msg + "@FirstReceiver");  
        setResultExtras(bundle);  
    }  
  
}  

public class SecondReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = getResultExtras(true).getString("msg");          Log.i(TAG, "SecondReceiver: " + msg);                    Bundle bundle = new Bundle();          bundle.putString("msg", msg + "@SecondReceiver");          setResultExtras(bundle);      }    }  

public class ThirdReceiver extends BroadcastReceiver {  
      
    private static final String TAG = "OrderedBroadcast";  
      
    @Override  
    public void onReceive(Context context, Intent intent) {  
        String msg = getResultExtras(true).getString("msg");  
        Log.i(TAG, "ThirdReceiver: " + msg);  
    }  
  
}  

我们注意到。在FirstReceiver和SecondReceiver中最后都使用了setResultExtras方法将一个Bundle对象设置为结果集对象,传递到下一个接收者那里,这样以来,优先级低的接收者能够用getResultExtras获取到最新的经过处理的信息集合。

代码改完之后,我们须要为三个接收者注冊广播地址,我们改动一下AndroidMainfest.xml文件:

<receiver android:name=".FirstReceiver">  
    <intent-filter android:priority="1000">  
        <action android:name="android.intent.action.MY_BROADCAST"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>  
<receiver android:name=".SecondReceiver">  
    <intent-filter android:priority="999">  
        <action android:name="android.intent.action.MY_BROADCAST"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>  
<receiver android:name=".ThirdReceiver">  
    <intent-filter android:priority="998">  
        <action android:name="android.intent.action.MY_BROADCAST"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>  

我们看到。如今这三个接收者的<intent-filter>多了一个android:priority属性。而且依次减小。这个属性的范围在-1000到1000,数值越大。优先级越高。

如今,我们须要改动一下发送广播的代码,例如以下:

public void send(View view) {      Intent intent = new Intent("android.intent.action.MY_BROADCAST");      intent.putExtra("msg", "hello receiver.");      sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION");  }  

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

所以我们在AndroidMainfest.xml中定义一个权限:

<permission android:protectionLevel="normal"              android:name="scott.permission.MY_BROADCAST_PERMISSION" />  

然后声明使用了此权限:

<uses-permission android:name="scott.permission.MY_BROADCAST_PERMISSION" />  

然后我们点击发送button发送一条广播,控制台打印例如以下:

赵雅智_BroadcastReceiver

我们看到接收是依照顺序的。第一个和第二个都在结果集中增加了自己的标记。而且向优先级低的接收者传递下去。

既然是顺序传递,试着终止这样的传递,看一看效果怎样。我们改动FirstReceiver的代码,在onReceive的最后一行加入下面代码:

abortBroadcast();  

然后再次执行程序,控制台打印例如以下:

赵雅智_BroadcastReceiver

此次,仅仅有第一个接收者运行了。其他两个都没能运行,由于广播被第一个接收者终止了。

1。  该广播的级别有级别之分。级别数值是在 -1000 到 1000 之间 , 值越大 , 优先级越高;

2,  同级别接收是先后是随机的,再到级别低的收到广播。

3,  同级别接收是先后是随机的,假设先接收到的把广播截断了,同级别的例外的接收者是无法收到该广播的。(abortBroadcast() )

4 ,能截断广播的继续传播。高级别的广播收到该广播后。能够决定把该钟广播是否截断掉。

5 ,实验现象,在这种方法发来的广播中,代码注冊方式中,收到广播先后次序为:注明优先级的、代码注冊的、没有优先级的;假设都没有优先级。代码注冊收到为最先。

异步广播的发送和接收:

sendStickyBroadcast(intent);

当处理完之后的Intent ,依旧存在。直到你把它去掉。

发这个广播须要权限<uses-permission android:name=“android.permission.BROADCAST_STICKY” />

去掉是用这种方法removeStickyBroadcast(intent); 但别忘了在运行这种方法的应用里面 AndroidManifest.xml相同要加上面的权限;

sendStickyOrderedBroadcast(intent, resultReceiver, scheduler,

       initialCode, initialData, initialExtras)

这种方法具有有序广播的特性也有异步广播的特性;

发送这个广播要: <uses-permission android:name=“android.permission.BROADCAST_STICKY” /> 这个权限。才干使用这种方法。

假设您并不拥有该权限,将抛出 SecurityException 的。

实验现象( sendStickyOrderedBroadcast ()中),在这种方法发来的广播中。代码注冊方式中。收到广播先后次序为:注明优先级的、代码注冊的、没有优先级的。假设都没有优先级。代码注冊收到为最先。

常见的样例

开机启动服务

我们常常会有这种应用场合,比方消息推送服务,须要实现开机启动的功能。

要实现这个功能,我们就能够订阅系统“启动完毕”这条广播,接收到这条广播后我们就能够启动自己的服务了。

我们来看一下BootCompleteReceiver和MsgPushService的详细实现:

package com.scott.receiver;  
  
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.util.Log;  
  
public class BootCompleteReceiver extends BroadcastReceiver {  
      
    private static final String TAG = "BootCompleteReceiver";  
      
    @Override  
    public void onReceive(Context context, Intent intent) {  
        Intent service = new Intent(context, MsgPushService.class);  
        context.startService(service);  
        Log.i(TAG, "Boot Complete. Starting MsgPushService...");  
    }  
  
}  


package com.scott.receiver;  
  
import android.app.Service;  
import android.content.Intent;  
import android.os.IBinder;  
import android.util.Log;  
  
public class MsgPushService extends Service {  
  
    private static final String TAG = "MsgPushService";  
      
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.i(TAG, "onCreate called.");  
    }  
      
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        Log.i(TAG, "onStartCommand called.");  
        return super.onStartCommand(intent, flags, startId);  
    }  
  
    @Override  
    public IBinder onBind(Intent arg0) {  
        return null;  
    }  
}  

然后我们须要在AndroidManifest.xml中配置相关信息:

<!-- 开机广播接受者 -->  
<receiver android:name=".BootCompleteReceiver">  
    <intent-filter>  
        <!-- 注冊开机广播地址-->  
        <action android:name="android.intent.action.BOOT_COMPLETED"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>  
<!-- 消息推送服务 -->  
<service android:name=".MsgPushService"/>  

我们看到BootCompleteReceiver注冊了“android.intent.action.BOOT_COMPLETED”这个开机广播地址,从安全角度考虑,系统要求必须声明接收开机启动广播的权限。于是我们再声明使用以下的权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  


经过上面的几个步骤之后,我们就完毕了开机启动的功能,将应用执行在模拟器上。然后重新启动模拟器,控制台打印例如以下:

赵雅智_BroadcastReceiver

假设我们查看已执行的服务就会发现,MsgPushService已经执行起来了。

网络状态变化

在某些场合,比方用户浏览网络信息时,网络突然断开。我们要及时地提醒用户网络已断开。要实现这个功能,我们能够接收网络状态改变这样一条广播,当由连接状态变为断开状态时。系统就会发送一条广播。我们接收到之后,再通过网络的状态做出对应的操作。以下就来实现一下这个功能:

package com.scott.receiver;    import android.content.BroadcastReceiver;  import android.content.Context;  import android.content.Intent;  import android.net.ConnectivityManager;  import android.net.NetworkInfo;  import android.util.Log;  import android.widget.Toast;    public class NetworkStateReceiver extends BroadcastReceiver {            private static final String TAG = "NetworkStateReceiver";            @Override      public void onReceive(Context context, Intent intent) {          Log.i(TAG, "network state changed.");          if (!isNetworkAvailable(context)) {              Toast.makeText(context, "network disconnected!", 0).show();          }      }            /**      * 网络是否可用      *       * @param context      * @return      */      public static boolean isNetworkAvailable(Context context) {          ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);          NetworkInfo[] info = mgr.getAllNetworkInfo();          if (info != null) {              for (int i = 0; i < info.length; i++) {                  if (info[i].getState() == NetworkInfo.State.CONNECTED) {                      return true;                  }              }          }          return false;      }    }  

再注冊一下这个接收者的信息:

<receiver android:name=".NetworkStateReceiver">  
    <intent-filter>  
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>  

由于在isNetworkAvailable方法中我们使用到了网络状态相关的API,所以须要声明相关的权限才行。以下就是相应的权限声明:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  

我们能够測试一下,比方关闭WiFi。看看有什么效果。

电量变化

假设我们阅读软件,可能是全屏阅读,这个时候用户就看不到剩余的电量。我们就能够为他们提供电量的信息。

要想做到这一点。我们须要接收一条电量变化的广播,然后获取百分比信息。这听上去挺简单的,我们就来实现下面:

package com.scott.receiver;    import android.content.BroadcastReceiver;  import android.content.Context;  import android.content.Intent;  import android.os.BatteryManager;  import android.util.Log;    public class BatteryChangedReceiver extends BroadcastReceiver {        private static final String TAG = "BatteryChangedReceiver";            @Override      public void onReceive(Context context, Intent intent) {          int currLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);  //当前电量          int total = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);      //总电量          int percent = currLevel * 100 / total;          Log.i(TAG, "battery: " + percent + "%");      }    }  

然后再注冊一下广播接地址信息就能够了:

<receiver android:name=".BatteryChangedReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.BATTERY_CHANGED"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>  

当然,有些时候我们是要马上获取电量的。而不是等电量变化的广播,比方当阅读软件打开时马上显示出电池电量。我们能够按下面方式获取:

Intent batteryIntent = getApplicationContext().registerReceiver(null,  
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));  
int currLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);  
int total = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);  
int percent = currLevel * 100 / total;  
Log.i("battery", "battery: " + percent + "%"); 

怎么用好 BroadcastReceiver 

假设须要完毕一项比較耗时的工作 , 应该通过发送 Intent 给 Service, 由 Service 来完毕 . 这里不能使用子线程来解决 , 由于 BroadcastReceiver 的生命周期非常短 , 子线程可能还没有结束,BroadcastReceiver 就先结束了 .BroadcastReceiver 一旦结束 , 此时 BroadcastReceiver 的所在进程非常easy在系统须要内存时被优先杀死 , 由于它属于空进程 ( 没有不论什么活动组件的进程 ). 假设它的宿主进程被杀死 , 那么正在工作的子线程也会被杀死 . 所以採用子线程来解决是不可靠的 .

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/115964.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号