@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if(info!=null&&info.isAvailable()) { String name = info.getTypeName(); if(info.getType()==ConnectivityManager.TYPE_WIFI) { Toast.makeText(context, "WIFI网络", Toast.LENGTH_SHORT).show(); }else if(info.getType()==ConnectivityManager.TYPE_ETHERNET) { Toast.makeText(context, "有限网络", Toast.LENGTH_SHORT).show(); }else if(info.getType()==ConnectivityManager.TYPE_MOBILE) { Toast.makeText(context, "3G网络", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(context, "无网络", Toast.LENGTH_SHORT).show(); } } }
main方法里
IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(new Main2Activity(),filter);