Android 基于IntentService的文件下载

文件下载这种事情是很耗时的。之前使用AsyncTask这样的异步类来做下载,然后切到后台就被干掉。所以打算试试Service。(不过按目前那些系统的尿性,其实Service也分分钟被干掉)
不过,这里并不是直接使用Service类,而是使用的是继承自Service的IntentService。
这个东西有三大好处:
1.他有个任务队列;
2.任务队列执行完后会自动停止;
3.他会起一个独立的线程,耗时操作不会影响你app的主线程。
这么自动化的东西简直省心。
话不多说,开始撸代码。

首先,要建个应用,主文件如下(布局什么的代码就不贴了):

package net.codepig.servicedownloaderdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private String _url="http://www.boosj.com/apk/boosjDance.apk";
    private EditText urlText;
    private Button goBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        goBtn=(Button) findViewById(R.id.goBtn);
        urlText=(EditText) findViewById(R.id.urlText);
        urlText.setText(_url);
        goBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _url=urlText.getText().toString();
                //start download
                start_service();
            }
        });
    }

    public void start_service(){
        //等会再填
    }
}

以上代码不重要,嗯。

接下来是重点。创建一个IntentService 类,然后重写他的onHandleIntent 。

需要执行的任务就写在onHandleIntent 里
这里先用Thread.sleep模拟一下耗时任务,试跑一下就可以看到主app关闭后service还在跑,跑完后就自己Destroy了。

package net.codepig.servicedownloaderdemo;

import android.app.IntentService;
import android.content.Intent;

/**
 * 下载服务
 * Created by QZD on 2017/9/20.
 */

public class DownLoadService extends IntentService {
    public DownLoadService() {
        super("DownLoadService");//这就是个name
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    protected void onHandleIntent(Intent intent) {
        Bundle bundle = intent.getExtras();
        String downloadUrl = bundle.getString("download_url");

        Log.d(TAG,"下载启动:"+downloadUrl);
        Thread.sleep(1_000);
        int count=0;
        while(count<20){
            count++;
            Log.d(TAG,"下载运行中--"+count);
            Thread.sleep(1000);
        }
        Log.d(TAG,"下载结束");
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }
}

通过Intent接收任务,这里在MainActivity中通过startService启动服务

public void start_service(){
        Intent intent=new Intent(this,DownLoadService.class);
        intent.putExtra("download_url",_url);
        startService(intent);
    }

当然,AndroidManifest.xml里也得注册上

<service android:name="net.codepig.servicedownloaderdemo.DownLoadService"></service>

接下来我们看看怎么下载文件

首先别忘了添加权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

添加downloadFile方法管理下载。
下载相关说明都在注释里。

    /**
     * 文件下载
     * @param downloadUrl
     * @param file
     */
    private void downloadFile(String downloadUrl, File file){
        FileOutputStream _outputStream;//文件输出流
        try {
            _outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            Log.e(TAG, "找不到目录!");
            e.printStackTrace();
            return;
        }
        InputStream _inputStream = null;//文件输入流
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection _downLoadCon = (HttpURLConnection) url.openConnection();
            _downLoadCon.setRequestMethod("GET");
            fileLength = Integer.valueOf(_downLoadCon.getHeaderField("Content-Length"));//文件大小
            _inputStream = _downLoadCon.getInputStream();
            int respondCode = _downLoadCon.getResponseCode();//服务器返回的响应码
            if (respondCode == 200) {
                byte[] buffer = new byte[1024*8];// 数据块,等下把读取到的数据储存在这个数组,这个东西的大小看需要定,不要太小。
                int len;
                while ((len = _inputStream.read(buffer)) != -1) {
                    _outputStream.write(buffer, 0, len);
                    downloadLength = downloadLength + len;
                    Log.d(TAG, downloadLength + "/" + fileLength );
                }
            } else {
                Log.d(TAG, "respondCode:" + respondCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {//别忘了关闭流
                if (_outputStream != null) {
                    _outputStream.close();
                }
                if (_inputStream != null) {
                    _inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

放入onHandleIntent执行:

protected void onHandleIntent(Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            String downloadUrl = bundle.getString("download_url");

            File dirs = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download");//文件保存地址
            if (!dirs.exists()) {// 检查文件夹是否存在,不存在则创建
                dirs.mkdir();
            }

            File file = new File(dirs, "boosj.apk");//输出文件名
            Log.d(TAG,"下载启动:"+downloadUrl+" --to-- "+ file.getPath());
            // 开始下载
            downloadFile(downloadUrl, file);
            // 下载结束
            Log.d(TAG,"下载结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

跑一下,嗯,默默的下载完了。

但是,作为一个负责的app,当然要给用户反馈,所以我们要显示一下进度。

我们用Notification来显示进度。(需要注意的是,如果有必要调用主UI线程来显示进度的话,要充分考虑到Service运行过程中,你的app未必是一直活动着的,可能早就destroy了。)(当然用绑定来启动service的另说,那是另一种使用场景。)
下载前(也就是执行downloadFile方法前)先创建并对通知进行相关设置。
这里使用了NotificationCompat.Builder()这个方法。如果不考虑旧版本的兼容,可以使用Notification.Builder()方法。

private NotificationCompat.Builder builder;
private NotificationManager manager;
public void initNotification(){
        builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle("下载文件").setContentText("下载中……");//图标、标题、内容这三个设置是必须要有的。
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

然后使用NotificationManager.notify()方法将通知发送给系统。需要更新的话再次notify()给同一个ID的通知,如果该通知已存在则会更新,不存在就新建。

private int _notificationID= 1024;//嗯,这是一个十分绅士的ID
manager.notify(_notificationID,builder.build());

为了显示进度,使用handler和Runnable来定时刷新,并通过setProgress方法显示进度条。

private Handler handler = new Handler();
private Runnable run = new Runnable() {
        public void run() {
            int _pec=(int) (downloadLength*100 / fileLength);
            builder.setContentText("下载中……"+_pec+"%");
            builder.setProgress(100, _pec, false);//显示进度条,参数分别是最大值、当前值、是否显示具体进度(false显示具体进度,true就只显示一个滚动色带)
            manager.notify(_notificationID,builder.build());
            handler.postDelayed(run, 1000);
        }
    };

完事了以后如果需要清除通知可以使用manager.cancelAll();或者manager.cancel(int _id);

完整代码再来一遍

package net.codepig.servicedownloaderdemo;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

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.URL;

/**
 * 下载服务
 * Created by QZD on 2017/9/20.
 */

public class DownLoadService extends IntentService {
    private final String TAG="LOGCAT";
    private int fileLength, downloadLength;//文件大小
    private Handler handler = new Handler();
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private int _notificationID = 1024;
    public DownLoadService() {
        super("DownLoadService");//这就是个name
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    protected void onHandleIntent(Intent intent) {
        try {
            initNotification();

            Bundle bundle = intent.getExtras();
            String downloadUrl = bundle.getString("download_url");

            File dirs = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download");//文件保存地址
            if (!dirs.exists()) {// 检查文件夹是否存在,不存在则创建
                dirs.mkdir();
            }

            File file = new File(dirs, "boosj.apk");//输出文件名
            Log.d(TAG,"下载启动:"+downloadUrl+" --to-- "+ file.getPath());
            manager.notify(_notificationID,builder.build());
            // 开始下载
            downloadFile(downloadUrl, file);
            // 下载结束
            builder.setProgress(0,0,false);//移除进度条
            builder.setContentText("下载结束");
            manager.notify(_notificationID,builder.build());
//            manager.cancelAll();
//            manager.cancel(_notificationID);

            // 广播下载完成事件,通过广播调起对文件的处理。(就不多说了,在实际需要的地方接收广播就好了。)
            Intent sendIntent = new Intent("downloadComplete");
            sendIntent.putExtra("downloadFile", file.getPath());
            sendBroadcast(sendIntent);
            Log.d(TAG,"下载结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     * @param downloadUrl
     * @param file
     */
    private void downloadFile(String downloadUrl, File file){
        FileOutputStream _outputStream;//文件输出流
        try {
            _outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            Log.e(TAG, "找不到目录!");
            e.printStackTrace();
            return;
        }
        InputStream _inputStream = null;//文件输入流
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection _downLoadCon = (HttpURLConnection) url.openConnection();
            _downLoadCon.setRequestMethod("GET");
            fileLength = Integer.valueOf(_downLoadCon.getHeaderField("Content-Length"));//文件大小
            _inputStream = _downLoadCon.getInputStream();
            int respondCode = _downLoadCon.getResponseCode();//服务器返回的响应码
            if (respondCode == 200) {
                handler.post(run);//更新下载进度
                byte[] buffer = new byte[1024*8];// 数据块,等下把读取到的数据储存在这个数组,这个东西的大小看需要定,不要太小。
                int len;
                while ((len = _inputStream.read(buffer)) != -1) {
                    _outputStream.write(buffer, 0, len);
                    downloadLength = downloadLength + len;
//                    Log.d(TAG, downloadLength + "/" + fileLength );
                }
            } else {
                Log.d(TAG, "respondCode:" + respondCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {//别忘了关闭流
                if (_outputStream != null) {
                    _outputStream.close();
                }
                if (_inputStream != null) {
                    _inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Runnable run = new Runnable() {
        public void run() {
            int _pec=(int) (downloadLength*100 / fileLength);
            builder.setContentText("下载中……"+_pec+"%");
            builder.setProgress(100, _pec, false);//显示进度条,参数分别是最大值、当前值、是否显示具体进度(false显示具体进度,true就只显示一个滚动色带)
            manager.notify(_notificationID,builder.build());
            handler.postDelayed(run, 1000);
        }
    };

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        handler.removeCallbacks(run);
        super.onDestroy();
    }

    public void initNotification(){
        builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle("下载文件").setContentText("下载中……");//图标、标题、内容这三个设置是必须要有的。
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }
}

相关github项目地址:serviceDownloaderDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容