Android如何在继续之前等待代码执行完成

11

我有一个叫做 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()的内容,因为你所描述的行为是非标准的。 - Alex
一个 AsyncTask 并不能解决这个问题,因为 hostPhoto() 甚至没有阻塞线程。就像 atc 提到的那样,你需要发布 hostPhoto() 的代码。 - Che Jami
主机照片的代码已更新。 - asd2005
更新2:终于成功了!问题在于hostPhoto()中的线程,有人能解释一下为什么这个线程会导致这个问题吗?感谢所有回复的人。 - asd2005
由于AsyncTask现在已经被弃用,我们现在应该使用什么? - Ieshaan Saxena
5个回答

14

在这里您可以使用AsyncTask,

AsyncTask

通过使用它,您可以在doInBackground()中执行hostPhoto()的代码,然后在onPostExecute()方法中执行post(text+" "+link);的代码,这将是最好的解决方案。

您可以按照以下方式编写代码:

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();

嘿,谢谢您的回复。在执行您的方法后,我遇到了一个错误。请查看上面更新的问题。 - asd2005
终于成功了!问题出在hostPhoto()函数中的线程上,有人能解释一下为什么那个线程会导致这个问题吗? - asd2005

2
我假设你正在(或应该)使用单独的线程来异步完成此操作。
你需要把post()放在一个回调函数中,该回调函数在hostPhoto()完成时被调用。
一般来说,我会在Android中使用AsyncTask来实现这个目标……
这提供给你回调函数onPostExecute(),你可以在其中执行post()

0

你可以使用 AsyncTask,参考 this

编辑:这里还有一个关于 asynctask 的视频 tutorial,或者参考这个示例:clic here


0

0
针对你的第二个问题:
“有人能解释一下为什么那个线程会导致这种情况吗?”
你调用了一个在新线程上运行的“link= photo.post(filepath);”方法。当该方法仍在运行时,link仍然为空,而你当前的线程(主线程)继续以该链接(此时为空)运行。
在这种情况下,你需要等待结果,让新线程运行该方法,并在完成后,该线程将要求主线程通过某些回调或处理程序更新结果。所有这些工作都由Android AsyncTask很好地封装了起来。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接