簡體   English   中英

Android如何在繼續之前等待代碼完成

[英]Android how to wait for code to finish before continuing

我有一個名為hostPhoto()的方法; 它基本上將圖像上傳到網站並檢索鏈接。 然后,我有另一種方法將鏈接發布到網站。

現在我使用這種方法的方式是這樣的:

String link = hostPhoto(); //returns a link in string format

post(text+" "+link); // posts the text + a link.

我的問題是... hostPhoto()需要幾秒鍾上傳和檢索鏈接,我的程序似乎不等待並繼續發布,因此我留下鏈接為null,

無論如何,我可以讓它首先獲得鏈接...然后發布? 喜歡某種onComplete? 或類似的東西..我認為上面的方法可以工作,但通過做Log.i's似乎鏈接返回到一秒左右后的字符串。

更新:這是我的問題的更新進度,我使用AsyncTask作為通知,但Log.i的錯誤顯示urlLink為空...這意味着從hostphoto請求的鏈接永遠不會回來的時間為日志。 。

更新2:最終工作! 問題是hostPhoto()中的線程,是否有人可以為我提供一個探索,為什么該線程會導致這個? 感謝所有回復的人。

private class myAsyncTask extends AsyncTask<Void, Void, Void> {
    String urlLink;
    String text;
    public myAsyncTask(String txt){

        text=txt;
    }

    @Override
    protected Void doInBackground(Void... params) {
        urlLink=hostPhoto();
        //Log.i("Linked", urlLink);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        try {
            Log.i("Adding to status", urlLink);
            mLin.updateStatus(text+" "+urlLink);
            Log.i("Status:", urlLink);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

hostPhoto()執行此操作:

            String link;  new Thread(){

                @Override
                public void run(){
                    HostPhoto photo = new HostPhoto(); //create the host class


                    link= photo.post(filepath); // upload the photo and return the link
                    Log.i("link:",link);
                }
            }.start();

你可以在這里使用AsyncTask,

的AsyncTask

通過使用它你可以執行代碼

hostPhoto()

在doInBackground()中然后執行代碼

post(text+" "+link);

在onPostExecute()方法中,這將是您的最佳解決方案。

您可以使用此模式編寫代碼

private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params) {
        hostPhoto();
        return null;
    }
   @Override
   protected void onPostExecute(Void result) {
        post(text+" "+link);
    }
 }

並且可以使用它來執行它

 new MyAsyncTask().execute();

我假設您(或應該)使用單獨的線程來異步完成此操作。

您需要將post()放在hostPhoto()完成時調用的回調中。

通常我用Android的AsyncTask完成了這個...

這為你提供了回調onPostExecute() ,你可以在里面做post()

對於你的第二個問題:

有人能給我一個解釋為什么那個線程會導致這個?

你叫“link = photo.post(filepath);” 它正在一個新線程上運行。 當該方法仍在運行時,link仍然為null,並且您當前的線程(主線程)繼續使用該鏈接運行(當時為null)

在這種情況下,你需要等待結果,所以讓新線程運行該方法,並在完成后,該線程將要求主線程更新結果(通過一些Callback或Handler),所有這些作業都被很好地封裝了Android AsyncTask

你可以使用AsyncTask ,請參閱

編輯 :他是asynctask的視頻教程 ,或參考這個示例: clic here

您可能需要查看Java中的回調模式

暫無
暫無

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

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