如何在Android 2.2的自己的下载管理器 [英] how to create own download manager in android 2.2

查看:187
本文介绍了如何在Android 2.2的自己的下载管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以在安卓2.3及以上版本使用内置的下载管理器,但我的应用程序适用于Android 2.2及above.My的问题是如何在Android 2.2的创建​​自己的下载管理器?请给我提供了一些示例答案。

解决方案
  

请给我提供了一些示例答案。

第一步寻找实例如何在Android的下载文件

第二步:寻找示例如何在AsyncTask的执行操作。

第三步:寻找示例如何显示下载进度,同时下载。

第四步:寻找例如在如何发送自定义广播时,任务完成

第五步:寻找例如在如何坚持,即使在设备旋转AsysncTask操作

第六步:寻找例如在如何显示在通知下载进度。

下面的例子code。

1。使用AsyncTask的,并显示在对话框中的下载进度

  //声明对话框,你的活动中的一员现场
ProgressDialog mProgressDialog;

//在onCreate方法中实例化它
mProgressDialog =新ProgressDialog(YourActivity.this);
mProgressDialog.setMessage(信息);
mProgressDialog.setIndeterminate(假);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

//执行此当下载必须被解雇
DownloadFile downloadFile =新DownloadFile();
downloadFile.execute(链接直接您要下载的文件);

该AsyncTask的将是这样的:

//通常的AsyncTask的子类的活动类中声明。
//这种方式,你可以很容易地从这里修改UI线程
私有类DownloadFile扩展的AsyncTask<字符串,整数,字符串> {
    @覆盖
    保护字符串doInBackground(字符串... SURL){
        尝试 {
            网址URL =新的URL(SURL [0]);
            URLConnection的连接= url.openConnection();
            connection.connect();
            //这将是有益的,这样就可以显示一个典型的0-100%的进度条
            INT文件长度= connection.getContentLength();

            //下载文件
            的InputStream输入=新的BufferedInputStream(url.openStream());
            的OutputStream输出=新的FileOutputStream(/ SD卡/ file_name.extension);

            字节的数据[] =新的字节[1024];
            总长= 0;
            诠释计数;
            而((计数= input.read(数据))!=  -  1){
                共有+ =计数;
                //发布进度....
                publishProgress((int)的(总* 100 /文件长度));
                output.write(数据,0,计数);
            }

            output.flush();
            output.close();
            input.close();
        }赶上(例外五){
        }
        返回null;
    }
 

以上(doInBackground)的方法总是在后台线程中运行。你不应该做任何UI任务那里。在另一方面,onProgressUpdate和preExecute在UI线程上运行,所以你可以改变进度条:

  @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        mProgressDialog.show();
    }

    @覆盖
    保护无效onProgressUpdate(整数...进度){
        super.onProgressUpdate(进度);
        mProgressDialog.setProgress(进展[0]);
    }
}
 

2。下载从服务

这里的大问题是:如何更新从服务我的活动?在下面的例子中,我们将使用两个类,你可能不知道的:ResultReceiver和IntentService。 ResultReceiver是一个可以让我们更新从服务我们的线程; IntentService是服务的子类,产生一个线程从那里做后台工作(你应该知道,一个服务于你的应用程序在同一个线程实际运行;当你扩展了服务,你必须手动产卵运行CPU阻塞操作新主题)

