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

标签 java android hyperlink android-asynctask

我有一个名为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/

相关文章:

java - RabbitMQ 和 hibernate : Unable to commit against JDBC Connection

java - 异步任务中的 MediaPlayer : finalized without being released

android - 从 BackgroundWorker onPostExecute 将结果返回到 Main

linux - 在网页上的 html 链接中搜索字符串并下载链接文件

java - 方法 : org. gradle.api.java.archives.internal.DefaultManifest.srcFile() 没有签名

java - 如何使用触摸监听器并仅在触摸按钮时播放声音?

java - 防止将eclipse项目中的授权数据保存到存储库

jquery链接点击不起作用

excel - 添加数据或对列表排序后维护超链接

java - 如何监听发送到 ActorSystem 的消息(Akka 2.0)