Returning an Input Stream from Parcel File Descriptor using Androids DownloadManager
Asked Answered
L

1

11

I'm trying to download a file using the android DownloadManager, access the file, and write it to a new location (in this example I'm downloading a database which is compiled server side and needs to be wrote to the /database/ directory).

I've been reading up and managed to download the file, and activate the BroadcastReceiver, but at this point I get stuck.

I've returned the ParcelFileDecriptor file but I'm having trouble converting it to a stream in any way. I can't decide if the ParcelFileDecriptor.AutoCloseInputStream is a red herring or not, but I'm pretty sure the ParcelFileDecriptor has relativity to a stream, but I'm really struggling to work it out. Any help would be much appreciated.

Lemberg answered 3/11, 2011 at 20:16 Comment(0)
L
24

Assuming you've started the download already and set up the Broadcast Reciver, the following code will do the job...

            ParcelFileDescriptor file = dMgr.openDownloadedFile(downloadId);
            File dbFile = getDatabasePath(Roads.DATABASE_NAME);
            
            InputStream fileStream = new FileInputStream(file.getFileDescriptor());
            OutputStream newDatabase = new FileOutputStream(dbFile);
            
            byte[] buffer = new byte[1024];
            int length;
            
            while((length = fileStream.read(buffer)) > 0)
            {
                newDatabase.write(buffer, 0, length);
            }
            
            newDatabase.flush();
            fileStream.close();
            newDatabase.close();

If you're looking for more information on overwriting a database with your own check this link (Also where most of the above info has come from):

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Lemberg answered 4/11, 2011 at 8:11 Comment(3)
You may consider using com.google.common.io.ByteStreams.copy(in,out)Oniskey
Hey orian, thanks for the input. I've not actually done any android development for many years now. If using bytestreams copy is now the more preferred way of moving a stream (which makes sense it would be), please feel free to update/edit the post respectively. =)Lemberg
It's a library provided by Google, I find it pretty useful. When developing complex app for Android I depend on it anyway so mentioning it for others may make their life easier.Oniskey

© 2022 - 2024 — McMap. All rights reserved.