将媒体文件保存到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, 0, 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");
}
}

以下是在"活动"中如何调用该方法。

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);
}
}
}

非常感谢这个答案,它帮助我如此简洁地解决了问题。

相关内容

最新更新