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

前端之家收集整理的这篇文章主要介绍了java – Android如何在继续之前等待代码完成前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个名为hostPhoto()的方法;它基本上将图像上传到网站并检索链接.
然后我有另一种方法链接发布到网站.

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

  1. String link = hostPhoto(); //returns a link in string format
  2.  
  3. post(text+" "+link); // posts the text + a link.

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

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

更新:这是我的问题的更新进度,我使用AsyncTask作为通知,但Log.i的错误输出显示urlLink为空…这意味着从hostphoto请求的链接永远不会回来的时间为日志. .

更新2:最终工作!问题是hostPhoto()中的线程,有人可以为我提供一个探索,为什么该线程会导致这个?
感谢所有回复的人.

  1. private class myAsyncTask extends AsyncTask<Void,Void,Void> {
  2. String urlLink;
  3. String text;
  4. public myAsyncTask(String txt){
  5.  
  6. text=txt;
  7. }
  8.  
  9. @Override
  10. protected Void doInBackground(Void... params) {
  11. urlLink=hostPhoto();
  12. //Log.i("Linked",urlLink);
  13. return null;
  14. }
  15.  
  16. @Override
  17. protected void onPostExecute(Void result) {
  18.  
  19. try {
  20. Log.i("Adding to status",urlLink);
  21. mLin.updateStatus(text+" "+urlLink);
  22. Log.i("Status:",urlLink);
  23. } catch (Exception e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27. }
  28. }

hostPhoto()执行此操作:

  1. String link; new Thread(){
  2.  
  3. @Override
  4. public void run(){
  5. HostPhoto photo = new HostPhoto(); //create the host class
  6.  
  7.  
  8. link= photo.post(filepath); // upload the photo and return the link
  9. Log.i("link:",link);
  10. }
  11. }.start();

解决方法

你可以在这里使用AsyncTask,

AsyncTask

通过使用它你可以执行代码

hostPhoto()

在doInBackground()中然后执行代码

发布(文字“”链接);

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

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

  1. private class MyAsyncTask extends AsyncTask<Void,Void>
  2. {
  3. @Override
  4. protected Void doInBackground(Void... params) {
  5. hostPhoto();
  6. return null;
  7. }
  8. @Override
  9. protected void onPostExecute(Void result) {
  10. post(text+" "+link);
  11. }
  12. }

并且可以使用执行它

  1. new MyAsyncTask().execute();

猜你在找的Android相关文章