简体   繁体   English

DownloadManager从资产文件夹中下载文件? (Android Studio)

[英]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. 我收到一条错误消息,说我只能从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. 使用AssetManager 及其open()方法获取资产内容上的InputStream Then, copy the bytes to a FileOutputStream on the file that you want to create. 然后,将字节复制到要创建的文件上的FileOutputStream

I use this to copy a SQLite database out of the Assets folder to internal storage: 我使用它来将SQLite数据库从Assets文件夹复制到内部存储中:

        //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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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