BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(context, intent.getAction(), 1).show();
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo activeInfo = manager.getActiveNetworkInfo();
Toast.makeText(context, "mobile:"+mobileInfo.isConnected()+"\n"+"wifi:"+wifiInfo.isConnected()
+"\n"+"active:"+activeInfo.getTypeName(), 1).show();
} //如果无网络连接activeInfo为null
}
在清单文件中注册 BroadcastReceiver
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
要读取网络状态记得要加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>