“Good programmers write solid code, while great programmers reuse the code of good programmers”
— W. Jason Gilmore, the author of “Beginning PHP and MySQL”
In Android Platform, it supports some ways to download files from URLs via HttpURLConnection or HttpClient, or DownloadProvider.When you write an android programm with Eclipse, try to import:
import android.provider.Downloads
The Eclipse gives a red error prompting and complains:
The import android.provider.Downloads cannot be resolved
Oops…
The download manager is not part of the public SDK, and there are no relational API description in Android developers Reference.Comment in sources frameworks/base/core/java/android/provider/Downloads.java, says: “For 1.0 the download manager can’t deal with abuse from untrusted apps, so this API is hidden.” Refer to the document description from: packages/providers/DownloadProvider/docs/index.html. we Know that Browser / Gmail / Market / Updater depend on the download manager. Yes, show some screenshots in the market:
We maybe can’t compile with Eclipse, but we can write an Android.mk makefile, use mmm to do it.
DownloadProvider is very easy to use.First, declare permission in AndroidManifest.xml:
<uses-permission
android:name="android.permission.INTERNET"
>
</uses-permission>
<uses-permission
android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"
>
</uses-permission>
And then just need to fill some field values:
ContentValues values = new ContentValues();
String url = "http://blog.lytsing.org/wp-content/uploads/2010/06/android_downloadprovider_market.jpg";
values.put(Downloads.URI, url);
values.put(Downloads.MIMETYPE, "image/jpeg");
values.put(Downloads.FILENAME_HINT, getFullFilename("android_downloadprovider_market.jpg"));
values.put(Downloads.TITLE, "screenshot");
values.put(Downloads.DESCRIPTION, "screenshot file for DownloadProvider Demo");
values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE);
values.put(Downloads.NOTIFICATION_CLASS, "org.lytsting.android.downloads.DownloadReceiver");
values.put(Downloads.NOTIFICATION_PACKAGE, "org.lytsting.android.downloads");
getContentResolver().insert(Downloads.CONTENT_URI, values);
private String getFullFilename(String filename) {
return Environment.getExternalStorageDirectory().toString() + "/download/" + filename);
}
Notes
Downloads.FILENAME_HINT, for a demo, here, I put the file into SD Card, the download directory, without checking any exception.
Downloads.NOTIFICATION_CLASS, you want to write a DownloadReceiver class, which extends BroadcastReceiver, and handle the message Downloads.DOWNLOAD_COMPLETED_ACTION or Downloads.NOTIFICATION_CLICKED_ACTION. like this:
public class DownloadReceiver extends BroadcastReceiver {
static final String TAG = "DownloadReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, intent.getAction());
if (intent.getAction().equals(Downloads.NOTIFICATION_CLICKED_ACTION)) {
Intent activityIntent = new Intent(Intent.ACTION_VIEW);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityIntent.setClass(context, Downloads.class); // Downloads Activity
try {
context.startActivity(activityIntent);
} catch (ActivityNotFoundException ex) {
Log.d(TAG, "no activity for Downloads.NOTIFICATION_CLICKED_ACTION" + ex);
}
} else if (intent.getAction().equals(Downloads.DOWNLOAD_COMPLETED_ACTION)) {
// balabala
}
}
}
By here, we need to modify the AndroidManifest.xml, add:
<receiver
android:name=".DownloadReceiver"
android:permission="android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"
android:exported="true" >
<intent-filter>
<action
android:name="android.intent.action.DOWNLOAD_COMPLETED">
</action>
</intent-filter>
<intent-filter>
<action
android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED">
</action>
<category
android:name="android.intent.category.DEFAULT">
</category>
<data
android:scheme="content">
</data>
</intent-filter>
</receiver>
Maybe, you don’t like show the the Download state in status bar, just change Downloads.VISIBILITY_VISIBLE to Downloads.VISIBILITY_HIDDEN
and even, maybe you would like to show the download progress in the Activity, little case.
Cursor c = getContentResolver().query(
Downloads.CONTENT_URI, new String[] {
Downloads._ID,
Downloads.CURRENT_BYTES,
Downloads.TOTAL_BYTES,
Downloads.STATUS },
" " + Downloads.MIMETYPE + " = 'image/jpeg'", null,
Downloads._ID);
if (c == null) {
return;
}
// Columns match projection in query above
final int idColumn = 0;
final int currentBytesColumn = 1;
final int totalBytesColumn = 2;
final int statusColumn = 3;
c.moveToFirst();
long totalBytes = c.getLong(totalBytesColumn);
long currentBytes = c.getLong(currentBytesColumn);
c.close();
Add a ProgressBar and a Handler to display and refresh the progress, I suppose you should know how to do. You also can write a class extends ContentObserver to observer the download status.
The last step, delete the history data:
getContentResolver().delete(Downloads.CONTENT_URI,
"(" + Downloads.TITLE + " = 'screenshot')", null);
This code snippet should be write into a function in really code.
Read the code packages/apps/Browser for a more complete example.
Update:Since Android 2.2, the Downloads’s api has changed, they put some variables input a sub class which named Impl, so you should check it in the source code.
相关推荐
How to use projector
How to use SFTP (with client validation - public key authentication) The topic How to use SFTP (with client validation - password authentication) discusses the simplest form of client ...
How to Use Objects Code and Concepts Holger Gast
this article introduces how to use awk in linux
How to use the Bayes Net Toolbox? This documentation was last updated on 29 October 2007.
How To Use Adobe Photoshop CS2 <br>Photoshop CS2使用指南 <br>By Daniel Giordan, Doug Nelson <br>Publisher: Sams Publishing <br>Have you ever looked at your color pictures and wished ...
How to use epoll A complete example in C How to use epoll A complete example in C How to use epoll A complete example in C How to use epoll A complete example in C
IBM How to use Seven Keys To Success.
HOW TO USE SDRAM ,sdr sdram的用户手册,比datasheet讲述的详细!
how to use array in jaba
Simple application that shows how to use the Data Control to connect to the Biblio.mdb database and display all authors in the Authors table.
How to Use Objects will help you gain that understanding, so you can write code that works exceptionally well in the real world. Author Holger Gast focuses on the concepts that have repeatedly ...
how to use spring validator
How to use HttpWebRequest and HttpWebResponsein _NET
How to use Android to build Java-based mobile applications for Google phones with a touch screen or keyboard (thanks to Cupcake’s inclusion as of Android 1.5) How to design and architect using Google...
This is a guide to Android application developers on how to use Android Studio 6 to develop their apps. The first part is a guide on how to use the Code Editor in Android 6. The Code Editor provides ...
RK3399的DRM-HOWTO测试 最近在学习与调试RK3399的DRM显示架构,网上有很多例程,其中介绍比较多的是来于David Herrmann’s Github的drm-howto.开源代码 但这些源码下载后执行make编译出来的执行文件只能在PC机上测试...
How to use 256 Color Bitmaps in ImageList (Win32 SDK solution)如何在ImageList中使用256色的位图(Win32 SDK的解决方案)(5KB)
Android How to Program(2nd) 英文无水印pdf 第2版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开