<p>main.xml</p><pre class="brush:xml;toolbar:false"><?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Buttonandroid:text="StartDownload"android:id="@+id/button1"
android:layout_width="wrap_content"android:layout_height="wrap_content"
android:onClick="onClick"></Button>
<Buttonandroid:text="ViewDownloads"android:id="@+id/button2"
android:layout_width="wrap_content"android:layout_height="wrap_content"
android:onClick="showDownload"></Button>
<ImageViewandroid:layout_height="wrap_content"android:id="@+id/imageView1"
android:src="@drawable/icon"android:layout_width="wrap_content"></ImageView>
</LinearLayout></pre><pre class="brush:java;toolbar:false">packagede.vogella.android.downloadmanager;
importandroid.app.Activity;
importandroid.app.DownloadManager;
importandroid.app.DownloadManager.Query;
importandroid.app.DownloadManager.Request;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.database.Cursor;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.ImageView;
publicclassDownloadManagerActivityextendsActivity{
privatelongenqueue;
privateDownloadManagerdm;
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiverreceiver=newBroadcastReceiver(){
@Override
publicvoidonReceive(Contextcontext,Intentintent){
Stringaction=intent.getAction();
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
longdownloadId=intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID,0);
Queryquery=newQuery();
query.setFilterById(enqueue);
Cursorc=dm.query(query);
if(c.moveToFirst()){
intcolumnIndex=c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if(DownloadManager.STATUS_SUCCESSFUL==c
.getInt(columnIndex)){
ImageViewview=(ImageView)findViewById(R.id.imageView1);
StringuriString=c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver,newIntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
publicvoidonClick(Viewview){
dm=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Requestrequest=newRequest(
Uri.parse("http://www.vogella.de/img/lars/LarsVogelArticle7.png"));
enqueue=dm.enqueue(request);
}
publicvoidshowDownload(Viewview){
Intenti=newIntent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}</pre><p>permission设置</p>