简体   繁体   English

Android:如何从不同的类文件运行asynctask?

[英]Android: How to run asynctask from different class file?

When I use my code in one class file, it runs perfectly: 当我在一个类文件中使用我的代码时,它运行完美:

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    private static String fileName = "yo.html";
    private static String fileURL = "http://example.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program with asynctask... ");
        tv.append("\nYo, this line is appended!");

        startDownload();

     }

    private void startDownload() {
        new DownloadFileAsync().execute(fileURL);
    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }


    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... aurl) {

            try {
                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(fileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
}

I want to run the asyntask I have from a different class file, I have my code: 我想从不同的类文件中运行asyntask,我有我的代码:

DownloadFile.java DownloadFile.java

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

public class DownloadFile extends Activity {


    private static String fileName = "yo.html";
    private static String fileURL = "http://example.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";

     @Override
     public void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        TextView tv = new TextView(this);
        tv.setText("This is download file program with asynctask... ");
        tv.append("\nYo, this line is appended!");

        startDownload();

     }

    private void startDownload() {
        new DownloadFileAsync().execute(fileURL);
    }

}

DownloadFileAsync.java DownloadFileAsync.java

package com.example.downloadfile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

class DownloadFileAsync extends AsyncTask<String, String, String> {
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {

        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lenghtOfFile = c.getContentLength();

            FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName));

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                publishProgress("" + (int)((total*100)/lenghtOfFile));
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }

        return null;

    }

    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }
}

I'm using eclipse and I'm getting errors in my DownloadFile.java file, there are many red underlined codes.... I'm new to java and android dev. 我正在使用eclipse,我的DownloadFile.java文件中出现错误,有许多带红色下划线的代码....我是java和android dev的新手。

Some changes in your code will make it work : 代码中的一些更改将使其工作:

public class DownloadFileAsync extends AsyncTask<String, String, String> {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;

private Context context;

public DownloadFileAsync(Context context) 
{
    this.context = context;
     mProgressDialog = new ProgressDialog(context);
     mProgressDialog.setMessage("Downloading file..");
     mProgressDialog.setIndeterminate(false);
     mProgressDialog.setMax(100);
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     mProgressDialog.setCancelable(true);

}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    mProgressDialog.show();
}

@Override
protected String doInBackground(String... aurl) {

    try {
        File root = Environment.getExternalStorageDirectory();
        URL u = new URL(aurl[0]);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        int lenghtOfFile = c.getContentLength();

        FileOutputStream f = new FileOutputStream(new File(root + "/download/", aurl[1]));

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        long total = 0;

        while ((len1 = in.read(buffer)) > 0) {
            total += len1; //total = total + len1
            publishProgress("" + (int)((total*100)/lenghtOfFile));
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        Log.d("Downloader", e.getMessage());
    }

    return null;

}

protected void onProgressUpdate(String... progress) {
     Log.d("ANDRO_ASYNC",progress[0]);
     mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
    mProgressDialog.dismiss();
}


}

And DownloadFile Class : 和DownloadFile类:

public class DownloadFile extends Activity {


private static String fileName = "yo.html";
private static String fileURL = "http://mydomain.com/tabletcms/tablets/tablet_content/000002/form/Best%20Form%20Ever/html";

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    TextView tv = new TextView(this);
    tv.setText("This is download file program with asynctask... ");
    tv.append("\nYo, this line is appended!");

    startDownload();

 }

private void startDownload() {
    new DownloadFileAsync(this).execute(fileURL,fileName);
}

}

If you can somehow pass the Activity class or its context to the AsyncTask that will solve your issue for showing dialog. 如果您能以某种方式将Activity类或其上下文传递给AsyncTask,它将解决您显示对话框的问题。 You would need to include another parameter together with the URL you are sending and put that parameter in a Context variable. 您需要将另一个参数与要发送的URL一起包含在内,并将该参数放在Context变量中。 And then whenever you need the dialog you use that context variable to show it. 然后,只要您需要对话框,就可以使用该上下文变量来显示它。

If the dialog does not have a Context from which to show it will definitely run into runtime errors. 如果对话框没有可以显示它的Context,它肯定会遇到运行时错误。

Update (put my comment up here as well): here we go... found a good example that you can modify to make use for your case. 更新(也在这里提出我的评论):我们在这里......找到一个很好的例子,你可以修改以便用于你的案例。 It's at brighthub.com/mobile/google-android/articles/82805.aspx . 它位于brighthub.com/mobile/google-android/articles/82805.aspx Scroll down to Source Code section and have a look at the code for WebServiceAsyncTask and WebServiceBackgroundActivity. 向下滚动到“源代码”部分,查看WebServiceAsyncTask和WebServiceBackgroundActivity的代码。

I know its too late to help you but for others this may help. 我知道为时已晚,无法帮助你,但对其他人而言,这可能有所帮助。

Its so simple just Simply build an object of main class and than call the inner class like this 它如此简单只需构建一个主类的对象,然后像这样调用内部类

 OuterMainClass outer = new OuterMainClass();
       outer.new InnerAsyncClass(param)
         .execute();

Thanks 谢谢

Actual problem can be class level error, you might not be placing async class and download class in same package. 实际问题可能是类级别错误,您可能不会将异步类和下载类放在同一个包中。 Other problem I can see is async class using showDialog() , onCreateDialog() etc., which is available only if your class extends Activity . 我能看到的其他问题是使用showDialog()onCreateDialog()等异步类,只有在类扩展Activity时才可用。

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

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