簡體   English   中英

Android如何等待線程完成並通知?

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

該程序的任務是從Internet讀取數據並進行處理。

我在主類中使用AsyncTask從Internet讀取數據。但是AsyncTask將作為單獨的線程運行,因為該主類在AsyncTask讀取網頁之前完成了。現在我希望主類等待AsyncTask線程完成(即讀取數據)從互聯網)並恢復主類線程。

注意 :

  1. 我不想在onPostExcecute()方法中執行該過程。
  2. 我不想使用sleep()。

這是代碼

    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

      }
     }
    }

更換

this.wait();

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

並打電話

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

您想要的地方。

將代碼也處理在AsyncTask中的字符串。 盡你所能。 僅在需要更新UI時返回主線程。 而且,如果您真的不需要onPostExecute()任何內容, onPostExecute()我想您可以向您的應用發送一個Intent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM