简介:

1.按照发送方式分为两类:

(1)标准广播/无序广播

采用异步方式传播,广播发出后,所有的广播接收者几乎是同一时间收到消息的。接收没有先后顺序可言,不可以被拦截。

(2)有序广播

同步执行的广播,在广播发出后,同一时刻只有一个广播接收器可以收到消息,有优先级之分,当广播中的逻辑执行完成后,广播才会继续传播。

 

2按照注册的方式分类

(1)动态注册广播

在代码中注册的,推荐。

(2)静态注册广播

动态注册要求程序必须在运行时才能进行,有一定的局限性,如果我们需要在程序还没启动的时候就可以接收到注册的广播,就需要静态注册了。主要是在AndroidManifest中进行注册。

 

3.按照定义的方式分类

(1)系统广播

Android系统中内置了多个系统广播,每个系统广播都具有特定的intent-filter,其中主要包括具体的action,系统广播发出后,将被相应的BroadcastReceiver接收。系统广播在系统内部当特定事件发生时,由系统自动发出。

(2)自定义广播

由应用程序开发者自己定义的广播

 

Android开发中作用:

(1)当我们需要接收系统发出或者别的程序发出来的消息的时候,就需要用到广播接收器。

(2)我们需要在应用之中传递一些数据时,我们也可以用本地广播来发送和接收这些消息。

(3)可以通过广播给不同的界面发送更新信息,对界面进行刷新。当然也可以用观察者设计模式进行操作(详见:Android开发-通过观察者设计模式刷新和关闭界面)。事实上,从实现原理看,Android中的广播就是使用了观察者模式,基于消息的发布/订阅事件模型。

静态注册举例:
步骤一:在清单文件AndroidManifest.xml注册
<receiver
            android:name="com.huwan.broadcastjingtaidemo.MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>
步骤二:写一个MyBroadcastReceiver.java接收器
package com.huwan.broadcastjingtaidemo;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
// 实现一个广播接收器
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
    }
}
步骤三:MainActivity.java主界面
package com.huwan.broadcastjingtaidemo;
 
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
    Button btn;
    TextView tv;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btn = findViewById(R.id.btn);
        tv = findViewById(R.id.tv);
    }
}
 
静态广播Demo样例下载:
http://www.huwan.xin/Source/AppPackage/ZIP/Android/BroadCastJingtaiDemo.rar
 
 
静态注册传值给activity举例:
(数据传递的方式有很多种,例如bundle,handler,intent,重新发一个广播,第三方eventbus等各种形式;我倾向于使用接口回调来写,但是写了五个小时始终报空指针,内心崩溃,最后使用观察者设计模式,本质其实还是接口回调,但是不知道为什么接口回调我没写成功,如果有朋友写出了比较简单的代码,欢迎和我沟通,谢谢)
步骤一:导入观察者封装好的三个java文件,下面可以下载的demo中有。
步骤二:在清单文件AndroidManifest.xml注册
<receiver
            android:name="com.huwan.broadcastjingtaidemo.MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>
步骤二:写一个MyBroadcastReceiver.java接收器
package com.huwan.broadcastjingtaidemo;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
// 实现一个广播接收器
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
ObserverManager.getInstance().notifyObserver("观察者请刷新信息");
    }
}
步骤三:MainActivity.java主界面
package com.huwan.broadcastjingtaidemo;
 
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
    Button btn;
    TextView tv;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btn = findViewById(R.id.btn);
        tv = findViewById(R.id.tv);
                   ObserverManager.getInstance().add(this);// 注册
}
 
@Override
    public void observerUpData(String content) {
        tv.setText(content);
    }
 
 // 销毁非常非常重要,一定不要忘记了
 @Override
protected void onDestroy() {
      super.onDestroy();
      ObserverManager.getInstance().remove(this);
  }
}

静态广播注册传值Demo样例下载:

http://www.huwan.xin/Source/AppPackage/ZIP/Android/BroadCastJingtaiChuanzhiDemo.rar

