虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > Android编程 > Android 基于IntentService的文件下载的示例代码

Android 基于IntentService的文件下载的示例代码
类别:Android编程   作者:码皇   来源:互联网   点击:

本篇文章主要介绍了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;
    //嗯,这是一个十分绅士的IDmanager.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 );

完整代码再来一遍

    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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关热词搜索: Android IntentService文件下载 Android 文