关于在android上面的联网判断
具体如下:
- 注意联网的权限
- 注意对手机网络的监听
- 对WiFi是否可用的判断
代码实现如下:
/**
* Created by chen on 15-9-5.
*/
public class ConnectionDetector {
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
} else {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if (ping()) {
if (info[i].getType() == ConnectivityManager.TYPE_MOBILE) {
Log.d("TYPE","手机");
} else {
Log.d("TYPE","wifi");
}
return true;
}
}
}
return false;
}
//wifi连接上,但网络不可用的判断,ping外网
public static boolean ping() {
String result = null;
try {
String ip = "www.baidu.com";
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("the result is ",result);
}
return false;
}
public static void isNetwork(Context context) {
boolean isOnline = isConnectingToInternet(context);
if (!isOnline) {
Toast.makeText(context, R.string.is_online, Toast.LENGTH_SHORT).show();
}
}
}