【发布时间】:2016-04-05 15:50:58
【问题描述】:
我有一个异步任务来检查互联网访问,但有时它不运行,所以如果能解释一下这种奇怪的行为,我将不胜感激。
这是我的代码:
if(activeNetworkinfo.getType()==ConnectivityManager.TYPE_WIFI){
if(NetworkPrivider()){
//this is my asyntask with weird behavior,and always enter here.
CheckInternetAccess ch=new CheckInternetAccess();
ch.execute();
Log.i("sms", "Esta conetado a wifi");
}else{
mycallback.QuePaso(MainActivity.LOCALIZACION_APAGADA_WIFI);
}
}if(activeNetworkinfo.getType()==ConnectivityManager.TYPE_MOBILE){
Log.i("sms", "Esta conetado a datos");
if(GpsON()){
CheckInternetAccess ch=new CheckInternetAccess();
ch.execute();
}else{
mycallback.QuePaso(MainActivity.LOCALIZACION_APAGADA_GPS);
}
}
这是我的异步任务:
public class CheckInternetAccess extends AsyncTask<Void, Void, Boolean> {
//http://clients3.google.com/generate_204
@Override
protected Boolean doInBackground(Void... params) {
Log.i("sms", "Checando acceso a internet...");
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000);
urlc.connect();
return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
}catch (SocketTimeoutException ex){
Log.e("ChecarInternet: ", "Error esperando", ex);
cancel(true);
}catch (ConnectException e) {
Log.e("ChecarInternet: ", "Sin acceso a internet", e);
cancel(true);
} catch (Exception e) {
Log.e("ChecarInternet: ", "Error checking internet connection", e);
cancel(true);
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if(result){
//do someting.
}
}
}
当我安装应用程序时执行异步任务,但如果我关闭应用程序并再次打开已经不执行异步任务,直到那之前,我删除应用程序数据或再次安装。 有时会正常执行。
【问题讨论】:
-
这在你的 onCreate 方法中吗?当您说关闭时,您的意思是您杀死了该应用程序还是它只是在屏幕外?你可能想在 onResume() 中调用它。
-
在oncreate方法中调用一个类,这个类有我在activitymain中实现的asyntask和一个接口,所以当asyntask结果为真时,在“//do someting”行中对我的mainactivity执行一个回调。”当我关闭应用程序时,我的意思是彻底摧毁。我为我的英语感到抱歉,但我来自墨西哥..