下载服务可以是这样的:

 公共类下载服务扩展IntentService {
    公共静态最终诠释UPDATE_PROGRESS = 8344;
    公众下载服务(){
        超级(下载服务);
    }
    @覆盖
    保护无效onHandleIntent(意向意图){
        串urlToDownload = intent.getStringExtra(URL);
        ResultReceiver接收器=(ResultReceiver)intent.getParcelableExtra(接收器);
        尝试 {
            网址URL =新的URL(urlToDownload);
            URLConnection的连接= url.openConnection();
            connection.connect();
            //这将是有益的,这样就可以显示一个典型的0-100%的进度条
            INT文件长度= connection.getContentLength();

            //下载文件
            的InputStream输入=新的BufferedInputStream(url.openStream());
            的OutputStream输出=新的FileOutputStream(/ SD卡/酒吧codeScanner-debug.apk);

            字节的数据[] =新的字节[1024];
            总长= 0;
            诠释计数;
            而((计数= input.read(数据))!=  -  1){
                共有+ =计数;
                //发布进度....
                捆绑resultData =新包();
                resultData.putInt(进步,(INT)(总* 100 /文件长度));
                receiver.send(UPDATE_PROGRESS,resultData);
                output.write(数据,0,计数);
            }

            output.flush();
            output.close();
            input.close();
        }赶上(IOException异常E){
            e.printStackTrace();
        }

        捆绑resultData =新包();
        resultData.putInt(进步,100);
        receiver.send(UPDATE_PROGRESS,resultData);
    }
}
 

添加服务到您的清单:

 <服务机器人:名称=下载服务/>
 

和活动将是这样的:

//初始化进度像在第一示例对话框

//你这是怎么火的下载

  mProgressDialog.show();
意向意图=新的意图(这一点,DownloadService.class);
intent.putExtra(URL,URL下载文件);
intent.putExtra(接收器,新DownloadReceiver(新处理器()));
startService(意向);
 

下面是份ResultReceiver来玩:

 私有类DownloadReceiver扩展ResultReceiver {
    公共DownloadReceiver(处理程序处理){
        超(处理);
    }

    @覆盖
    保护无效onReceiveResult(INT结果code,捆绑resultData){
        super.onReceiveResult(结果code,resultData);
        如果(结果code == DownloadService.UPDATE_PROGRESS){
            INT进度= resultData.getInt(进步);
            mProgressDialog.setProgress(进度);
            如果(进度== 100){
                mProgressDialog.dismiss();
            }
        }
    }
}
 

I know that we can use built-in download manager in Android 2.3 and above but my app is suitable for Android 2.2 and above.My question is how to create own download manager in android 2.2? please provide me some sample answer.

解决方案

please provide me some sample answer.

Step1 Look for Example on How to Download Files in Android

Step2 Look for Example on How to perform operations in AsyncTask.

Step3 Look for Example on How to Display Download Progress while Downloading.

Step4 Look for Example on How to send Custom Broadcast when Task is completed

Step5 Look for Example on How to Persist AsysncTask operation even on device rotation

Step6 Look for Example on How to Show Download Progress in Notification.

Below is example code.

1. Use AsyncTask and show the download progress in a dialog

// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;

// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");

The AsyncTask will look like this:

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadFile extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... sUrl) {
        try {
            URL url = new URL(sUrl[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/file_name.extension");

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
        return null;
    }

The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate and onPreExecute run on the UI thread, so there you can change the progress bar:

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

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        mProgressDialog.setProgress(progress[0]);
    }
}

2. Download from Service

The big question here is: how do I update my activity from a service?. In the next example we are going to use two classes you may not be aware of: ResultReceiver and IntentService. ResultReceiver is the one that will allow us to update our thread from a service; IntentService is a subclass of Service which spawns a thread to do background work from there (you should know that a Service runs actually in the same thread of your app; when you extends Service, you must manually spawn new threads to run CPU blocking operations).

Download service can look like this:

public class DownloadService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;
    public DownloadService() {
        super("DownloadService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        String urlToDownload = intent.getStringExtra("url");
        ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {
            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                receiver.send(UPDATE_PROGRESS, resultData);
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);
        receiver.send(UPDATE_PROGRESS, resultData);
    }
}

Add the service to your manifest:

<service android:name=".DownloadService"/>

And the activity will look like this:

// initialize the progress dialog like in the first example

// this is how you fire the downloader

mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);

Here is were ResultReceiver comes to play:

private class DownloadReceiver extends ResultReceiver{
    public DownloadReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);
        if (resultCode == DownloadService.UPDATE_PROGRESS) {
            int progress = resultData.getInt("progress");
            mProgressDialog.setProgress(progress);
            if (progress == 100) {
                mProgressDialog.dismiss();
            }
        }
    }
}

这篇关于如何在Android 2.2的自己的下载管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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