简体   繁体   中英

DownloadManager a file from assets folder? (Android Studio)

I'm making a soundboard application and I want users to be able to download files from assets so they can set it as a notification sound/ringtone. I'm getting an error saying I can only download files from HTTP/HTTPS. Is there a way around this?

DownloadManager.Request request = new DownloadManager.Request(Uri.parse("content://com.thingy.app/" + filename));
request.setDescription("Soundbite from ");
request.setTitle(filename);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

Use AssetManager and its open() method to get an InputStream on the asset content. Then, copy the bytes to a FileOutputStream on the file that you want to create.

I use this to copy a SQLite database out of the Assets folder to internal storage:

        //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_IN);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM