這次的這個demo想要實現一個后台下載文件的功能,下載的時候會有一個告知進度的通知,
使用的依賴庫就一個:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
大體思路是創建一個AsyncTask運行在Service中,然后活動和Service進行通信,實現開始、暫停、取消下載的功能
所以先創建一個接口:
public interface DownloadListener { //用於通知當前下載進度 void onProgress(int progress); //用於通知下載成功 void onSuccess(); //用於通知下載失敗 void onFailed(); //用於通知下載暫停 void onPaused(); //用於通知下載取消 void onCanceled(); }
然后是下載這個行為的AsyncTask,AsyncTask是一個可以十分簡單的從子線程切換到主線程的工具,AsyncTask是一個抽象類所以要創建一個類去繼承它。
首先AsyncTask有三個泛型參數,第一個Params是傳入的參數的類型,這里需要傳入的是文件下載的地址,所以設定為String類型,第二個參數是Progress后台任務執行的時候,需要顯示進度時使用這里的泛型作為進度單位,所以這里設為Integer,第三個參數是Result用於反饋執行結果,這里依舊使用Integer
還有經常需要重寫的四個方法,onPreExecute()這個方法是在任務開始前進行的,它由UI線程(主線程)調用,即可以進行UI操作,這里我想要在Service中執行這個下載的任務就不需要這個方法了就略過,然后是最重要的doInBackground(Params...),這個方法是onPreExecute()完成后,立即在后台進行的,用以執行任務,並將Result傳給onPostExecute(Result)。另外,在此期間,可以調用publishProgress(Progress...),這個方法能夠傳遞一些數據給onProgressUpdate(Progress...),所以這里就需要執行下載,保存,反饋進度所有的下載邏輯,再然后就是onProgressUpdate(Progress...)這里可以使用來自doInBackground的數據,然后UI的操作,這里就用來修改通知的進度條就行了,最后就是onPostExecute(Result)根據來自doInBackground的結果用於通知最后的結果了。
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; public DownloadTask(DownloadListener listener){ this.listener = listener; } @Override protected Integer doInBackground(String... params) { InputStream is = null; RandomAccessFile savedFile = null; File file = null; try{ long downloadedLength = 0;//記錄已經下載的文件長度 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()){ downloadedLength = file.length(); } long contentLength = getContentLength(downloadUrl); if(contentLength == 0){ return TYPE_FAILED; }else if(contentLength == downloadedLength){ //已下載字節與總文件字節相等 說明已經下載完成 return TYPE_SUCCESS; } OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() //斷點下載,指定從那個字節下載 .addHeader("RANGE", "bytes=" + downloadedLength + "-") .url(downloadUrl) .build(); Response response = client.newCall(request).execute(); if (response != null){ is = response.body().byteStream(); savedFile = new RandomAccessFile(file, "rw"); savedFile.seek(downloadedLength);//跳過已經下載好的字節 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 + downloadedLength) * 100 / contentLength); 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; } @Override protected void onProgressUpdate(Integer... values) { int progress = values[0]; if(progress > lastProgress){ listener.onProgress(progress); lastProgress = progress; } } @Override protected void onPostExecute(Integer integer) { switch (integer){ 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 contentLength = response.body().contentLength(); response.body().close(); return contentLength; } return 0; } }
具體其中下載時候 保存、斷點下載、中斷的邏輯下次再說吧==。
然后是Service,Service的使用同樣需要創建一個類來繼承Service,這次的主題是Service,其實應該寫點小demo探究生命周期什么的==,算了以后弄把,這次改標題就好了。然后這次是想要使用服務執行一個任務,然后讓活動綁定這個服務,然后使用服務中的提供的接口實現開始、暫停、取消的功能,
綁定服務是 Service 類的實現,可讓其他應用與其綁定和交互。要提供服務綁定,您必須實現 onBind() 回調方法。該方法返回的 IBinder 對象定義了客戶端用來與服務進行交互的編程接口。
客戶端可通過調用 bindService() 綁定到服務。調用時,它必須提供 ServiceConnection 的實現,后者會監控與服務的連接。bindService() 方法會立即無值返回,
但當 Android 系統創建客戶端與服務之間的連接時,會對 ServiceConnection 調用 onServiceConnected(),向客戶端傳遞用來與服務通信的 IBinder。
這是google文檔中的描述,意思就是這個子類中要重寫的方法只有onBind(),這個方法會返回一個IBinder對象,意思就是創建一個內部類繼承自Binder,這個類里面的方法就需要實現開始、暫停、取消。然后使用這個類創建一個名為的IBinder對象在onBind()中返回就好了
public class DownloadService extends Service { private DownloadTask downloadTask; private String downloadUrl; private DownloadListener listener = 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("下載中", -1)); Toast.makeText(DownloadService.this, "下載成功", Toast.LENGTH_SHORT).show(); } @Override public void onFailed() { downloadTask =null; //下載失敗后將前台服務通知關閉,並創建一個下載成功的通知 stopForeground(true); getNotificationManager().notify(1, getNotification("下載失敗", -1)); Toast.makeText(DownloadService.this, "下載失敗", Toast.LENGTH_SHORT).show(); } @Override public void onPaused() { downloadTask = null; Toast.makeText(DownloadService.this, "下載暫停", Toast.LENGTH_SHORT).show(); } @Override public void onCanceled() { downloadTask = null; stopForeground(true); Toast.makeText(DownloadService.this, "下載取消", 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(DownloadService.this, "下載中", 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, "取消", 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){ //當進度大於0或者等於0的時候才顯示下載進度 builder.setContentText(progress + "%"); builder.setProgress(100, progress , false); } return builder.build(); } }
然后就是活動了,活動中要實現的就是控制服務中的任務,
Intent intent = new Intent(this, DownloadService.class); startService(intent);//啟動服務 bindService(intent, connection, BIND_AUTO_CREATE);//綁定服務
首先是啟動和綁定這個服務。其中的connection是一個需要重寫的匿名類
private DownloadService.DownloadBinder downloadBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { downloadBinder = (DownloadService.DownloadBinder) iBinder; } @Override public void onServiceDisconnected(ComponentName componentName) { } };
downloadBinder就是在服務中創建的類,這里的綁定只需要把服務返回的iBinder實例化即可。
整體的代碼是這樣:
public class MainActivity extends AppCompatActivity { private DownloadService.DownloadBinder downloadBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { downloadBinder = (DownloadService.DownloadBinder) iBinder; } @Override public void onServiceDisconnected(ComponentName componentName) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startDownload = (Button) findViewById(R.id.start_download); Button pauseDownload = (Button) findViewById(R.id.pause_download); Button cancelDownload = (Button) findViewById(R.id.cancel_download); Intent intent = new Intent(this, DownloadService.class); startService(intent);//啟動服務 bindService(intent, connection, BIND_AUTO_CREATE);//綁定服務 if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1); } startDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe"; downloadBinder.startDownload(url); } }); pauseDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { downloadBinder.pauseDownload(); } }); cancelDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { downloadBinder.cancelDownload(); } }); } @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); } }
然后還有注意權限的申請
<manifest ... <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ... </manifest>
