首页 > 代码库 > 广播接受者判断网络连接状态

广播接受者判断网络连接状态

需求:网络连接分三种状态:无网络、移动数据、WIFI

public class ConnectionChangeReceiver extends BroadcastReceiver {    private AlertDialog alertDialog;    //标记的作用是为了避免对话框弹出多次    private boolean isConnect = false;//标记是否连接    private boolean isGPRS = false;//标记连接方式是移动网络    private boolean isWifi = false;//标记连接方式是wifi    @Override    public void onReceive(final Context context, Intent intent) {        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE);        NetworkInfo networkInfo = cm.getActiveNetworkInfo();        //无网络状态        if(networkInfo == null || !networkInfo.isConnected()){            if(isConnect){                alertDialog = new AlertDialog(context).builder();                alertDialog.setTitle("已关闭移动数据");                alertDialog.setMsg("您可以在“设置”中为此应用打开移动数据。");                alertDialog.setPositiveButton("好", new View.OnClickListener() {                    @Override                    public void onClick(View v) {                    }                });                alertDialog.setNegativeButton("设置", new View.OnClickListener() {                    @Override                    public void onClick(View v) {                        context.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));                    }                });                LogHelp.i("dialog","dialog1");                isGPRS = false;                isWifi = false;                isConnect = false;                alertDialog.show();            }        }else if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {            if(!isGPRS){                //只有GPRS,没有wifi的状态                alertDialog = new AlertDialog(context).builder();                alertDialog.setTitle("流量使用提示");                alertDialog.setMsg("当前网络无Wi-Fi,继续播放可能会被运营商收取流量费用");                alertDialog.setPositiveButton("继续播放", new View.OnClickListener() {                    @Override                    public void onClick(View v) {                    }                });                alertDialog.setNegativeButton("停止播放", new View.OnClickListener() {                    @Override                    public void onClick(View v) {                    }                });                LogHelp.i("dialog", "dialog2");                isWifi = false;                isGPRS = true;                isConnect = true;                alertDialog.show();            }        }else if(networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI){            if(!isWifi){                LogHelp.i("dialog", "dialog3");                isGPRS = false;                isConnect = true;                isWifi = true;            }        }    }}

 

广播接受者判断网络连接状态