【问题标题】:how to call UI or UI thread in doInBackground method如何在 doInBackground 方法中调用 UI 或 UI 线程
【发布时间】:2016-12-20 14:26:12
【问题描述】:

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

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

有什么方法可以在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;
}

【问题讨论】:

  • 你真的需要在后台创建新的LinearLayout吗?您可以在onPostExecute 中创建它

标签: android multithreading android-asynctask ui-thread


【解决方案1】:

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

显然,这是为了类似进度的使用。您应该已经清楚地将一个工作单元分离为后台,然后在onPostExecute 中正常处理。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      更优雅的方法是传递一个回调函数,这样当您的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);
      

      希望有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-15
        • 2019-04-29
        • 2012-04-27
        • 1970-01-01
        • 1970-01-01
        • 2012-01-24
        相关资源
        最近更新 更多