Android学习日记(二):
广播:标准广播 有序广播(可以截断)
一、接收系统广播
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.coon.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) {
ConnectivityManager connectionManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context , "network is available",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "network is unavailable",
Toast.LENGTH_SHORT).show();
}
}
}
IntentFilter的实例addAction android.net.coon.CONNECTIVITY_CHANGE
监听网络变化
在AndroidMainfest.xml中加入
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
二、自定义广播
在AndroidMainfest.xml中加入
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.sun.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
可以用Intent传数据
Intent intent = new Intent("com.sun.broadcasttest.MY_BROADCAST");
sendBroadcast(intent)
三、有序广播
Intent intent = new Intent("com.sun.broadcasttest.MY_BROADCAST");
sendOrderBroadcast(intent,null)
四、本地广播
优势:
安全,比全局广播高效。