我有一个方法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