由于我们需要访问网络,先将所需依赖库声明:dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.4.1' //声明Okhttp
}
接下来需要定义一个回调接口, 用于对下载过程中的各种状态进行监听和回调。 如下:public interface DownloadListener {
void onProgress(int progress); //通知下载进度
void onSucceed(); //通知下载成功事件
void onFailed(); //通知下载失败事件
void onPaused(); //通知下载停止事件
void onCanceled(); //通知下载取消事件
}
接着编写下载功能, 使用AsyncTask进行实现。public class DownloadTask extends AsyncTask {
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAILED = 1;
public static final int TYPE_PAUSE = 2;
public static final int TYPE_CANCELED = 3;
private DownloadListener listener;
private boolean isCanceled = false;
private boolean isPause = false;
private int lastProgress;
public DownloadTask(DownloadListener listener) {
this.listener = listener;
}
@Override
protected Integer doInBackground(String... strings) {
InputStream in = null;
RandomAccessFile saveFile = null;
File file = null;
try{
long downloadLength = 0; //记录已下载的文件长度
String downloadUrl = strings[0];
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(); //将文件下载到SD卡的Download目录
file = new File(directory + fileName);
if (file.exists()) {
downloadLength = file.length();
}
long contentLength = file.length();
if (contentLength == 0) {
return TYPE_FAILED;
}else if (contentLength == downloadLength) {
//已下载字节和文件总字节相等, 说明已下载完成
return TYPE_SUCCESS;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("RANGE", "bytes=" + downloadLength + "-" )
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if (request != null) {
in = response.body().byteStream();
saveFile = new RandomAccessFile(file, "rw");
saveFile.seek(downloadLength); //跳过已下载的字节
byte[] b = new byte[1024];
int total = 0;
int len;
while((len = in.read(b)) != -1){
if (isCanceled) {
return TYPE_CANCELED;
}else if (isPause) {
return TYPE_PAUSE;
}else {
total += len;
saveFile.write(b, 0, len);
//计算已下载百分比
int progress = (int) ((total + downloadLength) * 100 / contentLength);
publishProgress(progress);
}
}
response.body().close();
return TYPE_SUCCESS;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if (in != null){
in.close();
}
if (saveFile != null){
saveFile.close();
}
if (isCanceled && file != null) {
file.delete();
}
}catch (Exception e){
e.printStackTrace();
}
}
return TYPE_FAILED;
}
@Override
protected void onProgressUpdate(Integer... values) {
int proogress = values[0];
if (proogress > lastProgress) {
listener.onProgress(proogress);
lastProgress = proogress;
}
}
@Override
protected void onPostExecute(Integer integer) {
switch (integer) {
case TYPE_SUCCESS:
listener.onSucceed();
break;
case TYPE_FAILED:
listener.onFailed();
break;
case TYPE_PAUSE:
listener.onPaused();
break;
case TYPE_CANCELED:
listener.onCanceled();
break;
default:
break;
}
}
public void pauseDodnload(){
isCanceled = true;
}
public void cancelDownload(){
isCanceled = true;
}
//getContentLength()方法获取下载文件的总长度,
private long getContentLength(String downloadUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if (response != null && response.isSuccessful()) {
long contentLength = request.body().contentLength();
response.body().close();
return contentLength;
}
return 0;
}
}
AsyncTask中的3个泛型参数, 第一个String便是在执行AsyncTask是需要传入一个字符串参数给后台任务, 第二个Integer 表示使用整型数据来作为进度显示单位, 第三个表示使用整型数据来反馈执行结果。
接下来定义了4个整型常量用于表示下载状态, 待会就会将下载的状态通过这个参数进行回调。
doInBackground()方法用于在后台执行具体的下载逻辑, onProgressUpdata()方法用于在界面进行更新下载条, onPostExecute()用于通知最终的下载结果。
当文件长度既不为0 也不为已下载文件长度时,就是要OkHttp来发送一条网络请求, 这里在请求中添加了一个header, 用于告诉服务器我们想要从哪个字节开始下载, 因为已经下载完成的就无需下载了。 接下来读取服务器返回的数据, 并使用Java的文件流的方式, 不断从网络读取数据, 不断将读取的数据写入到本地, 知道全部下载完成。
在下载过程中我们还需要判断用户有没有 暂停或取消下载的操作,如果有的话则返回TYPE_PAUSED或TYPE_CANCELED 来中断下载, 如果没有的话 则实时计算进度,然后调用publishProgress()方法进行通知。
如此,我们就把下载功能完成了, 为了保证下载任务可以在后台一直运行, 就需要创建一个下载的服务. 此时新建服务, 代码如下:public class MyService extends Service {
private DownloadTask downloadTask;
private String downloadUrl;
public MyService() {
}
private DownloadListener listener = new DownloadListener() {
@Override
public void onProgress(int progress) {
getNotificationManager().notify(1, getNotification("Downloading..." , progress));
}
@Override
public void onSucceed() {
downloadTask = null;
//下载成功时将前台服务通知关闭,并创建一个下载成功的通知
stopForeground(true);
getNotificationManager().notify(1,getNotification("Download succcess", -1));
Toast.makeText(MyService.this, "Download Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailed() {
downloadTask = null;
//下载失败时前台服务通知关闭, 并创建一个下载失败的通知
stopForeground(true);
getNotificationManager().notify(1,getNotification("Download Failed", -1));
Toast.makeText(MyService.this, "Download Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onPaused() {
downloadTask = null;
Toast.makeText(MyService.this, "Download Paused", Toast.LENGTH_SHORT).show();
}
@Override
public void onCanceled() {
downloadTask = null;
Toast.makeText(MyService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
};
private DownloadBinder mBinder =new DownloadBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class DownloadBinder extends Binder{
public void startDownload(String url) {
if (downloadTask == null) {
downloadUrl = url;
downloadTask = new DownloadTask(listener);
downloadTask.execute(downloadUrl);
startForeground(1, getNotification("Downloading...", 0));
Toast.makeText(MyService.this, "Downloading...", Toast.LENGTH_SHORT).show();
}
}
public void pauseDownload(){
if (downloadTask != null) {
downloadTask.pauseDownload();
}
}
public void cancelDownload(){
if (downloadTask != null) {
downloadTask.cancelDownload();
}
if (downloadUrl != null) {
//取消下载时需将文件删除, 并将通知关闭
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
File file = new File(directory + fileName);
if (file.exists()) {
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(MyService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
}
}
private NotificationManager getNotificationManager(){
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private Notification getNotification(String s, int progress) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentIntent(pi);
if (progress > 0){
//当progress大于或等于0时才显示下载速度
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}
}
首先此创建了一个DownloadListener的匿名类实例, 并在这个匿名类中实现了接口的五个方法, 在onnProgress()方法中, 我们调用getNotification()方法构建了一个用于显示下载进度的通知, 调用NotificationManager 的 nitify()方法去触发这个通知。 在 onSuccess()方法中 首先是将正在下载的前台通知关闭, 然后创建一个新的通知用于告诉用户下载成功了。 其余方法类似。
接下来为了让服务可以和活动进行通信, 我们又创建了一个DownloadBinder。 DownloadBinder中提供了 startDownload(), pauseDownload(), 和 cancelDownload()这3个方法。 在startDownload()中 创建了一个 DownloadTask的实例, 把刚才的 DownloadListener 作为参数传入, 调用execute()开启下载, 并将下载文件的url地址传到execute()方法中。调用startForeground()方法让此下载服务成为前台服务, 这样就会在系统状态栏创建一个持续的通知了。 另外服务类中所有使用到的通知都是调用getNotification()方法进行构建的, 介绍一下其中的 setProgress()方法 此方法接收3个参数, 第一个为传入通知的最大进度, 第二个为传入通知的当前进度, 第三个表示是否使用模糊进度条。 设置完setProgress()方法, 通知栏就会有进度条显示了。
现在下载的服务也已经实现, 后端的工作基本完成了, 那么接下来开始编写前端的部分。 修改主活动代码:<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/start_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start download"
/>
android:id="@+id/pause_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="pause download"
/>
android:id="@+id/cancel_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="cancel download"
/>
然后修改主活动:public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start_download = (Button) findViewById(R.id.start_download);
Button pause_download = (Button) findViewById(R.id.pause_download);
Button cancel_download = (Button) findViewById(R.id.cancel_download);
start_download.setOnClickListener(this);
pause_download.setOnClickListener(this);
cancel_download.setOnClickListener(this);
Intent intent = new Intent(this, MyService.class);
startService(intent); //启动服务
bindService(intent, connection, BIND_AUTO_CREATE); //绑定服务
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
@Override
public void onClick(View v) {
if (downloadBinder == null){
return;
}
switch (v.getId()){
case R.id.start_download:
String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
downloadBinder.startDownload(url);
break;
case R.id.pause_download:
downloadBinder.pauseDownload();
break;
case R.id.cancel_download:
downloadBinder.cancelDownload();
break;
default:
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] !=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "拒绝权限", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
可以看到, 这里我们首先创建了一个SrviceConnection匿名类, 然后在onServiceConnected()方法中获取到DownloadBinder的实例, 有了这个实例, 就可以在活动中调用服务提供的各种方法了。
在onCreate()方法中分别调用 startService()和 bindService() 方法来启动和 绑定服务。 这一点很重要, 因为启动服务可以保证服务一直在后台运行, 绑定服务可以让MainActivity和 下载服务进行通信, 因此两个方法都必不可少。 在onCreat()方法的最后 我们还进行了 WRITE_EXTERNAL_STORAGE 的运行时权限申请, 将文件下载到SD卡的Download目录下。
另外注意, 如果活动被销毁了, 那么一定要对服务进行解绑, 不然可能造成内存泄漏, 这里我们在onDestory()中进行了解绑。