为什么我的AsyncTask冻结UI线程?

时间:2019-09-02 08:00:30

标签: java android multithreading user-interface android-asynctask

我有这个问题:我希望在以表格形式插入和提交数据时,AsyncTask开始检查一切正常。 在我现在面对的特定情况下,我想验证输入的用户名尚未被使用,因此我希望它进入服务器并通过php来查询用户的数据库。 我希望当整个过程开始时,用户屏幕不会被遮挡,也就是说,我希望无论如何都允许用户在屏幕内移动。

我附上代码:

public class ControlloUsername extends AsyncTask<String, Void, String> {

AlertDialog a;
Context context;

public ControlloUsername(Context ct) {
    // TODO Auto-generated constructor stub
    context = ct;
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
}

@Override
protected void onPostExecute(String result) { //sync
    // TODO Auto-generated method stub
}

@Override
protected void onProgressUpdate(Void... values) {
    // TODO Auto-generated method stub
}

@Override
protected String doInBackground(String... params) { //sync
    // TODO Auto-generated method stub

    String username = params[0];
    String login_url = Connector.db + "script/usercontrol.php";
    String resultado = "";

    URL u = null;
    try {
        u = new URL(login_url);
    } catch (MalformedURLException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = writer.toString();
    }
    HttpURLConnection http = null;
    try {
        http = (HttpURLConnection) u.openConnection();
    } catch (IOException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = writer.toString();
    }
    try {
        http.setRequestMethod("POST");
    } catch (ProtocolException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = writer.toString();
    }
        http.setDoInput(true);
        http.setDoOutput(true);


        http.setConnectTimeout(7000);


    try {
        OutputStream out = http.getOutputStream();
        BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
        bf.write(post_data);
        bf.flush();
        bf.close();
        out.close();
        InputStream in = http.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "iso-8859-1"));
        String result = "";
        String line = "";
        while ((line = br.readLine()) != null) {
            result += line;
        }
        bf.close();
        in.close();
        http.disconnect();
        return result;
    } catch (ConnectException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = "CONNECT" + writer.toString();
        Log.d("PRINT", "CONNECT");
    } catch (UnsupportedEncodingException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = "UNSUPPORTEDENCODING" + writer.toString();
        Log.d("PRINT", "UNSUPPORTEDENCODING");
    } catch (ProtocolException e) {
       Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = "PROTOCOL" + writer.toString();
        Log.d("PRINT", "PROTOCOL");
    } catch (MalformedURLException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = "MALFORMEDURL" + writer.toString();
        Log.d("PRINT", "MALFORMEDURL");
    } catch (IOException e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        resultado = "IO" + writer.toString();
        Log.d("PRINT", "IO");
    }
    return resultado;
}
}

RegisterActivity

String u = user.getText().toString();
            ControlloUsername bg = new ControlloUsername(this);
            try {
                String res = bg.execute(u).get();
                Log.d("PRINT", res);
                if (res.contains("...

我已经读到这是execute()。get()和AsyncTask自己的方法的问题。

1 个答案:

答案 0 :(得分:0)

AsyncTask完成后,您可以使用界面来返回结果。在您的AsyncTask内部:

onFinishListener mListener; // Create a variable for your interface

// Define the interface & callbacks
public interface onFinishListener{
    // Replace 'variableType' with the appropriate type for your result
    void onFinish(variableType myResult);
}

public void setOnFinishListener(onFinishListener l){
    mListener = l;
}

@Override
protected void onPostExecute(variableType result){
    if(mListener != null){
        mListener.onFinish(result);
    }
}

然后在“活动”中,确保设置界面:

MyAsyncTask task = new MyAsyncTask();
task.execute();
task.setOnFinishListener(new MyAsyncTask.onFinishListener(){
    @Override
    public void onFinish(variableType myResult){
        // The task has finished and you can now use the result
    }
});