首页 > 代码库 > 广播接收者Receiver

广播接收者Receiver

public class broadcastReceiverDemo extends Activity {
    private IntentFilter intentFilter;
    private NetworkChanceReceiver networkChangeReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.broadcase_recever_layout);
        intentFilter =new IntentFilter();//创建intentFilter(目的过滤器)实例
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//添加系统广播的网络变化的值
        networkChangeReceiver = new NetworkChanceReceiver();//创建NetworkChanceReceiver实例
        registerReceiver(networkChangeReceiver,intentFilter);//调用registerReceiver()方法进行注册,将NetworkChangeReceiver的实例
        // 和 IntentFilter 的实例都传了进去,这样NetworkChangeReceiver就会收到所有值为android.net.conn.CONNECTIVITY_CHANGE的广播              播
    }
    @Override
    protected void onDestroy() {//动态注册的广播接收器一定都要取消注册才行,在onDestroy()方法中通过调用unregisterReceiver()方法来实现的
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
    }
    class NetworkChanceReceiver extends BroadcastReceiver{//定义内部类NetworkChanceReceiver,继承于BroadcastReceiver
        @Override
        public void onReceive(Context context, Intent intent) {//当网络发生改变的时候就会执行onReceiver里的代码
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取系统服务的ConnectivityManager(网络连接管理器)实例
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            //通过ConnectivityManager获取网络信息,赋值给networkInfo
            if (networkInfo != null && networkInfo.isAvailable()) {
                //通过isAvailable()判断网络是否联通
                Toast.makeText(context, "网络连接可用",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "请检查网络连接",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}

调用网络信息需要系统权限

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

广播接收者Receiver