我有一个叫做 hostPhoto()
的方法;它基本上将一张图片上传到一个网站并获取链接。
然后我有另一个方法来将该链接发布到网站上。
现在我使用这个方法的方式是这样的:
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请求的链接没有及时返回到Logs中。
更新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()
的内容,因为你所描述的行为是非标准的。 - AlexAsyncTask
并不能解决这个问题,因为hostPhoto()
甚至没有阻塞线程。就像 atc 提到的那样,你需要发布hostPhoto()
的代码。 - Che Jami