项目中遇到这个问题,百度了下有问这个问题的,也不知道有没有解决,就这样找了好久才找到答案
我是需要在有数据连接的时候做操作,具体的原因我也没搞太明白,希望有清楚的朋友看到后指点下~~~
首先贴下广播接收者的代码
private class ConnectionChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
NetworkInfo netInfo = (NetworkInfo) b.get(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo.State state = netInfo.getState();
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
Log.i("ConnectionChangeReceiver", "网络状态改变");
String phoneNO = sp.getString(Constants.PHONE_NUMBER, null);
if ((state == NetworkInfo.State.CONNECTED) && (activeNetInfo != null) && (activeNetInfo.getType() != netInfo.getType())) {
return;
}
boolean isConnected = isNetworkAvailable(connManager, context);
if(isConnected) {
//连接上网络的操作
}
}
}
//判断是否有建立数据连接
public static boolean isNetworkAvailable(ConnectivityManager connManager,Context context) {
if (connManager == null) {
} else {
NetworkInfo[] info = connManager.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
//参考文章
http://www.blogjava.net/liuyanbo/archive/2012/09/17/387882.html
和
http://bbs.csdn.net/topics/390254217