当前位置: 首页 > 工具软件 > FAR Manager > 使用案例 >

android编程 下载文件,Android开发(22)使用DownloadManager下载文件

淳于哲
2023-12-01

概述

使用DownloadManager 是个很好用的下载方式。它会出现在任务栏,指示当前的下载位置。它使用广播来接收完成消息,点击任务事件的交互。

实现步骤

1.添加权限

2.在页面里初始化

DownloadManager downloadManager;

// 过SystemService 以获取 DownloadManager

downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

3.启动下载

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); // 加入下载队列

startQuery(mDownloadId);

4.移除(停止)下载

private int removeDownload(long downloadId) {

return downloadManager.remove(downloadId);

}

5.监听下载的完成

@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();

}

// 监听下载结束,启用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.在下载过程中,查看状态

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) {

// 关键:通过ID向下载管理查询下载情况,返回一个cursor

Cursor c = downloadManager.query(new DownloadManager.Query()

.setFilterById(downID));

if (c == null) {

Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG)

.show();

} else { // 以下是从游标中进行信息提取

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); // 加入下载队列

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) {

// 关键:通过ID向下载管理查询下载情况,返回一个cursor

Cursor c = downloadManager.query(new DownloadManager.Query()

.setFilterById(downID));

if (c == null) {

Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG)

.show();

} else { // 以下是从游标中进行信息提取

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";

}

}

// 监听下载结束,启用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

// 监听下载结束,启用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();

}

}

};//

}

参考资料

 类似资料: