将媒体文件保存到 SharedPreferences/Files Android

问题描述

我想为我的 Android 应用程序中的自定义字体下载并保存 .ttf 或 .otf 文件。是否可以将其保存在 SharedPreferences 中?

不是文件路径,而是文件本身。

编辑:我要求使用此方法是因为 OutputStream 一直给我“权限被拒绝”错误。我愿意接受任何有助于我将下载的 .ttf 文件保存到文件并稍后检索的建议。

谢谢!

编辑:我在下面添加了输入输出代码,它在运行时给了我一个权限被拒绝的错误。如果我能在这里解决一些问题,请告诉我。

class DownloadFileFromURL extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        URL url = new URL(f_url[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int lenghtOfFile = connection.getContentLength();

        InputStream input = new BufferedInputStream(url.openStream(),8192);
        File file = new File(Environment.getExternalStorageDirectory(),"downloadedFont.ttf");
        OutputStream output = new FileOutputStream(file);

        byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                output.write(data,count);
            }
            output.flush();
            output.close();
            input.close();

    } catch (Exception e) {
        Log.e("Error",e.getMessage() + e.getCause());
    }
    return null;
}

@Override
protected void onPostExecute(String file_url) {
    loadFont();
}

public static void loadFont() {
    File file = new File(Environment.getExternalStorageDirectory().toString() + "/downloadedFont.ttf");
    if(file.exists()){
        Log.d("LOAD","File exists");
        Typeface typeFace = Typeface.createFromFile(file);
        ContextHelper.setDownloadedFontType(typeFace);
    }
    else {
        download();
    }
}

public static void download() {
    Log.d("DOWNLOAD","In the download.");
    new DownloadFileFromURL().execute("https://www.dropBox.com/s/y980vywiprd8eci/riesling.ttf?raw=1");
}
}

以下是在Activity中调用方法的方式。

DownloadFileFromURL.loadFont();

解决方法

我认为这是可能的。 下载文件首先转换为Base64编码 将该编码数据保存在 Share Pref 中。 当你获取它解码并再次创建一个文件并使用它。

,

经过多次搜索,我在StackOverflow的深处找到了答案:

public static void downloadFont(String url,Context context) {
    DownloadManager.Request request1 = new DownloadManager.Request(Uri.parse(url));
    request1.setDescription("Sample Font File");
    request1.setTitle("Font.ttf");
    request1.setVisibleInDownloadsUi(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request1.allowScanningByMediaScanner();
        request1.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    }
    request1.setDestinationInExternalFilesDir(context,"/File","Font.ttf");

    DownloadManager manager1 = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Objects.requireNonNull(manager1).enqueue(request1);

    if (DownloadManager.STATUS_SUCCESSFUL == 8) {
        File file = new File(context.getExternalFilesDir("/File").toString() + "/Font.ttf");
        if(file.exists()){
            Typeface typeFace = Typeface.createFromFile(file);
        }
    }
}

非常感谢 this answer 帮助我如此简洁地解决了我的问题。