前一章写到使用HttpUrlConnection或HttpClient做APP下载更新,这章来说下DownloadManager。
DownloadManager系统下载管理的使用
主要代码
public class MainActivity extends Activity implements android.view.View.OnClickListener {
private static final String TAG = "MainActivity";
private Button startBtn, pauseBtn, stopBtn;
private TextView mInfoText;
private DownloadManager mDownloadManager;
private String path = "http://dldir1.qq.com/weixin/android/weixin602android520.apk";
private BroadcastReceiver mReceiver;
private long downloadId;
private ApplicationsIntentReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.start_download);
pauseBtn = (Button) findViewById(R.id.btn_query);
stopBtn = (Button) findViewById(R.id.btn_del);
mInfoText = (TextView) findViewById(R.id.download_info);
startBtn.setOnClickListener(this);
pauseBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (TextUtils.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE, action)) {
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadId == reference) {
mInfoText.setText("下载结束");
mInfoText.setTextColor(Color.RED);
mInfoText.setTextSize(30);
}
} else if (TextUtils.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED, action)) {
String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
long[] references = intent.getLongArrayExtra(extraID);
for (long reference : references)
if (reference == downloadId) {
DownloadView();
}
}
}
};
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
mFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
registerReceiver(mReceiver, mFilter);
registerIntentReceivers();
}
private void registerIntentReceivers() {
IntentFilter filter;
filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
registerReceiver(mApplicationsReceiver, filter);
}
/**
* Receives notifications when applications are added/removed.
*/
private class ApplicationsIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
{
Log.i(TAG, "============================RETURN VALUE ");
if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Uri uri = null;
uri = intent.getData();
Log.i(TAG, "+++++++++++++++++++++++RETURN VALUE " + uri);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Uri uri = null;
uri = intent.getData();
Log.i(TAG, "----------------------------RETURN VALUE " + uri);
}
}
}
}
private void DownloadView() {
startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch (id) {
case R.id.start_download:
mInfoText.setText("开始下载");
mInfoText.setTextSize(30);
Uri uri = Uri.parse(path);
DownloadManager.Request request = new DownloadManager.Request(uri);
// SDK 11以上可以使用, 允许扫描,在Download中显示
// request.allowScanningByMediaScanner();
// 设置允许下载网络类型:WIFI或者 3G
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
// 设置Notification 通知信息
request.setDescription("正在下载apk");
String filename = path.substring(path.lastIndexOf("/") + 1);
// 文件下载保存目录
request.setDestinationInExternalFilesDir(getApplicationContext(), null, filename);
// 设置下载中Notification显示如果使用DownloadManager.Request.VISIBILITY_HIDDEN 需要加入权限
// android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
// SDK 11 以上可以使用
// DownloadManager.Request.VISIBILITY_HIDDEN
// DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
// DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// 设置Notification Title
// request.setShowRunningNotification(true);
request.setTitle("下载");
// 加入下载队列
downloadId = mDownloadManager.enqueue(request);
break;
case R.id.btn_query:
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = mDownloadManager.query(query);
if (cursor == null) {
mInfoText.setText("没有数据");
mInfoText.setTextSize(30);
} else {
if (cursor.moveToFirst()) {
// 查询已经下载的大小
long downsize = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
String desc = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
String time = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP));
String fn = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
String localUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String mediaType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
String mediaUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIAPROVIDER_URI));
int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
long totalSize = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
StringBuilder sb = new StringBuilder();
sb.append("downsize = " + downsize).append("\n");
sb.append("desc = " + desc).append("\n");
sb.append("time = " + time).append("\n");
sb.append("fn = " + fn).append("\n");
sb.append("localUri = " + localUri).append("\n");
sb.append("mediaType = " + mediaType).append("\n");
sb.append("mediaUri = " + mediaUri).append("\n");
sb.append("reason = " + reason).append("\n");
sb.append("status = " + status).append("\n");
sb.append("title = " + title).append("\n");
sb.append("totalSize = " + totalSize);
mInfoText.setText(sb.toString());
mInfoText.setTextSize(20);
}
}
break;
case R.id.btn_del:
// 取消和删除下载
mDownloadManager.remove(downloadId);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (null != mReceiver) {
unregisterReceiver(mReceiver);
unregisterReceiver(mApplicationsReceiver);
}
}
}
布局文件
<?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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@id/start_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="@string/start" />
<Button
android:id="@id/btn_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="@string/query" />
<Button
android:id="@id/btn_del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="@string/del" />
</LinearLayout>
<TextView android:id="@id/download_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin"/>
</LinearLayout>
配置文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.me.downloadmanager"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity"
android:label="@string/download">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
它在使用上很方便,帮我们把所有的事情都处理完了,在项目开发使用于可以根据需要来,不是特别需要自己处理的,那么可以直接使用DownloadManager。