参考阅读:Android开发-通过观察者设计模式刷新数据或者关闭界面

参考样例:手机网络切换,通过接口回调通知主界面

Demo下载:

http://www.huwan.xin/Source/AppPackage/ZIP/Android/BroadCastWithNetWorkState.rar

 

 

动态广播:(无序)

package com.huwan.broadcastdynamicdemo1;
 
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Date;
 
public class MainActivity extends Activity {
    Button btn;
    TextView tv;
MyReceiver receiver;               
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //1.注册广播
        receiver = new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.huwan.broadcast.send");
        MainActivity.this.registerReceiver(receiver,filter);
 
        btn = findViewById(R.id.btn);
        tv = findViewById(R.id.tv);
        // 2.点击按钮,发送一个无序的广播
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.huwan.broadcast.send");
                sendBroadcast(intent);
            }
        });
    }
 
    //3.自定义一个广播接收器
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            tv.setText("收到一个无序广播----" + new Date());
        }
}
 
  //4.界面关闭的时候注销广播
    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
 
}
 
// 举例是在主MainActivity中,要发送广播的时候,直接把发送广播的代码写到其他acitivity中即可。
Intent intent = new Intent();
intent.setAction("com.huwan.broadcast.send");
sendBroadcast(intent);
上面三行代码是发送广播的代码,处理接收广播的代码,既可以静态也可以动态。上面都有,就不写demo了。
 
 
动态广播:(有序)
步骤一:配置清单文件AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.huwan.broadcastdynamicdemo2">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".Level1Receiver" >
            <intent-filter android:priority="1000" >
                <action android:name="com.huwan.broadcast.kaihui" />
            </intent-filter>
        </receiver>
        <receiver android:name=".Level2Receiver" >
            <intent-filter android:priority="500" >
                <action android:name="com.huwan.broadcast.kaihui" />
            </intent-filter>
        </receiver>
        <receiver android:name=".Level3Receiver" >
            <intent-filter android:priority="100" >
                <action android:name="com.huwan.broadcast.kaihui" />
            </intent-filter>
        </receiver>
        <receiver android:name=".Level4Receiver" >
            <intent-filter android:priority="0" >
                <action android:name="com.huwan.broadcast.kaihui" />
            </intent-filter>
        </receiver>
    </application>
</manifest>
步骤二:主界面MainActivity.java写一个发送有序广播
package com.huwan.broadcastdynamicdemo2;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("com.huwan.broadcast.kaihui");
                //有序广播,可被拦截,可终止,可以修改数据。
                sendOrderedBroadcast(intent, null, new Level4Receiver(), null, 0, "早上十点开会", null);
            }
        });
    }
}
步骤三:写优先级不同的界面分别接收到消息
Level1Receiver.java
package com.huwan.broadcastdynamicdemo2;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
 
public class Level1Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = getResultData();
        System.out.println("系主任得到的消息:" + message);
        setResultData("早上九点开会");
    }
}
------------------------------------------------------------
Level2Receiver.java
package com.huwan.broadcastdynamicdemo2;
 
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Level2Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = getResultData();
        System.out.println("班主任得到的消息:"+message);
        setResultData("早上八点开会!");
    }
}
------------------------------------------------------------
Level3Receiver.java
package com.huwan.broadcastdynamicdemo2;
 
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
 
public class Level3Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = getResultData();
        System.out.println("班长得到的消息:"+message);
        abortBroadcast(); //无序广播需要终止(重要)
        setResultData("早上七点开会");
    }
}
------------------------------------------------------------
Level4Receiver.java
package com.huwan.broadcastdynamicdemo2;
 
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Level4Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = getResultData();
        System.out.println("学生得到的的消息:" + message);
        new AlertDialog.Builder(context).setTitle("消息")
                .setMessage("学生得到的的消息:"+ message)
                .setPositiveButton("知道了", null).setCancelable(true).show();
    }
}

动态无序广播Demo样例下载:

http://www.huwan.xin/Source/AppPackage/ZIP/Android/BroadCastDynamicdemo2.rar