gpt4 book ai didi

java - Android如何在继续之前等待代码完成

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:20:39 26 4
gpt4 key购买 nike

我有一个名为hostPhoto() 的方法;它基本上是将图像上传到站点并检索链接。然后我有另一种方法来发布网站链接。

现在我使用这个方法的方式是这样的:

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

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

我的问题是...hostPhoto() 需要几秒钟来上传和检索链接,我的程序似乎没有等待并继续发布,因此我留下了空链接,

无论如何,我可以让它先获取链接...然后发布吗?像某种 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();

关于java - Android如何在继续之前等待代码完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7149923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com