简体   繁体   English

Android如何等待线程完成并通知?

[英]Android how to wait for a thread to finish and notify?

The task of the program is to read data from internet and process it. 该程序的任务是从Internet读取数据并进行处理。

I am using AsyncTask inside the main class to read data from internet.But AsyncTask will run as separate thread because of that main class finishes before AsyncTask reads the webpage.Now i want the main class to wait for AsyncTask thread to complete(ie read data from internet) and resume the main class thread. 我在主类中使用AsyncTask从Internet读取数据。但是AsyncTask将作为单独的线程运行,因为该主类在AsyncTask读取网页之前完成了。现在我希望主类等待AsyncTask线程完成(即读取数据)从互联网)并恢复主类线程。

NOTE : 注意 :

  1. I don't want to do that process in onPostExcecute() method. 我不想在onPostExcecute()方法中执行该过程。
  2. I don't want to use sleep(). 我不想使用sleep()。

Here is the code 这是代码

    public class MyApp extends Activity {

    String data[] = null;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.m1_pm_material_requisitions_main);
    tv = (TextView)findViewById(R.id.test_textview);

    GetData get = new GetData();
    get.execute(new String[]{"http://192.168.92.171/erp/index.php"});
    try {
        this.wait();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

   //i want the program to wait here till the above task is done and proceed further 

   /* Here the code to process the data in String[] data;....
   ..........
   .......... */      



    private class GetData extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... params) {

    // code to read webpage from internet
    //im using HttpGet to read a webpage

    //now the content of webpage is stored in String[] data

      }
     }
    }

Replace 更换

this.wait();

with

get.wait(); // wait until get calls notify()

and call 并打电话

this.notify(); // wakeup someone who waiting for me

somewhere you want. 您想要的地方。

Put the code to process the string in your AsyncTask too. 将代码也处理在AsyncTask中的字符串。 Do as much there as you can. 尽你所能。 Only return to the main thread when it's time to update the UI. 仅在需要更新UI时返回主线程。 And if you really don't want anything in onPostExecute() , I suppose you could send your app an Intent . 而且,如果您真的不需要onPostExecute()任何内容, onPostExecute()我想您可以向您的应用发送一个Intent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM