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

时间:2011-05-25 03:42:55

标签: java android android-asynctask

当我在一个类文件中使用我的代码时,它运行得很完美:

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

我想从不同的类文件中运行asyntask,我有我的代码:

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

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

我正在使用eclipse,我的DownloadFile.java文件中出现错误,有许多带红色下划线的代码....我是java和android dev的新手。

4 个答案:

答案 0 :(得分:32)

您的代码中的某些更改会使其有效:

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


}

并下载文件类:

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

}

答案 1 :(得分:20)

如果您能以某种方式将Activity类或其上下文传递给AsyncTask,它将解决您显示对话框的问题。您需要将另一个参数与要发送的URL一起包含在内,并将该参数放在Context变量中。然后,只要您需要对话框,就可以使用该上下文变量来显示它。

如果对话框没有可以显示它的上下文,它肯定会遇到运行时错误。

更新(也在这里提出我的评论):在这里我们去...找到了一个很好的例子,您可以修改以便用于您的案例。它在brighthub.com/mobile/google-android/articles/82805.aspx。向下滚动到“源代码”部分,查看WebServiceAsyncTask和WebServiceBackgroundActivity的代码。

答案 2 :(得分:3)

我知道为时已晚,无法帮助你,但对其他人而言,这可能有所帮助。

它如此简单只需构建一个主类的对象,然后像这样调用内部类

class MyControl0 : Control
{
    private SolidBrush foreColor = new SolidBrush(SystemColors.ControlText);
    public override Color ForeColor
    {
        get { return foreColor.Color; }
        set { foreColor.Color = value; }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);

        TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
                                TextFormatFlags.VerticalCenter ;
        TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, 
                              ForeColor, flags);
    }
}

由于

答案 3 :(得分:2)

实际问题可能是类级别错误,您可能不会在同一个包中放置异步类和下载类。我能看到的其他问题是使用showDialog()onCreateDialog()等的异步类,仅当您的类扩展Activity时才可用。