「Android/DiskLruCache」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→準備) |
|||
| 行22: | 行22: | ||
[[android/hash]] [ショートカット] | [[android/hash]] [ショートカット] | ||
| − | |||
==使い方サンプル== | ==使い方サンプル== | ||
2018年11月29日 (木) 16:00時点における版
準備
以下追加
- app/build.gradle
dependencies {
implementation 'com.jakewharton:disklrucache:2.0.2'
}
公式?
https://github.com/JakeWharton/DiskLruCache
準備
key部分のhogehogeはmd5やsha1などでhash化して使うと良い。
android/hash [ショートカット]
使い方サンプル
String UNIQUE_CACHE_NAME = "hogehoge-cache";
int VALUE_COUNT = 1;
int DISK_CACHE_INDEX = 0;
String cachePath = context.getCacheDir().getPath()
File cacheDirectory = new File(cachePath + File.separator + UNIQUE_CACHE_NAME);
long diskCacheSizeBytes = 30 * 1024 * 1024; // 30 MB
// 初期化
DiskLruCache sDiskLruCache = DiskLruCache.open(
cacheDirectory,
APP_VERSION,
VALUE_COUNT,
diskCacheSizeBytes);
// 取得
DiskLruCache.Snapshot snapshot = sDiskLruCache.get("hogehoge");
final InputStream in = snapshot.getInputStream(DISK_CACHE_INDEX);
// 更新
DiskLruCache.Editor editor = sDiskLruCache.edit("hogehoge");
final OutputStream outputStream =
new BufferedOutputStream(editor.newOutputStream(DISK_CACHE_INDEX));
Streams.copyContent(content, outputStream);
outputStream.flush();
outputStream.close();
sDiskLruCache.flush();
editor.commit();
// 削除
sDiskLruCache.delete()
mopubに上記コードの詳細がある https://github.com/mopub/mopub-android-sdk/blob/master/mopub-sdk/mopub-sdk-base/src/main/java/com/mopub/common/CacheService.java
downloadしたものをcacheする
URL u = new URL(mUrl);
InputStream is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
int size = huc.getContentLength();
if (huc != null) {
InputStream inputStream = new BufferedInputStream(huc.getInputStream());
boolean diskPutResult = CacheService.putToDiskCache(sha1(mUrl), inputStream);
}
<pre>
==permission追加==
保存場所はconstructのparamで指定するので、適宜記述となる。
mopubではcontext.getCacheDir()を使っておりAndroidManifestのpermissionは不要だった。
https://github.com/mopub/mopub-android-sdk/blob/master/mopub-sdk/mopub-sdk-base/src/main/java/com/mopub/common/CacheService.java
context.getExternalCacheDir()をもし使う場合はKitKatからpermission不要となったが、それ以前では必要なので以下のように追加する
<pre>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
http://wada811.blogspot.com/2014/09/storage-access-and-permission-in-android.html
