学习目的:1.了解标准广播 有序广播区别(简单,不赘述) 2.接收系统广播 3,发送自定义广播 4.使用本地广播
2.接收系统广播
1.动态注册监听网络变化
1.动态注册监听网络变化
- 需要声明权限
1 | <manifest xmlns:android="http://schemas.android.com/apk/res/android" |
- 新建NetworkChangeReceiver类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//当网络发生变化 系统发出值/为android.net.conn.CONNECTIVITY_CHANGE的广播 要监听什么广播就加什么action
networkChangeReceiver = new NetworkChangeReceiver();//新建NetworkChangeReceiver实例
registerReceiver(networkChangeReceiver, intentFilter);//对其进行注册
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);//动态注册的的广播接收器一定要取消注册
}
class NetworkChangeReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(content,"network changes",Toast.LENGTH_SHORT).show();
}
优化(告诉用户有网还是没网)
1 | class NetworkChangeReceiver extends BroadcastReceiver { |
2.静态注册监听网路变化
直接NEW-other-BoardCastReceriver1
2
3
4
5
6
7
8
9
10
public class BoardCompelteReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Board Complete", Toast.LENGTH_SHORT).show();
}
}
添加权限(部分自动生成)1
2
3
4
5
6
7
8
9
10
11<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />//系统启动时会发android.intent.action.BOOT_COMPLETED值得广播
</intent-filter>
</receiver>
3,发送自定义广播
1.发送标准广播
1 | public class MyBroadcastReceiver extends BroadcastReceiver { |
如何定义先后顺序1
2
3
4
5
6
7<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="100">//100优先级最高
<action android:name="com.example.broadcasttest.MY_BROADCAST"/>
</intent-filter>
是否允许继续传递1
2
3
4ublic void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
abortBroadcast();//表示截断
}
4.使用本地广播
1 | ublic class MainActivity extends AppCompatActivity { |
本地广播的优势
不用担心机密数据泄露
其他程序将广播发送到我们程序内部
比全局广播更高效