Android:如何从不同的类文件运行异步任务? [英] Android: How to run asynctask from different class file?

查看:18
本文介绍了Android:如何从不同的类文件运行异步任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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("
Yo, 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:

下载文件.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("
Yo, 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 开发的新手.

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.

推荐答案

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

If you can somehow pass the Activity class or its context to the AsyncTask that will solve your issue for showing dialog. You would need to include another parameter together with the URL you are sending and put that parameter in a Context variable. 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.

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

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. Scroll down to Source Code section and have a look at the code for WebServiceAsyncTask and WebServiceBackgroundActivity.

这篇关于Android:如何从不同的类文件运行异步任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