Android 基于IntentService的文件下载的示例代码
作者:书柜里的松鼠 发布时间:2023-10-28 23:26:02
文件下载这种事情是很耗时的。之前使用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 );
完整代码再来一遍
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
来源:http://www.jianshu.com/p/f7f34c4bc8fb?utm_source=tuicool&utm_medium=referral


猜你喜欢
- 这篇文章主要介绍了Java判断用户名和密码过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可
- ChatGPT的基本介绍ChatGPT是一个用来进行自然语言处理任务的预训练模型。要使用ChatGPT,需要了解以下几点:理解预训练模型:预
- 泛型程序设计(Generic Programming)“使用泛型机制编写的程序代码要比那些杂乱地使用Object变量,然后再进行强制类型转换
- 目录Mybatis简介Mybatis开发步骤:Mybatis的映射文件概述Mybatis的增删改查操作MyBatis的核心配置文件概述MyB
- 前言进入到 SpringBoot2.7 时代,有小伙伴发现有一个常用的类忽然过期了:在 Spring Security 时代,这个类可太重要
- 开发一款性能优良的应用是每一个Android开发者都必须经历的挑战。在移动端资源有限的前提下,提高应用的性能显得尤为重要。常见的提高APP性
- 在文本框中输入一个数字,点击开始累加按钮,程序计算从1开始累计到该数字的结果。因为该累加过程比较耗时,如果直接在UI线程中进行,那么当前窗口
- 去公司面试,对方一口一个controller,一口一个service,dao,搞得我很紧张。其实都是很简单的东西,只是自己当时不知道罢了,接
- 导读12月总体来说互联网的技术圈是非常热闹的,chatGPT爆火,SpringBoot3.0发布等重磅陆消息续进入大家的视线,而本文作者将以
- 这篇讲解一下rocketMq的事务消息的原理在发送事务消息的时候,会加一个标识,表示这个消息是事务消息。broker接收到消息后,在我们之前
- 这篇文章主要介绍了SpringBoot以war包形式部署到外部Tomcat过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有
- 写在前面在前后端交互过程中,为了保证信息安全,我们往往需要加点用户验证。本文介绍了用springboot简单整合token。springbo
- Intellij IDEA 公司 JetBrains 推出了一种新字体:JetBrains Mono,它是专为开发人员设计的。为什么说它是专
- 本文实例讲述了Java线程同步方法。分享给大家供大家参考,具体如下:1. Semaphore1.1 二进制SemaphoreSemaphor
- 前面我们已经学习了平时实际开发中用得较多的线性布局(LinearLayout)与相对布局(RelativeLayout), 其实学完这两个基
- 一、什么是队列队列是一个有序列表,可以用数组或者链表来实现。遵循先入先出的原则,即:先存入队列的数据,要先取出。后存入的的数据,后取出。看一
- 一、引言最近发现很多人在论坛中问到如何防止程序被多次运行的问题的,如: http://social.msdn.microsoft.com/F
- 这一节我们将探索选择器(selectors)。选择器提供选择执行已经就绪的任务的能力,这使得多元 I/O 成为可能。就像在第一章中描述的那样
- Android屏蔽软键盘并且显示光标的实例详解如果是android4.0以下,那么editText.setInputType(InputTy
- Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试;生成测试数据初始化数据库用于测试;Spr