我有一种叫做hostPhoto()的方法;它基本上将图像上传到站点并检索链接。
然后,我还有另一种方法可以将链接发布到网站。

现在,Im'使用此方法的方式如下:

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()中,然后执行
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();

09-13 05:33