如何从android中的线程获得结果?

时间:2014-06-08 08:19:49

标签: android multithreading handler

我有一个主类,一个工作线程类,它分开了。在主线程中,我将输入传递给工作线程并要求它工作。完成后,我希望它将结果发送回主线程。我怎么能这样做?

public class MainActivity extends Activity{
     Handler showResults = new Handler(){
         public void handleMessage(Message msg){
               //Show results on textview.
         }

     workerThread worker = new workThread();
     worker.setInput(input);
    }

}

工作线程:

public class workerThread extends Thread{
       int result = 0;
       public void run(){
          //when receive input from main class. it will work
          .............
         //after working, it return result, and i want it to send this result 
         //to Handler in main activity, so, i can display that result on textview.
       }

      //function to get input
      public void setInput(){
        //get input form main class to work
      }
}

任何人都知道答案请告诉我。谢谢。:)

3 个答案:

答案 0 :(得分:3)

也许你应该试试AsynTask,它的设计就是:

 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
     }
 }  

你执行这样的线程:

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

请参阅http://developer.android.com/reference/android/os/AsyncTask.html

答案 1 :(得分:0)

您可以使用线程run()方法末尾的以下代码在主UI线程上发布要执行的runnable:

MainActivity.this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // TODO: modify the text view, other UI elements, etc.
    }
});

答案 2 :(得分:0)

使用AsyncTask来避免任何多线程问题示例代码:

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);
}}

将其用作适配器中的内部类 如果你正在进行网络连接,你也可以使用很多API。