How to enable HTTP response caching in the DownloadManager?

I want repeat requests for a URL to be served from a local cache, not re-downloaded from the server. I'm using the DownloadManager, hoping it'll be a convenient alternative to HttpURLConnection (saw it recommended), but it does no response caching by default. Here's my test code:

final Context context = getContext();
final DownloadManager manager =
  Android.ensureSystemService( DownloadManager.class, context );
final DownloadManager.Request req =
  new DownloadManager.Request( Uri.parse( BIG_FILE_URL ));
req.setNotificationVisibility( VISIBILITY_HIDDEN ); // hiding from user
context.registerReceiver( new BroadcastReceiver()
{
    public void onReceive( final Context context, final Intent intent )
    {
        context.unregisterReceiver( this ); // one shot for this test
        final long id = intent.getLongExtra( EXTRA_DOWNLOAD_ID, -1L );
        System.err.println( " --- downloaded id=" + id );
        System.err.println( " --- uri=" +
          manager.getUriForDownloadedFile(id) );
    }
}, new IntentFilter( ACTION_DOWNLOAD_COMPLETE ));
manager.enqueue( req );

Running the above test twice, I see two GET requests at the remote server (each with a 200 response) and the following in the local Android log:

20:14:27.574 D/DownloadManager( 1591): [1] Starting
20:14:28.256 D/DownloadManager( 1591): [1] Finished with status SUCCESS
20:14:28.263 W/System.err( 2203):  --- downloaded id=1
20:14:28.269 W/System.err( 2203):  --- uri=content://downloads/my_downloads/1
20:15:13.904 D/DownloadManager( 1591): [2] Starting
20:15:14.517 D/DownloadManager( 1591): [2] Finished with status SUCCESS
20:15:14.537 W/System.err( 2203):  --- downloaded id=2
20:15:14.541 W/System.err( 2203):  --- uri=content://downloads/my_downloads/2

So it downloaded BIG_FILE twice and stored it in two files. Instead I want response caching. Can the DownloadManager do response caching?


PS. It looks like 'no'. So I corrected the recommendation that brought me here (see rev 22).

PPS. To be sure, I tested a standard HttpResponseCache. It has no effect on the DownloadManager , though it does enable caching by default for each HttpURLConnection .


DownloadService downloads to a temporary destination by default. There is no build-in ability to cache requests, however you can query the list of downloads requested before with DownloadManager.query() method.

链接地址: http://www.djcxy.com/p/90818.html

上一篇: Android如何使用Environment.getExternalStorageDirectory()

下一篇: 如何在DownloadManager中启用HTTP响应缓存?