Android DownloadManager下載下傳完成事件監聽(系列4)
我在之前寫了寫一些關于Android DownloadManager 的文章:
(系列1)《Android大資料、斷點續傳、耗時下載下傳之DownloadManager開發簡介(1)》文章連結位址:
http://blog.csdn.net/zhangphil/article/details/48949027 (系列2)《Android DownloadManager下載下傳狀态查詢(2)》文章連結位址: http://blog.csdn.net/zhangphil/article/details/48976427 (系列3)《Android DownloadManager下載下傳進度查詢(系列3)》文章連結位址: http://blog.csdn.net/zhangphil/article/details/49248723文章(1)簡單介紹了Android DownloadManager的基礎使用方法;文章(2)是Android DownloadManager的基礎下載下傳狀态查詢;文章(3)是Android DownloadManager下載下傳進度的查詢。
本文是在前三篇文章的基礎上寫作而成,本文介紹:當Android DownloadManager下載下傳某一個任務完成時候,可以立即獲得下載下傳任務完成的消息通知。Android DownloadManager通過注冊一個廣播監聽系統的廣播事件完成此操作,在建立廣播時候,需要指明過濾器為:DownloadManager.ACTION_DOWNLOAD_COMPLETE
測試的主Activity MainActivity.java:
package zhangphil.demo;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
private BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// 假設從這一個連結下載下傳一個大檔案。
Request request = new Request(
Uri.parse("http://apkc.mumayi.com/2015/03/06/92/927937/xingxiangyi_V3.1.3_mumayi_00169.apk"));
// 僅允許在WIFI連接配接情況下下載下傳
request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
// 通知欄中将出現的内容
request.setTitle("我的下載下傳");
request.setDescription("下載下傳一個大檔案");
// 下載下傳過程和下載下傳完成後通知欄有通知消息。
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE | Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// 此處可以由開發者自己指定一個檔案存放下載下傳檔案。
// 如果不指定則Android将使用系統預設的
// request.setDestinationUri(Uri.fromFile(new File("")));
// 預設的Android系統下載下傳存儲目錄
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my.apk");
// enqueue 開始啟動下載下傳...
long Id = downloadManager.enqueue(request);
Log.d(this.getClass().getName(), "開始下載下傳任務:" + Id + " ...");
listener(Id);
}
private void listener(final long Id) {
// 注冊廣播監聽系統的下載下傳完成事件。
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (ID == Id) {
Toast.makeText(getApplicationContext(), "任務:" + Id + " 下載下傳完成!", Toast.LENGTH_LONG).show();
}
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
}