如何在另一个类的onProgressUpdate AsyncTask中获取价值?

时间:2015-02-26 12:17:58

标签: android interface android-asynctask

我通常在调用者的同一个类中使用AsyncTask,但现在我想使用接口类从不同的类调用asyntask,我想从另一个clas的onProgressUpdate调用中获取值,这是我的asynctask类..

class UploadFileToServer extends AsyncTask<String, Integer, String> implements DialogInterface.OnCancelListener {
      private String url;
      private File file;
      ShareProgress shareProgres;
      SharePosExecute sharePosExecute;
       public UploadFileToServer(String url, String file) {

        this.url = url;
        this.file = new File(file); 
       }

   @Override
  protected void onPreExecute() {

  }

   @Override
  protected String doInBackground(String... v) {
    //place code of upload file to server,run very well...
    return responseFromServer;
  }

   @Override
  protected void onProgressUpdate(Integer... progress) {
    Log.v("progress",progress[0]+""); //this work well
    shareProgres.progressUpdate(progress[0]); //I get error in here

  }

   @Override
  protected void onPostExecute(String response) {
       sharePosExecute.posExecute(response); // i also get error in here
  }

   @Override
  public void onCancel(DialogInterface dialog) {
    cancel(true);
   // dialog.dismiss();
  }
}

在我的活动课

public class myActivity extends SherlockFragmentActivity implements ShareProgress,SharePosExecute {


        @Override
        public void progressUpdate(int progress) {
             Log.i("progress in myactivity",progress+""); //i want to this code work.

        }
        @Override
        public void posExecute(String output) {
            Log.i("processFinish myActivity",output);
        }
}

我使用接口类来通过不同的类进行通信,这里是我的接口代码

public interface ShareProgress {
     void progressUpdate(int progress);
}

我该如何解决这个问题,可能还有另外一种方法,请帮忙

感谢

1 个答案:

答案 0 :(得分:0)

你应该在你的asynctask中设置你的听众吗?

    ShareProgress shareProgres;
      SharePosExecute sharePosExecute;
       public UploadFileToServer(String url, String file,ShareProgress shareProgres,SharePosExecute sharePosExecute) {

        this.url = url;
        this.file = new File(file); 
        this.shareProgres=shareProgres;
        this.sharePosExecute=sharePosExecute;
       }

并在您的活动中,开始初始化您的异步任务:

UploadFileToServer uFTS=new UploadFileToServer(url,file,myActivity.this,myActivity.this);
//then execute:
uFTS.execute();