1、DownloadListener
下载接口
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPaused();
void onCanceled();
}
2、新建DownloadTask继承自AsyncTask。实现下载过程
public class DownloadTask extends AsyncTask<String, Integer, Integer> {
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAILED = 1;
public static final int TYPE_PAUSED = 2;
public static final int TYPE_CANCELED = 3;
private boolean isCanceled = false;
private boolean isPaused = false;
private DownloadListener listener;
private int lastProgress;
public DownloadTask(DownloadListener listener) {
this.listener = listener;
}
@Override
protected Integer doInBackground(String... params) {
File file = null;
RandomAccessFile saveFile = null;
InputStream is = null;
int downloadLength = 0;//记录下载文件长度
try {
String downloadUrl = params[0];
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
if (file.exists()) {
downloadLength = (int) file.length();
}
long contentLength = getContentLength(downloadUrl);
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 (response != null && response.isSuccessful()) {
is = response.body().byteStream();
saveFile = new RandomAccessFile(file, "rw");
saveFile.seek(downloadLength);
byte[] b = new byte[1024];
int len, total = 0;
while ((len = is.read(b)) != -1) {
if (isCanceled) {
return TYPE_CANCELED;
} else if (isPaused) {
return TYPE_PAUSED;
} 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 {
if (is != null) {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (saveFile != null) {
try {
saveFile.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (isCanceled && file != null) {
file.delete();
}
}
return TYPE_FAILED;
}
@Override
protected void onProgressUpdate(Integer... values) {
int value = values[0];
if (value > lastProgress) {
listener.onProgress(value);
lastProgress = value;
}
}
@Override
protected void onPostExecute(Integer status) {
switch (status) {
case TYPE_SUCCESS:
listener.onSuccess();
break;
case TYPE_FAILED:
listener.onFailed();
break;
case TYPE_PAUSED:
listener.onPaused();
break;
case TYPE_CANCELED:
listener.onCanceled();
break;
default:
break;
}
}
@Nullable
private long getContentLength(String downloadUrl) {
try {
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 = response.body().contentLength();
response.close();
return contentLength;
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public void pauseDownload() {
isPaused = true;
}
public void cancelDownload() {
isCanceled = true;
}
}
3、编写下载Service
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import java.io.File;
public class DownloadService extends Service {
private String downloadUrl;
private DownloadTask downloadTask;
private DownloadBindler downloadBindler = new DownloadBindler();
private DownloadListener downloadListener = new DownloadListener() {
@Override
public void onProgress(int progress) {
getNotificationManager().notify(1, getNotification("Downloading....", progress));
}
@Override
public void onSuccess() {
downloadTask = null;
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Success....", -1));
Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailed() {
downloadTask = null;
//下载失败时将前台通知关闭,并创建一个新的下载失败的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Failed....", -1));
Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onPaused() {
downloadTask = null;
Toast.makeText(DownloadService.this, "Paused", Toast.LENGTH_SHORT).show();
}
@Override
public void onCanceled() {
downloadTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
};
class DownloadBindler extends Binder {
public void startDownload(String url) {
if (downloadTask == null) {
downloadUrl = url;
downloadTask = new DownloadTask(downloadListener);
downloadTask.execute(downloadUrl);
startForeground(1, getNotification("Downloading...", 0));
Toast.makeText(DownloadService.this, "Downloading...", Toast.LENGTH_SHORT).show();
}
}
public void pauseDownload() {
if (downloadTask != null) {
downloadTask.pauseDownload();
}
}
public void cancelDownload() {
if (downloadTask != null) {
downloadTask.cancelDownload();
} else {
if (downloadUrl != null) {
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath();
File file = new File(directory.concat(fileName));
if(file.exists()){
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return downloadBindler;
}
private NotificationManager getNotificationManager() {
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private Notification getNotification(String title, int progress) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = 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.setContentTitle(title);
builder.setContentIntent(pendingIntent);
if (progress > 0) {
//当进度大于0才显示进度
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}
}
4、修改 AndroidManifest.xml。
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
///看这里
<service android:name=".DownloadService"/>
</application>
5、编写界面xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.mbh.downloadservice.MainActivity">
<Button
android:id="@+id/start_download"
android:text="start"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/pause_download"
android:text="pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/cancel_download"
android:text="cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
6、Activity
import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button startBtn, pauseBtn, cancelBtn;
private DownloadService.DownloadBindler downloadBindler;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBindler = (DownloadService.DownloadBindler) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button) findViewById(R.id.start_download);
pauseBtn = (Button) findViewById(R.id.pause_download);
cancelBtn = (Button) findViewById(R.id.cancel_download);
startBtn.setOnClickListener(this);
pauseBtn.setOnClickListener(this);
cancelBtn.setOnClickListener(this);
Intent intent = new Intent(this,DownloadService.class);
startService(intent);
bindService(intent,connection,BIND_AUTO_CREATE);
String writeExternalStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE;
String internet = Manifest.permission.INTERNET;
requestPermission(writeExternalStorage,internet);
}
private void requestPermission(String... permissions) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
permissions[0]) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,permissions, 1);
}
}
@Override
public void onClick(View v) {
if(downloadBindler == null){
return ;
}
switch (v.getId()){
case R.id.start_download:
String url = "http://file45.ting55.com/mplay/2017/10/11216/499.mp3?s=rR1xsTNA5iufa8xSQn4B7g&e=1522748309";
downloadBindler.startDownload(url);
break;
case R.id.pause_download:
downloadBindler.pauseDownload();
break;
case R.id.cancel_download:
downloadBindler.cancelDownload();
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(MainActivity.this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
非常简单,没有实现多线程。后面有时间可能会考虑加入。8.0环境通知栏可能会发生变化