本文实例讲述了Android编程监听网络连接状态改变的方法。分享给大家供大家参考,具体如下:
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
要读取网络状态记得要加权限
希望本文所述对大家Android程序设计有所帮助。