广播Broadcastreceiver分为两种
1:静态注册
2:动态注册
静态注册
拿网络来讲个例子:
无界面代码
新建一个BroadCastReceiver
代码:
public class MyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivitymanager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
if (networkinfo != null && networkinfo.isAvailable()) {
Toast.makeText(context, "网络已连接", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "网络已断开", Toast.LENGTH_SHORT).show();
}
}
}
在配置文件中注册
<receiver android:name=".MyBroadCastReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
动态注册
拿点击一个按钮发送广播,显示文字为例
界面xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/receiver_str"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="send"
android:textColor="#000000" />
</LinearLayout>
java代码:
public class MainActivity extends Activity {
BroadcastReceiver broadcastReceiver;
TextView receiver_str;
String ss;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver_str =(TextView)findViewById(R.id.receiver_str);
findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("my_broadcast");
intent.putExtra("ss","hello");
sendOrderedBroadcast(intent,null);
broadcastReceiver =new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ss= intent.getExtras().getString("ss");
receiver_str.setText(ss);
}
};
registerReceiver(broadcastReceiver,new IntentFilter("my_broadcast"));
}
});
}
}
好处:哪里的界面需要获取传送的值,就在那里去创建broadCastReceiver,然后注册即就是new BroadCastReceiver()
个人总结:
1.静态注册:随时都能监测广播 就拿上面的网络变化广播来说
2.动态注册:在需要传输数据的类中,新建一个匿名对象,就能数据 比较灵活
3.OnReceive()方法结束了,也就结束了,后面的代码不执行
4.记得在OnDestory()方法中unregeisterReceiver(xx);