[英]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,
通过使用它你可以执行代码
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.