简体   繁体   English

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

[英]How to call a method in activity class from a seperate asynctask class?

This is my activity class 这是我的活动课

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);
}
}

and here is my asynctask class 这是我的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();
}


}

Now in the asynctask method i want to send the progress[0] to myactivity where it accepts it. 现在,在asynctask方法中,我想将progress [0]发送到myactivity接受它的地方。 But certainly I am not able to do it. 但是我当然不能做到。 Please help Thanks in advance :) 请帮助提前谢谢:)

Change your Download constructor to accept an Activity as a parameter instead of a Context . 更改您的Download构造函数,使其接受Activity作为参数而不是Context Then you can use the sent in activity as both an Activity and as a Context as appropriate. 然后,您可以将发送的活动同时用作ActivityContext

CAUTION: Be careful about what methods you call on the Activity during doInBackground() . 注意:请注意在doInBackground()期间在Activity上调用什么方法。 Your app will crash if you try to modify any views during this method. 如果您尝试在此方法期间修改任何视图,则您的应用程序将崩溃。

you can parse your context like ((MyActivity) this.context).yourMethodInActivity(progress[0]). 您可以像((MyActivity)this.context).yourMethodInActivity(progress [0])这样来解析上下文。 Don't forget to do it in your onPostExecute 别忘了在onPostExecute中执行此操作

You can try this also: 您也可以尝试以下操作:

Add a progress dialog variable in async task: 在异步任务中添加进度对话框变量:

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

And in the async task constructor pass the ProgressDialog instance from the activity: 并在异步任务构造函数中传递来自活动的ProgressDialog实例:

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

In the onProgressUpdate method of 在的onProgressUpdate方法中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM