如何在doInBackground方法中调用UI或UI线程

时间:2016-12-20 14:26:13

标签: android multithreading android-asynctask ui-thread

我使用AsyncTask类来连接数据库。根据数据,我将创建动态EditTextCheckbox,而不涉及XML文件。

lView = new LinearLayout(this); - 我在这里遇到了错误!

enter image description here

有没有办法在doInBackground方法中调用UI线程!

提前致谢!!

@Override
protected String doInBackground(String... param) {

    HashMap<String, bean> map = new HashMap<String, bean>();

    try {
        url = new URL("http://localhost/app/alldata.php");
    } catch (MalformedURLException e) {
        Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
        e.printStackTrace();
        return null;
    }

    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestMethod("POST");

        // setDoInput and setDoOutput method depict handling of both send and receive
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Append parameters to URL
        Uri.Builder builder = new Uri.Builder()
                .appendQueryParameter("user_id", "user_id")
                .appendQueryParameter("dpt_id","dptid");
        String query = builder.build().getEncodedQuery();

        // Open connection for sending data
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();
        conn.connect();

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    try {
        int response_code = conn.getResponseCode();
        lView = new LinearLayout(this);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        conn.disconnect();
    }

    return null;
}

3 个答案:

答案 0 :(得分:3)

您可以从publishProgress()方法调用doInBackground并覆盖将在UI线程上调用的onProgressUpdate

显然,这是用于进步的用法。您应该明确区分一个工作单元作为背景,然后在onPostExecute中正常处理。

答案 1 :(得分:1)

如果您真的想与主UI线程进行通信,可以使用:

runOnUiThread(new Runnable() {
        @Override
        public void run() {
         //place your code here
     }
});

答案 2 :(得分:0)

更优雅的方法是传递回调函数,以便在AsyncTask完成其工作时,它可以调用Activity中的方法调用,然后您可以在那里进行必要的更改。

我建议保留这样的界面。

public interface HttpResponseListener {
    void httpResponseReceiver(String result);
}

现在,在Activity中,您需要实现此侦听器,并且在执行AsyncTask时,您还需要将侦听器传递给AsyncTask

public YourActivity extends Activity implements HttpResponseListener {

    // ... Other functions

    @Override
    public void httpResponseReceiver(String result) {
        int response_code = (int) Integer.parseInt(result);

        // Take necessary actions here
        lView = new LinearLayout(this);
    }
}

现在,在您的AsyncTask中,您需要先将变量作为Activity的聆听者。

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

    // Declare the listener here 
    public HttpResponseListener mHttpResponseListener;

    @Override
    protected String doInBackground(String... param) {

        HashMap<String, bean> map = new HashMap<String, bean>();

        try {
            url = new URL("http://localhost/app/alldata.php");
        } catch (MalformedURLException e) {
            Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            return null;
        }

        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("user_id", "user_id")
                    .appendQueryParameter("dpt_id","dptid");
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            e1.printStackTrace();
        }

        try {
            // int response_code = conn.getResponseCode();  // Return the result to onPostExecute
            // lView = new LinearLayout(this); // Remove this from here
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return conn.getResponseCode() + "";
    }

    // Set the result here
    @Override
    protected void onPostExecute(final String result) {
        mHttpResponseListener.httpResponseReceiver(result);
    }
}

现在,从Activity开始AsyncTask启动HttpRequestAsyncTask mHttpRequestAsyncTask = new HttpRequestAsyncTask(); mHttpRequestAsyncTask.mHttpResponseListener = YourActivity.this; // Start your AsyncTask mHttpRequestAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); ,您需要首先像这样分配侦听器。

{{1}}

希望有所帮助!