检查我是否在网络本地,但没有互联网,Android
问题描述:
如何才能知道我是否在Network Local中连接,但没有连接到Internet或没有接收数据?我试图找到一种方法,可以检查它...请帮我,我正在安卓工作检查我是否在网络本地,但没有互联网,Android
答
这是你如何能做到这
检查网络可用这样
功能1
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
之后,检查这样,如果互联网可
功能2
public static boolean isInternetAccessible(Context context) {
if (isWifiAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Couldn't check internet connection", e);
}
} else {
Log.d(LOG_TAG, "Internet not available!");
}
return false;
}
- 如果功能1返回错误 - >未连接到网络
- 如果函数返回1 true并且函数2返回false - >已连接但没有intenet
- 如果两个函数都返回true - >可以访问Internet
注意您将需要这两个权限在清单
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我测试了它
答
请验证您是否被允许从您的APP访问互联网。
该权限在AndroidManifest.xml
中定义。 请确保您有以下权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
代码方法
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000);
urlc.connect();
Log.i(Tag,Integer.toString(urlc.getResponseCode()));
和它的伟大工程,非常感谢Rohit5k2 – 2015-02-09 19:11:59
很高兴我能帮忙。 – Rohit5k2 2015-02-09 19:15:22
你会如何处理异步任务?我希望布尔值返回到调用它的活动。 – TheLearner 2017-09-28 16:55:56