안드로이드 웹뷰 캐쉬를 내부메모리가 아닌 외부로 쓰게 할려고 방법을 찾다가
해외 사이트에서 방법을 찾았는데 까먹을까봐 여기 기록해둠
package com.devahead.androidwebviewcacheonsd;
import java.io.File;
import android.app.Application;
import android.os.Environment;
public class ApplicationExt extends Application
{
// NOTE: the content of this path will be deleted
// when the application is uninstalled (Android 2.2 and higher)
protected File extStorageAppBasePath;
protected File extStorageAppCachePath;
@Override
public void onCreate()
{
super.onCreate();
// Check if the external storage is writeable
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
// Retrieve the base path for the application in the external storage
File externalStorageDir = Environment.getExternalStorageDirectory();
if (externalStorageDir != null)
{
// {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd
extStorageAppBasePath = new File(externalStorageDir.getAbsolutePath() +
File.separator + "Android" + File.separator + "data" +
File.separator + getPackageName());
}
if (extStorageAppBasePath != null)
{
// {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd/cache
extStorageAppCachePath = new File(extStorageAppBasePath.getAbsolutePath() +
File.separator + "cache");
boolean isCachePathAvailable = true;
if (!extStorageAppCachePath.exists())
{
// Create the cache path on the external storage
isCachePathAvailable = extStorageAppCachePath.mkdirs();
}
if (!isCachePathAvailable)
{
// Unable to create the cache path
extStorageAppCachePath = null;
}
}
}
}
@Override
public File getCacheDir()
{
// NOTE: this method is used in Android 2.2 and higher
if (extStorageAppCachePath != null)
{
// Use the external storage for the cache
return extStorageAppCachePath;
}
else
{
// /data/data/com.devahead.androidwebviewcacheonsd/cache
return super.getCacheDir();
}
}
}
이런 class를 하나 만들어 추가해준다.
웹뷰를 사용하는 액티비티 클래스에서
@Override
public File getCacheDir()
{
// NOTE: this method is used in Android 2.1
return getApplicationContext().getCacheDir();
}
함수를 하나 추가해 준다
그리고 Androidmenifest.xml에다가 아래와 같이 추가해준다.
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:name="com.devahead.androidwebviewcacheonsd.ApplicationExt"> <activity android:name=".MainActivity" android:label="@string/app_name">
이 코드를 쓰면 웹브라우징 도중에 SD메모리가 빠진다던지 캐시클리어 명령이 안먹는다던지 뭐 자잘하게 문제가 생길 수 있다
그건 당신이 알아서 예외 처리 해야 한다고 함.
출처: http://www.devahead.com/blog/2012/01/saving-the-android-webview-cache-on-the-sd-card/
답글 남기기