java - Save Media Files to SharedPreferences/Files Android
问题描述
I want to download and save a .ttf or .otf file for custom fonts in my Android App. Is it possible to save this in SharedPreferences?
Not the file path, but the file itself.
Edit: I asked for this method because OutputStream kept giving me 'Permission Denied' error. I am open to any suggestion that would help me save the downloaded .ttf to files and retrieve it later.
Thanks!
Edit: I have added the Input Output Stream code below, which gives me a permission denied error when running. Please let me know if I can fix something here.
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");
}
}
The following is how the method is called in an Activity.
DownloadFileFromURL.loadFont();
解决方案
I thought that's possible. Download File first convert to Base64 Encoding save that encoding data in Share Pref. When you Fetch it Decoding and create a file again and use it.
推荐阅读
- java - Android中半透明导航栏的问题
- c# - 在 asp net mvc 中添加搜索栏
- mongodb - MongoInvalidArgumentError:更新文档需要原子运算符
- amazon-web-services - Aws Api 网关 - ERR_ABORTED 403 - 未加载 JS 和 CSS
- flutter - 如何使用字符串或变量在flutter中使用OrderByChild从firebase实时数据库中获取数据
- excel - 准确获取 MAXIF 结果的单元格地址
- python - 用python中数据框的值替换字符串的一部分
- c# - 如何在 SwashBuckle.ASP.NET Core 库中显示外部库程序集提供的端点的 XML 注释
- .htaccess - .htaccess 通过发送 dummy user:pass in url 来强制密码不断循环
- python - 如何解决 io.UnsupportedOperation: can't do nonzero end-relative seeks?