我得到了一个AsyncTask,应该检查对主机名的网络访问。但是doInBackground()永远不会超时。有人知道吗?
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();
}
}
这个线程中的大多数答案只检查是否有可用的连接,但不检查该连接是否工作,其他答案不是设备范围,我的解决方案应该在每个设备上工作。
你可以在启动应用程序之前在你的主要活动中删除我的代码,它会快速确定是否有实际的互联网连接,如果有对话框将立即删除,应用程序将被启动,如果没有警报会弹出说应用程序需要互联网连接才能工作。
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Checking Connection");
alertDialog.setMessage("Checking...");
alertDialog.show();
new CountDownTimer(5000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL("http://web.mit.edu/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
isConnected = connection.getResponseCode() == HttpURLConnection.HTTP_OK;
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
if (isConnected == false){
alertDialog.setMessage("Try " + (5 - millisUntilFinished/1000) + " of 5.");
} else {
alertDialog.dismiss();
}
}
@Override
public void onFinish() {
if (isConnected == false) {
alertDialog.dismiss();
new AlertDialog.Builder(activity)
.setTitle("No Internet")
.setMessage("Please connect to Internet first.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// kill the app?
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else {
// Launch the app
}
}
}.start();
这是最简单和简单的方法来检查互联网连接的wifi和移动数据。
public static boolean isConnected(Activity _context) {
if (_context != null) {
ConnectivityManager connMgr = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
boolean wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
boolean mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if (wifiConnected || mobileConnected) {
Log.d(TAG, "Wifi Connected ");
return true;
} else {
showAlert(_context,_context.getString(R.string.err_no_internet));
return false;
}
} else {
showAlert(_context,_context.getString(R.string.err_no_internet));
return false;
}
} else {
Log.e(TAG, "networkConnectivity: Context NULL");
}
return false;
}
看一下ConnectivityManager类。您可以使用这个类来获取主机上活动连接的信息。http://developer.android.com/reference/android/net/ConnectivityManager.html
编辑:你可以使用
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
or
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
并解析返回NetworkInfo对象的DetailedState枚举
EDIT EDIT:查看是否可以访问主机
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.requestRouteToHost(TYPE_WIFI, int hostAddress)
显然,我使用Context.getSystemService(Context.CONNECTIVITY_SERVICE)作为代理来表示
ConnectivityManager cm = Context.getSystemService(Context.CONNECTIVITY_SERVICE);
cm.yourMethodCallHere();