如何检查在Android上网? InetAddress类从不超时... [英] How to check internet access on Android? InetAddress never timeouts...
问题描述
我有一个的AsyncTask
是应该检查网络访问的主机名。但 doInBackground()
永不超时。任何人都有一个线索吗?
公共类HostAvailabilityTask扩展的AsyncTask<字符串,太虚,布尔> {
私营主为主;
公共HostAvailabilityTask(主主){
this.main =为主;
}
保护布尔doInBackground(字符串... PARAMS){
Main.Log(doInBackground()isHostAvailable():+参数[0]);
尝试 {
返回InetAddress.getByName(PARAMS [0])isReachable(30)。
}赶上(UnknownHostException异常E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
返回false;
}
保护无效onPostExecute(布尔......结果){
Main.Log(onPostExecute());
如果(结果[0] == FALSE){
main.setContentView(R.layout.splash);
返回;
}
main.continueAfterHostCheck();
}
}
@Eddie。只是一个小修改,以您的解决方案 - 如果设备处于飞行模式(或presumably在其他情况下,有无可用网络), cm.getActiveNetworkInfo()
将空
,所以你需要添加一个空
检查。
以下修改方案:
公共布尔isOnline(){
ConnectivityManager厘米=
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
的NetworkInfo的NetInfo = cm.getActiveNetworkInfo();
返回的NetInfo = NULL和放大器;!&安培; netInfo.isConnectedOrConnecting();
}
另外添加以下权限到的AndroidManifest.xml
:
<使用-权限的Android:名称=android.permission.ACCESS_NETWORK_STATE/>
另外一个小点,如果你确实需要在给定时间点的网络连接,那么它可能是最好使用 netInfo.isConnected()
而不是 netInfo.isConnectedOrConnecting
。我想这是最多不过indivudal用例。
I got a AsyncTask
that is supposed to check the network access to a host name. But the doInBackground()
is never timed out. Anyone have a clue?
public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {
private Main main;
public HostAvailabilityTask(Main main) {
this.main = main;
}
protected Boolean doInBackground(String... params) {
Main.Log("doInBackground() isHostAvailable():"+params[0]);
try {
return InetAddress.getByName(params[0]).isReachable(30);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean... result) {
Main.Log("onPostExecute()");
if(result[0] == false) {
main.setContentView(R.layout.splash);
return;
}
main.continueAfterHostCheck();
}
}
@Eddie. Just a minor edit to your solution - if the device is in airplane mode (or presumably in other situations where there's no available network), cm.getActiveNetworkInfo()
will be null
, so you need to add a null
check.
Modified solution below:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
Also add the following permission to the AndroidManifest.xml
:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use netInfo.isConnected()
rather than netInfo.isConnectedOrConnecting
. I guess this is up to the indivudal use-case however.
这篇关于如何检查在Android上网? InetAddress类从不超时...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!