how to get result from thread in android?

后端 未结 3 677
小蘑菇
小蘑菇 2021-01-21 09:07

I have a main class, a worker thread class and it separated. In main thread, I pass input to worker thread and ask for it to work. When it finish, I want it to send back result

相关标签:
3条回答
  • 2021-01-21 09:32

    Maybe you should try AsynTask, it is designed for just that:

     private class MyThread extends AsyncTask<Params, Progress, Result> {
         protected Long doInBackground(URL... urls) {
                // Calculate and return retulst
         }
    
    
         protected void onPostExecute(Long result) {
             // This is executed in main Thread, use the result
         }
     }  
    

    You execute this thread like this:

    new MyThread().execute(params, ...);
    

    See http://developer.android.com/reference/android/os/AsyncTask.html

    0 讨论(0)
  • 2021-01-21 09:52

    You can post a runnable to be executed on the main UI thread using the following code at the end of your thread's run() method:

    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // TODO: modify the text view, other UI elements, etc.
        }
    });
    
    0 讨论(0)
  • 2021-01-21 09:56

    use AsyncTask instead to avoid any multi-threading issues example code:

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();
    
          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }
    
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }
    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }}
    

    Use it as an inner class in your adapter Also you can use many APIs like volly if you are into networking.

    0 讨论(0)
提交回复
热议问题