概述
使用DownloadManager 是個(gè)很好用的下載方式醒颖。它會(huì)出現(xiàn)在任務(wù)欄,指示當(dāng)前的下載位置壳炎。它使用廣播來接收完成消息泞歉,點(diǎn)擊任務(wù)事件的交互逼侦。
實(shí)現(xiàn)步驟
1.添加權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
2.在頁面里初始化
DownloadManager downloadManager;
// 過SystemService 以獲取 DownloadManager
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3.啟動(dòng)下載
Request request = new Request(
Uri.parse("http://192.168.3.123:8080/androidautoupdate/apks/2.zip"));
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_WIFI)
.setAllowedOverRoaming(false) // 缺省是true
.setTitle("更新") // 用于信息查看
.setDescription("下載apk") // 用于信息查看
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "2.zip");
mDownloadId = downloadManager.enqueue(request); // 加入下載隊(duì)列
startQuery(mDownloadId);
4.移除(停止)下載
private int removeDownload(long downloadId) {
return downloadManager.remove(downloadId);
}
5.監(jiān)聽下載的完成
@Override
protected void onPause() {
stopQuery();
this.unregisterReceiver(receiver);
super.onPause();
}
@Override
protected void onResume() {
IntentFilter filter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
this.registerReceiver(receiver, filter);
IntentFilter filter22 = new IntentFilter(
DownloadManager.ACTION_NOTIFICATION_CLICKED);
this.registerReceiver(receiver2, filter22);
startQuery(mDownloadId);
super.onResume();
}
// 監(jiān)聽下載結(jié)束,啟用BroadcastReceiver
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
// 查詢
Query query = new Query();
query.setFilterById(downloadId);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//removeDownload(downloadId);
Toast.makeText(MainActivity.this,
"get file complete: " + uriString, 0).show();
// Uri.parse(uriString);
}
}// endif
}// endif
}// onReceive
};// end class receiver
6.在下載過程中腰耙,查看狀態(tài)
class QueryRunnable implements Runnable {
public long DownID;
@Override
public void run() {
queryState(DownID);
handler.postDelayed(runnable, step);
}
};
private void startQuery(long downloadId) {
if (downloadId != 0) {
runnable.DownID = downloadId;
handler.postDelayed(runnable, step);
}
};
private void stopQuery() {
handler.removeCallbacks(runnable);
}
private void queryState(long downID) {
// 關(guān)鍵:通過ID向下載管理查詢下載情況榛丢,返回一個(gè)cursor
Cursor c = downloadManager.query(new DownloadManager.Query()
.setFilterById(downID));
if (c == null) {
Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG)
.show();
} else { // 以下是從游標(biāo)中進(jìn)行信息提取
if(!c.moveToFirst()){
c.close();
return;
}
Log.d(TAG,
"Column_id : "
+ c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_ID)));
Log.d(TAG,
"Column_bytes_downloaded so far : "
+ c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
Log.d(TAG,
"Column last modified timestamp : "
+ c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
Log.d(TAG,
"Column local uri : "
+ c.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
Log.d(TAG,
"Column statue : "
+ c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS)));
Log.d(TAG,
"Column reason : "
+ c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_REASON)));
int st = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
Toast.makeText(this, statusMessage(st), Toast.LENGTH_LONG).show();
//Log.i(TAG, statusMessage(st));
c.close();
}
}
private String statusMessage(int st) {
switch (st) {
case DownloadManager.STATUS_FAILED:
return "Download failed";
case DownloadManager.STATUS_PAUSED:
return "Download paused";
case DownloadManager.STATUS_PENDING:
return "Download pending";
case DownloadManager.STATUS_RUNNING:
return "Download in progress!";
case DownloadManager.STATUS_SUCCESSFUL:
return "Download finished";
default:
return "Unknown Information";
}
}
完整代碼
package example.downloaddemo;
import java.io.File;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
/**
* 參考:http://blog.csdn.net/flowingflying/article/details/6925683
* @author yunfei
*
*/
public class MainActivity extends Activity {
private static final String TAG = "PDWY";
// an ID for the download, unique across the system. This ID is used to make
// future calls related to this download.
long mDownloadId;
DownloadManager downloadManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 過SystemService 以獲取 DownloadManager
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
}
@Override
protected void onPause() {
stopQuery();
this.unregisterReceiver(receiver);
super.onPause();
}
@Override
protected void onResume() {
IntentFilter filter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
this.registerReceiver(receiver, filter);
IntentFilter filter22 = new IntentFilter(
DownloadManager.ACTION_NOTIFICATION_CLICKED);
this.registerReceiver(receiver2, filter22);
startQuery(mDownloadId);
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void lookDownload() {
startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
}
public void onClick(View view) {
int id = view.getId();
if (id == R.id.start) {
Request request = new Request(
Uri.parse("http://192.168.3.123:8080/androidautoupdate/apks/2.zip"));
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_WIFI)
.setAllowedOverRoaming(false) // 缺省是true
.setTitle("更新") // 用于信息查看
.setDescription("下載apk") // 用于信息查看
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "2.zip");
mDownloadId = downloadManager.enqueue(request); // 加入下載隊(duì)列
startQuery(mDownloadId);
}
if (id == R.id.stop) {
stopQuery();
removeDownload(mDownloadId);
}
if (id == R.id.look) {
lookDownload();
}
}
private int removeDownload(long downloadId) {
return downloadManager.remove(downloadId);
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
int step = 1000;
QueryRunnable runnable = new QueryRunnable();
class QueryRunnable implements Runnable {
public long DownID;
@Override
public void run() {
queryState(DownID);
handler.postDelayed(runnable, step);
}
};
private void startQuery(long downloadId) {
if (downloadId != 0) {
runnable.DownID = downloadId;
handler.postDelayed(runnable, step);
}
};
private void stopQuery() {
handler.removeCallbacks(runnable);
}
private void queryState(long downID) {
// 關(guān)鍵:通過ID向下載管理查詢下載情況,返回一個(gè)cursor
Cursor c = downloadManager.query(new DownloadManager.Query()
.setFilterById(downID));
if (c == null) {
Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG)
.show();
} else { // 以下是從游標(biāo)中進(jìn)行信息提取
if(!c.moveToFirst()){
c.close();
return;
}
Log.d(TAG,
"Column_id : "
+ c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_ID)));
Log.d(TAG,
"Column_bytes_downloaded so far : "
+ c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
Log.d(TAG,
"Column last modified timestamp : "
+ c.getLong(c
.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
Log.d(TAG,
"Column local uri : "
+ c.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
Log.d(TAG,
"Column statue : "
+ c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS)));
Log.d(TAG,
"Column reason : "
+ c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_REASON)));
int st = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
Toast.makeText(this, statusMessage(st), Toast.LENGTH_LONG).show();
//Log.i(TAG, statusMessage(st));
c.close();
}
}
private String statusMessage(int st) {
switch (st) {
case DownloadManager.STATUS_FAILED:
return "Download failed";
case DownloadManager.STATUS_PAUSED:
return "Download paused";
case DownloadManager.STATUS_PENDING:
return "Download pending";
case DownloadManager.STATUS_RUNNING:
return "Download in progress!";
case DownloadManager.STATUS_SUCCESSFUL:
return "Download finished";
default:
return "Unknown Information";
}
}
// 監(jiān)聽下載結(jié)束挺庞,啟用BroadcastReceiver
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
// 查詢
Query query = new Query();
query.setFilterById(downloadId);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
//removeDownload(downloadId);
Toast.makeText(MainActivity.this,
"get file complete: " + uriString, 0).show();
// Uri.parse(uriString);
}
}// endif
}// endif
}// onReceive
};// end class receiver
// 監(jiān)聽下載結(jié)束晰赞,啟用BroadcastReceiver
BroadcastReceiver receiver2 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
lookDownload();
}
}
};//
}
參考資料
http://developer.android.com/intl/zh-CN/reference/android/app/DownloadManager.html