如何从单独的asynctask类调用活动类中的方法?

时间:2014-10-09 03:14:09

标签: android android-activity android-asynctask

这是我的活动课

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;


public class MyActivity extends Activity {
ProgressBar pb_showprogress;
Button btn_startDownloading;
NotificationBuilder mNotificationBuilder = new NotificationBuilder(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    pb_showprogress = (ProgressBar) findViewById(R.id.pd_showProgress);
    pb_showprogress.setVisibility(View.GONE);
    pb_showprogress.setMax(100);
    btn_startDownloading = (Button) findViewById(R.id.btn_startDownload);
    btn_startDownloading.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pb_showprogress.setVisibility(View.VISIBLE);

            new Download(getApplicationContext()).execute();


        }
    });
}

public void setOnProgressUpdate(int percentageComplete){
    pb_showprogress.setProgress(percentageComplete);
}
}

这是我的asynctask类

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class Download extends AsyncTask<Integer, Integer, String> {
NotificationBuilder mNotificationBuilder;
MyActivity mMyActivity ;
Context context;
String mURL[] = new String[]{//array of the urls};

public Download(Context context) {
    this.context = context;
}

protected void onPreExecute() {
     Toast.makeText(context, "here", Toast.LENGTH_SHORT).show();
}

@Override
protected String doInBackground(Integer... params) {

    try {
        for (int i = 0; i < mURL.length; i++) {
            URL url = new URL(mURL[i]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.connect();

            int lengthOfFile = connection.getContentLength();


            String path = Environment.getExternalStorageDirectory() + "/Download";
            File file = new File(path);
            file.mkdir();
            //necessary to give the extension while giving the filename to store.
            String filename = "imageToDownload" + i + ".png";
            File outputFile = new File(file, filename);

            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);

            InputStream inputStream = connection.getInputStream();

            byte[] buffer = new byte[1024];
            int length = 0;
            int total=0;


            while ((length = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
                total += length ;

                publishProgress((int) (total * 100 / lengthOfFile));
            }
            fileOutputStream.close();
            inputStream.close();


        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
protected void onProgressUpdate(Integer... progress) {
    //This method runs on the UI thread, it receives progress updates
    //from the background thread and publishes them to the status bar
    mNotificationBuilder.progressUpdate(progress[0]);
    mMyActivity.setOnProgressUpdate(progress[0]);

}
@Override
protected void onPostExecute(String result)    {
    //The task is complete, tell the status bar about it
    mNotificationBuilder.completed();
    Toast.makeText(context,"Completed Download",Toast.LENGTH_SHORT).show();
}


}

现在在asynctask方法中,我想将进度[0]发送到接受它的myactivity。但我当然无法做到。请帮忙 在此先感谢:)

3 个答案:

答案 0 :(得分:1)

将您的Download构造函数更改为接受Activity作为参数而不是Context。然后,您可以根据需要将已发送的活动同时用作ActivityContext

注意:在Activity期间,请注意doInBackground()上您呼叫的方法。如果您尝试在此方法期间修改任何视图,您的应用程序将崩溃。

答案 1 :(得分:1)

你可以像((MyActivity)this.context).yourMethodInActivity(progress [0])一样解析你的上下文。别忘了在onPostExecute中执行此操作

答案 2 :(得分:0)

你也可以试试这个:

在异步任务中添加进度对话框变量:

public class Download extends AsyncTask<Integer, Integer, String> {
    private ProgressDialog mProgressDialog ;

在异步任务构造函数中,从活动中传递ProgressDialog实例:

public Download(Context pContext, ProgressDialog pProgressDialog ) {
    this.context = context;
    this.mProgressDialog = pProgressDialog;
}

的onProgressUpdate方法中
@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(message);
    mNotificationBuilder.progressUpdate(progress[0]);
    mProgressDialog .setMessage(""+progress[0]);
}