我有一個方法hostPhoto()
;它基本上將圖像上傳到網站並檢索鏈接。 然後我有其他方法將鏈接發佈到網站。Android如何在繼續之前等待代碼完成
現在使用這種方法的方式即時通訊」是這樣的:
String link = hostPhoto(); //returns a link in string format
post(text+" "+link); // posts the text + a link.
我的問題是...是,hostPhoto()
需要幾秒鐘,以上傳和檢索鏈接, 我的程序似乎不等待並繼續張貼,因此即時通訊留下的鏈接爲空,
是否有無論如何,我可以讓它首先得到鏈接...然後發佈? 像某種onComplete?或類似的東西.. 我認爲我的方法上面會工作,但通過做Log.i的似乎鏈接後返回到一秒左右的字符串。
更新:這是我的問題的更新進度,即時使用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();
封裝你應該張貼更多的代碼,尤其是因爲你描述的行爲是非標準的,所以'hostPhoto()'的內容。 –
'AsyncTask'不能解決這個問題,因爲'hostPhoto()'甚至不會阻塞該線程。像提到的atc一樣,你需要從'hostPhoto()'發佈代碼。 –
hostPhoto的代碼已更新 – asd2005