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

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

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

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

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

我的问题是… hostPhoto()需要几秒钟来上传和检索链接,
我的程序似乎不等待并继续发布,因此我将链接保留为null,

无论如何,我可以让它首先获得链接…然后发布?
喜欢某种onComplete?或类似的东西..
我认为上面的方法可以工作,但通过做Log.i,似乎链接在一秒左右后返回到字符串.

更新:这是我的问题的更新进度,我使用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()中然后执行代码

发布(文字“”链接);

在onPostExecute()方法中,这将是您的最佳解决方案.

您可以使用此模式编写代码

private class MyAsyncTask extends AsyncTask<Void,Void>
{
    @Override
    protected Void doInBackground(Void... params) {
        hostPhoto();
        return null;
    }
   @Override
   protected void onPostExecute(Void result) {
        post(text+" "+link);
    }
 }

并且可以使用执行它

new MyAsyncTask().execute();

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...