本文共 2890 字,大约阅读时间需要 9 分钟。
package com.lan.www; import java.io.File; import android.app.Activity; import android.app.DownloadManager; 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.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class DowloadManagerActivity extends Activity { /** Called when the activity is first created. */ TextView tv; Button btDel; DownloadManager dm; long downloadId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tv); btDel = (Button) findViewById(R.id.button2); btDel.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub //这个方法是变参,可以有多个参数 dm.remove(downloadId);//删除 } }); //得到系统的DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); public void doClick(View v) { DownloadManager.Request dmReq = //转化成Uri的格式 new DownloadManager.Request(Uri.parse("http://127.0.0.1:8080/tomServer/file/db.zip")); dmReq.setTitle("db.zip");//设置标题 dmReq.setDescription(" downloading!");//设置工作状态
//禁止发出通知,既后台下载 down.setShowRunningNotification(false);
//不显示下载界面 down.setVisibleInDownloadsUi(false);
//设置下载方式,(这里设置的是3G和WIFI)
dmReq.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
//dmReqi.setDestinationUri整合了下面两种方法
//dmReq.setDestinationInExternalFilesDir(context, dirType, subPath);//设置下载后文件存放的位置 // dmReq.setDestinationInExternalPublicDir(dirType, subPath); //公共路径
dmReqi.setDestinationUri( Uri.fromFile(new File( //设置公共路径 Environment.getExternalStoragePublicDirectory( //设置文件 Environment.DIRECTORY_DOWNLOADS ).getAbsoluteFile() +".zip") )); //放到一个队列里,队列里系统里会给一个Id; downloadId = dm.enqueue(dmReq); //设置过虑器,用系统给的就可以,可以添加多外过虑器,添加多个用add IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); //注册广播 registerReceiver(thereReceiver, filter); tv.setText(tv.getText().toString()+" download started : id = "+downloadId); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); //解除注册广播 unregisterReceiver(thereReceiver); } public BroadcastReceiver thereReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle extras = intent.getExtras(); long doneId = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID); tv.setText(tv.getText().toString()+" \nfinish "+doneId); } }; }
android设置配置文件
添加下面两条权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/>
2.2以前版本的可能还要添加DownloadManager的使用权限,转载地址:http://kcbsi.baihongyu.com/