import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AlertDialog; import static android.content.Context.CONNECTIVITY_SERVICE; import static android.net.ConnectivityManager.TYPE_WIFI; import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE; public class NetWord extends BroadcastReceiver { private Context context; @Override public void onReceive(Context context, Intent intent) { this.context = context; ConnectivityManager connectionManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { switch (networkInfo.getType()) { case TYPE_MOBILE: showPop(1); break; case TYPE_WIFI: showPop(2); break; default: break; } } else { showPop(3); } } private void showPop(int type) { switch (type) { case 1: myPop("正在使用2G/3G/4G网络"); break; case 2: myPop("正在使用wifi上网"); break; case 3: myPop("当前无网络连接"); break; } } public void myPop(String state) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(state); //设置正面按钮 builder.setPositiveButton("是的", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //设置反面按钮 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }
在监听的Activity的onCreate方法中注册
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
//提成成员变量
networkChangeReceiver = new NetWord(); //这个是自己写的广播接收者
registerReceiver(networkChangeReceiver, intentFilter);
在OnDestory方法中销毁 记得在super.onDestory()之前调用解绑广播!!!
unregisterReceiver(networkChangeReceiver);