一、广播做什么
广播用于进行系统级别的消息通知。
二、接受广播
动态注册监听(两个变量):
1.IntentFilter
2.自定义的Recevier的子类
3.注册receiver,注销receiver
例如:动态监听网络变化:
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
//为intentFilter添加Action(该Action监听网络变化)
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "network changes",
Toast.LENGTH_SHORT).show();
}
}
}
静态注册监听(APP启动时,就进行监听了):
1.在AndroidManifest.xml中进行注册receiver
例如监听开机启动事件:
//Receiver类,当监听到开机事件时,出发onReceive方法
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Boot Complete", Toast.LENGTH_LONG).show();
}
}
注册:
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
由于监听开机启动事件,所以app要获得开机自启权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
三、发送广播(接受者都采用静态注册)
1.发送标准广播:
//定义Intent,并设置action
Intent intent = new Intent("com.example.broadcasttest.
MY_BROADCAST");
//发送广播
sendBroadcast(intent);
2.有序广播:
Intent intent = new Intent("com.example.broadcasttest.
MY_BROADCAST");
//有序广播和标准广播的代码区别
sendOrderedBroadcast(intent, null);
}
三、本地广播(动态监听)
只有本进程才能接受,其他广播可以进行跨进程接受。
1.三个变量:
IntenFilter,LocalBroadcastManager,自定义的Receiver子类。
使用方法:
intentFilter = new IntentFilter();
intentFilter.addAction("com.fzd.LocalReceive");
localBroadcastManager = LocalBroadcastManager.getInstance(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("com.fzd.LocalReceive");
localBroadcastManager.sendBroadcast(intent);
}
});
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);