一、效果圖
三個按鈕,分別控制下載任務的開始、暫停和結束
下載任務在後臺運行,下載狀態在通知裏可以查看
下載完成後在SD卡中找到已下載的文件查看:
二、代碼
1、新建DownloadListener回調接口
/**
* 定義一個回調接口,用於對於下載過程中的各種狀態進行監聽和回調
*/
public interface DownloadListener {
//用於通知當前的下載進度
void onProgress(int progress);
//用於通知下載成功事件
void onSuccess();
//用於通知下載失敗事件
void onFailed();
//用於通知下載暫停事件
void onPaused();
//用於同事下載取消事件
void onCanceled();
}
2、新建一個DownloadTask類用於實現下載功能
/**
* 下載功能的實現
*/
/**
* AsyncTask中傳入3個泛型參數
* 第一個指定爲String,表示在執行AsyncTask的時候需要傳入一個字符串參數給後臺任務
* 第二個指定爲Integer,表示使用整型數據來作爲進度顯示單位
* 第三個泛型參數指定爲Integer,則表示使用整型數據來反饋執行結果
*/
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 DownloadListener listener;
private boolean isCanceled = false;
private boolean isPaused = false;
private int lastProgress;
DownloadTask(DownloadListener listener){
this.listener = listener;
}
/**
* 這個方法用於在後臺執行具體的下載邏輯
* @param strings
* @return
*/
@Override
protected Integer doInBackground(String... strings) {
InputStream is = null;
RandomAccessFile savedFile = null;
File file = null;
try{
long downloadLength = 0;//記錄已下載的文件長度
String downloadUrl = strings[0];//根據參數獲取到下載的URL地址
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));//根據URL地址解析出下載的文件名
//指定將文件下載到SD卡的Download目錄
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
//判斷目錄中是否已經存在要下載的文件了
if(file.exists()){
//已存在,讀取已下載的字節數
downloadLength = file.length();
}
//調用getContentLength()方法來獲取待下載的文件的總長度
long contentLength = getContentLength(downloadUrl);
//文件長度等於0則說明文件有問題
if(contentLength == 0 ){
return TYPE_FAILED;
//已下載字節和文件總字節相等,說明已經下載完成了
}else if(contentLength == downloadLength){
return TYPE_SUCCESS;
}
//使用OkHttp發送一條網絡請求
//在請求中添加一個header,用於告訴服務器我們想要從哪個字節開始下載
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//斷點下載,指定從那個字節開始下載
.addHeader("RANGE","bytes="+downloadLength+"-")
.url(downloadUrl)
.build();
//讀取服務器相應的數據
Response response = client.newCall(request).execute();
//使用Java的文件流方式,不斷從網絡上讀取數據,寫到本地
if(response != null){
is = response.body().byteStream();
savedFile = new RandomAccessFile(file,"rw");
savedFile.seek(downloadLength); //跳過已下載的字節
byte[] b = new byte[1024];
int total = 0;
int len;
while ((len = is.read(b)) != -1){
//判斷用戶有沒有觸發暫停或者取消的操作
if (isCanceled){
return TYPE_CANCELED;
}else if(isPaused){
return TYPE_PAUSED;
}else {
total += len;
savedFile.write(b,0,len);
//計算已下載的百分比
int progress = (int)((total + downloadLength) * 100 /contentLength);
//調用publishProgress()方法進行通知
publishProgress(progress);
}
}
response.body().close();
return TYPE_SUCCESS;
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(is!=null){
is.close();
}if(savedFile != null){
savedFile.close();
}if(isCanceled && file!=null){
file.delete();
}
}catch (Exception e){
e.printStackTrace();
}
}
return TYPE_FAILED;
}
/**
* 用於在界面上更新當前的下載進度
* @param values
*/
@Override
protected void onProgressUpdate(Integer... values) {
//從參數中獲取到當前的下載進度
int progress = values[0];
//和上一次的下載進度進行對比
if(progress > lastProgress){
listener.onProgress(progress);
lastProgress = progress;
}
}
/**
* 用於通知最終的下載結果
* @param status
*/
@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;
}
}
public void pauseDownload(){
isPaused = true;
}
public void cancelDownload(){
isCanceled = true;
}
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 contenLength = response.body().contentLength();
response.close();
return contenLength;
}
return 0;
}
}
3、新建一個下載服務DownloadService類
**
* 創建一個下載的服務,保證下載任務一直在後臺運行
*/
public class DownloadService extends Service {
private DownloadTask downloadTask;
private String downloadUrl;
//創建一個DownloadListener的匿名類實例
private DownloadListener listener = new DownloadListener() {
//調用getNotification()方法構建了一個用於顯示下載進度的通知
//調用getNotificationManager()的notify()方法去觸發這個通知。
@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();
}
};
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實例,
downloadTask = new DownloadTask(listener);
//,將下載文件的URL地址傳入execute()並開啓下載
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 + fileName);
//將正在下載的文件刪除掉
if(file.exists()){
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}
}
}
}
private NotificationManager getNotificationManager(){
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private Notification getNotification(String title,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);
builder.setContentTitle(title);
if(progress > 0 ){
//當progress大於或等於0時才需顯示下載進度
builder.setContentTitle(progress + "%");
//setProgress接受3個參數,第一個參數傳入通知的最大進度;
// 第二個從參數傳入通知的當前進度
//第三個參數表示是否使用模糊進度條
builder.setProgress(100,progress,false);
}
return builder.build();
}
}
4、寫佈局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/start_dowmload"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textSize="25dp"
android:text="開始下載"/>
<Button
android:id="@+id/pause_dowmload"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textSize="25dp"
android:text="暫停下載"/>
<Button
android:id="@+id/cancel_dowmload"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textSize="25dp"
android:text="停止下載"/>
</LinearLayout>
5、MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
@Override
public void onServiceConnected(ComponentName componentName,IBinder iBinder) {
downloadBinder = (DownloadService.DownloadBinder)iBinder;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button starDonload = (Button) findViewById(R.id.start_dowmload);
Button pauseDownload = (Button) findViewById(R.id.pause_dowmload);
Button cancelDownload = (Button) findViewById(R.id.cancel_dowmload);
starDonload.setOnClickListener(this);
pauseDownload.setOnClickListener(this);
cancelDownload.setOnClickListener(this);
Intent intent = new Intent(this,DownloadService.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 view) {
if(downloadBinder == null){
return;
}
switch (view.getId()) {
case R.id.start_dowmload:
//百度logo的地址
String url = "http://a2.att.hudong.com/10/96/300000931099127952960461732_950.jpg";
downloadBinder.startDownload(url);
break;
case R.id.pause_dowmload:
downloadBinder.pauseDownload();
break;
case R.id.cancel_dowmload:
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);
}
}
6、聲明權限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
然後,運行看效果吧~~