gpt4 book ai didi

android - 来自 AsyncTask 的静态方法调用是异步的?

转载 作者:行者123 更新时间:2023-11-29 00:09:48 25 4
gpt4 key购买 nike

我正在尝试使用 AsyncTask 检查互联网连接是否可用,然后执行一些操作。

我的问题是在执行缓刑期间我无法与 UI 交互。 “progressbar”在前面,如果我尝试点击按钮,UI 没有响应

这是对 AsyncTask 的调用

@Override
public void onStart(){
super.onStart();
AsyncHttpHandler check = new AsyncHttpHandler(**paramaters**);
check.execute("checkshared");

}

这是AsyncTask的代码

public class AsyncHttpHandler extends AsyncTask<String, Integer, String>{


public AsyncHttpHandler(Context c, Intent i, Bundle _data, String _language){
ctx = c;
intent = i;
data = _data;
language = _language;

startClock();


}

public void startClock(){
mDialog = new ProgressDialog(ctx,R.style.MyTheme);
mDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
mDialog.setCancelable(false);
mDialog.show();
}


@SuppressWarnings("unchecked")
@Override
protected String doInBackground(String... peticion) {
String response = "null";
//call to check if internet connection is available
if(Utils.isInternetConn(ctx)){

try {

// do stuff
response = "...";

}
else response = "offline";

return response;
}
}

protected void onPostExecute(String response) {
if(mDialog != null) mDialog.dismiss();

if(!response.equals("offline")){
// do stuff
}
else Toast.makeText(ctx, ctx.getResources().getString(ctx.getResources().getIdentifier(language+"_toast_nointernet", "string", ctx.getPackageName())), Toast.LENGTH_LONG).show();

}



}

这是检查互联网连接是否可用的方法:

public static Boolean isInternetConn(Context ctx){

ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

boolean conectado = false;
if((wifi != null && wifi.isConnectedOrConnecting()) || (mobile != null && mobile.isConnectedOrConnecting())){

try {

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL myurl = new URL("http://www.google.com");
URLConnection connection;
connection = myurl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
conectado = true;
httpConnection.disconnect();
}
else {
httpConnection.disconnect();
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return conectado;
}

我做错了什么?

最佳答案

问题不在于您的 AsyncTask 调用静态方法。这也将执行异步。问题是您在任务完成之前显示进度对话框。当然,当您的进度对话框可见时,您将无法与 UI 交互。如果您想与 UI 交互,请以另一种方式显示您的进度,而不是通过对话框。

关于android - 来自 AsyncTask 的静态方法调用是异步的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com