距以前写安卓已经有好几年时间了,现在又要重新回顾一遍了,看到了广播机制这块了就写了一个小Demo,过程中遇到了不少的问题,现在总结一下
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
Log.i("取消注册通知","已经取消了");
}
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
Toast.makeText(context, "网络状态发生了变化 网络可用", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "网络状态发生了变化 网络不可用", Toast.LENGTH_SHORT).show();
}
}
}
}
以上是完整的源码,在onCreate里边添加了网络状态的接收器,当然这个接收器是我们自己重写系统后得到的特有接收器,专门用于网络可用状态监控的。好吧,代码写好了跑一下吧,但发现一跑就崩溃,很苦恼,写的都对啊,后来一看log才发现是因为权限问题,没有向AndroidManifest.xml文件添加权限申请,记住这个很重要。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />