java">
/** * 本應用數據清除管理器 */
public class DataCleanManager {
/** * 清除本應用內部緩存(/data/data/com.xxx.xxx/cache) * * @param context */
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
/** * 清除本應用所有資料庫(/data/data/com.xxx.xxx/databases) * * @param context */
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/com.example.orderfood"));
}
/**
* * 清除本應用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param
* context
*/
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/com.example.orderfood/shared_prefs"));
}
/** * 按名字清除本應用資料庫 * * @param context * @param dbName */
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/** * 清除/data/data/com.xxx.xxx/files下的內容 * * @param context */
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的內容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param
* context
*/
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/** * 清除自定義路徑下的文件,使用需小心,請不要誤刪。而且只支持目錄下的文件刪除 * * @param filePath */
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/** * 清除本應用所有的數據 * * @param context * @param filepath */
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/** * 刪除方法 這里只會刪除某個文件夾下的文件,如果傳入的directory是個文件,將不做處理 * * @param directory */
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}
}
}
B. android 數據存儲的幾種方式
總體的來講,數據存儲方式有三種:一個是文件,一個是資料庫,另一個則是網路。其中文件和資料庫可能用的稍多一些,文件用起來較為方便,程序可以自己定義格式;資料庫用起稍煩鎖一些,但它有它的優點,比如在海量數據時性能優越,有查詢功能,可以加密,可以加鎖,可以跨應用,跨平台等等;網路,則用於比較重要的事情,比如科研,勘探,航空等實時採集到的數據需要馬上通過網路傳輸到數據處理中心進行存儲並進行處理。 對於Android平台來講,它的存儲方式也不外乎這幾種,按方式總體來分,也是文件,資料庫和網路。但從開發者的角度來講它可以分為以下五種方式: 1.SharedPreferences共享偏好 2.Internal Storage內部存儲空間 3.External Storage外部存儲空間 4.SQLite Database資料庫 5.Internet網路 這幾種方式各自有各自的優點和缺點,要根據不同的實際情況來選擇,而無法給出統一的標准。下面就各種方式談談它們的優缺點,以及最合適的使用情況: 1.Shared Preferences共享偏好 SharedPreferences是用來存儲一些Key/Value類似的成對的基本數據類型,注意,它只能存儲基本數據類型,也即int, long, boolean, String, float。事實上它完全相當於一個HashMap,唯一不同的就是HashMap中的Value可以是任何對象,而SharedPreferences中的值只能存儲基本數據類型(primitive types)。 對於它的使用方法,可以參考Android Developer Guide,這里不重復。 如此來看,最適合SharedPreferences的地方就是保存配置信息,因為很多配置信息都是Key/Value。事實上,在Android當中SharedPreferences使用最多的地方也是用來保存配置(Settings)信息,系統中的Settings中這樣,各個應用中的Settings也是這樣。並且,Android中為了方便的使用SharedPreferences保存配置信息,它來專門有PreferenceActivity用來封裝。也就是說如果你想在應用程序中創建配置(Settings),你可以直接使用PreferenceActivity和一些相關的專門為Preference封裝的組件,而不用再直接去創建,讀取和保存SharedPreference,Framework中的這些組件會為你做這些事。 再談談一些使用SharedPreference時的技巧,它只能保存基本數據類型,但假如我想保存一個數組,怎麼辦?可以把數據進行處理,把它轉化成一個String,取出的時候再還原就好了;再如,如想保存一個對象,怎麼辦,同樣,可以把對象序列化成為字元序列,或轉成String(Object.toString()),或是把它的HashCode(Object.hashCode())當成Value保存進去。 總之,SharedPreferences使用起來十分的方便,可以靈活應用,因為它簡單方便,所以能用它就盡量不要用文件或是資料庫。 1.Internal Storage內部存儲空間 所謂的內部存儲與外部存儲,是指是否是手機內置。手機內置的存儲空間,稱為內部存儲,它是手機一旦出廠就無法改變,它也是手機的硬體指標之一,通常來講手機內置存儲空間越大意味著手機價格會越貴(很多地方把它稱為手機內存,但我們做軟體的知道,這並不準確,內存是指手機運行時存儲程序,數據和指令的地方;這里應該是手機內部存儲的簡稱為內存,而並非嚴格意義上的內存)。 內部存儲空間十分有限,因而顯得可貴,所以我們要盡可能避免使用;另外,它也是系統本身和系統應用程序主要的數據存儲所在地,一旦內部存儲空間耗盡,手機也就無法使用了。所以對於內部存儲空間,我們要盡量避免使用。上面所談到的Shared Preferences和下面要談到的SQLite資料庫也都是存儲在內部存儲空間上的。 Android本身來講是一個Linux操作系統,所以它的內部存儲空間,對於應用程序和用戶來講就是「/data/data"目錄。它與其他的(外部的存儲)相比有著比較穩定,存儲方便,操作簡單,更加安全(因為可以控制訪問許可權)等優點。而它唯一的缺點就是它比較有限,比較可貴。 雖然,可以非常容易的知道程序本身的數據所在路徑,所有的應用程序的數據路徑都是「/data/data/app-package-name/」,所有的程序用到的數據,比如libs庫,SharedPreferences都是存放在這個路徑下面。但我們在使用的時候最好不要,或是千萬不要直接引用這個路徑。 使用內部存儲主要有二個方式,一個是文件操作,一個是文件夾操作。無論哪種方式,Context中都提供了相應的函數來支持,使用Context不但操作簡單方便,最重要的是Context會幫助我們管理這些文件,也可以方便幫助我們控制文件的訪問許可權。先來系統的說下Context中關於文件和文件夾操作的函數有哪些。 a. 創建一個文件,並打開成一個文件輸出流,需要提供一個String,作為文件名 1.FileOutputStream output = Context.openOutputFile(filename, Context.MODE_PRIVATE); 2.output.write(data);// use output to write whatever you like 3.output.close(); 1.FileOutputStream output = Context.openOutputFile(filename, Context.MODE_PRIVATE); output.write(data);// use output to write whatever you like output.close(); b. 同樣,想打開一個文件作為輸入的話,也是只需要提供文件名 1.FileInputStream input = Context.openInputFile(filename); 2.input.read(); 3.input.close(); 1.FileInputStream input = Context.openInputFile(filename); input.read(); input.close(); c. 列出所有的已創建的文件 1.String[] files = Context.fileList(); 2.for (String file : files) { 3. Log.e(TAG, "file is " + file); 4.} 1.String[] files = Context.fileList(); for (String file : files) { Log.e(TAG, "file is " + file); } d. 刪除文件,能創建就要能夠刪除,當然也會提供了刪除文件的介面,它也非常簡單,只需要提供文件名 1.if (Context.deleteFile(filename)) { 2. Log.e(TAG, "delete file " + filename + " sucessfully「); 3.} else { 4. Log.e(TAG, "failed to delete file " + filename); 5.} 1.if (Context.deleteFile(filename)) { Log.e(TAG, "delete file " + filename + " sucessfully「); } else { Log.e(TAG, "failed to delete file " + filename); } e. 獲取文件已創建文件的路徑,它返回一個文件對象用於操作路徑 1.File fileDir = Context.getFileDir(); 2.Log.e(TAG, "fileDir " + fileDir.getAbsolutePath(); 1.File fileDir = Context.getFileDir(); Log.e(TAG, "fileDir " + fileDir.getAbsolutePath(); f. 創建一個目錄,需要傳入目錄名稱,它返回 一個文件對象用到操作路徑 1.File workDir = Context.getDir(dirName, Context.MODE_PRIVATE); 2.Log.e(TAG, "workdir " + workDir.getAbsolutePath(); 1.File workDir = Context.getDir(dirName, Context.MODE_PRIVATE); Log.e(TAG, "workdir " + workDir.getAbsolutePath(); g. 以File對象方式查看所創建文件,需要傳入文件名,會返迴文件對象 1.File store = Context.openFileStreamPath(filename); 2.Log.e(TAG, "store " + store.length()); 1.File store = Context.openFileStreamPath(filename); Log.e(TAG, "store " + store.length()); h. 獲取Cache路徑,無需要傳入參數,返迴文件對象 1.File cachedir = Context.getCacheDir(); 2.Log.e(TAG, "cachedir " + cacheDir.getAbsolutePath()); 1.File cachedir = Context.getCacheDir(); Log.e(TAG, "cachedir " + cacheDir.getAbsolutePath()); 總結一下文件相關操作,可以得出以下三個特點: 1. 文件操作只需要向函數提供文件名,所以程序自己只需要維護文件名即可; 2. 不用自己去創建文件對象和輸入、輸出流,提供文件名就可以返回File對象或輸入輸出流 3. 對於路徑操作返回的都是文件對象。 如前所述,內部存儲空間有限,可貴,安全,穩定,所以應該用來保存比較重要的數據,比如用戶信息資料,口令秘碼等不需要與其他應用程序共享的數據。也可以用來創建臨時文件,但一定要注意及時刪除。另外,對於內部存儲還有一個非常重要的特點,那就是在應用程序被卸載時,應用程序在內部存儲空間的文件數據將全部被刪除。系統這樣做的原因很簡單,就是因為內部存儲很有限,它必須保證它的可用性,因為一旦添滿,系統將無法再正常工作。 1.External Storage外部存儲空間 再來談談手機外部存儲空間,與內部存儲空間相對,外部存儲空間是指手機出廠的時候不存在,用戶在使用時候可以自由添加的外部存儲介質比如TS卡,SD卡等快閃記憶體儲介質。這些快閃記憶體介質由最初的空間小價格貴,到現在的大容量價格便宜,所以幾乎每個支持外部存儲的手機上面都有大容量(大於等於2G)的快閃記憶體卡。 Android也是不例外,它完全支持外部存儲介質。其實更確切的說,它是要依賴於外部存儲卡的,因為對於Android系統,如果沒有外部存儲卡,很多的系統應用無法使用,比如多媒體相關的應用程序無法使用。雖然Android很依賴,但是外部存儲卡也有它自身的特點,它最大的優點就是存儲空間大,基本上你可無限制的使用,也不怎麼擔心去清除數據。就目前來看,很多程序都在使用外部存儲卡,但很少有程序去主動清理數據,所以無論你的SD卡有多大,它的可用空間卻越來越少。與內部存儲不同的是,當程序卸載時,它在外部存儲所創建的文件數據是不會被清除的。所以清理外部存儲空間的責任丟給了用戶自己,每隔一段時間就去查看下SD卡,發現無用數據立馬刪除。外部存儲的缺點就是不是很穩定,對於Android手機來講可以說,很不穩定,本身快閃記憶體介質就容易出問題,SD卡處於不能正常使用的狀態十分多。 先來說說外部存儲相關的使用方法和API: a. Check media availability檢查介質的可用性 如前所述,外部存儲介質的穩定性十分的差,所以在使用之前一定要先檢查它的可用性,如果可用再去用 view plain to clipboardprint? 1.final String state = Environment.getExternalStorageState(); 2.if (state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_READ_ONLY)) {// sd card is ready to us } view plain to clipboardprint? 1.final String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_READ_ONLY)) {// sd card is ready to us } final String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_READ_ONLY)) {// sd card is ready to us } b. Get the directory獲取外部存儲卡的路徑 事實上,外部存儲卡的路徑是「/mnt/sdcard",所以你直接這樣寫去訪問也能訪問的到。鑒於可讀性和可移植性的考慮,建議這樣寫: view plain to clipboardprint? 1.File sdcardDir = Environment.getExternalStorageDirectory(); view plain to clipboardprint? 1.File sdcardDir = Environment.getExternalStorageDirectory(); File sdcardDir = Environment.getExternalStorageDirectory(); c. For API 8 or greater, there are some other useful APIs helping to manager files and directories. 如果你使用API 8(Android 2.2)或者更高,那麼SDK中又多了幾個操作外部存儲文件和路徑的介面,文檔中也建議開始者更加規范的使用SD卡。比如,創建相應的目錄去存儲相應的數據,Music,Picture,Video等。應用程序目錄也變成了"/Android/data/package-name/data"。具體的使用可以參考文檔,這里不重復。當然,就像編程規范一樣,這里只是規范,你完全可以不遵守它,但出於可讀性和可移植性,還是建議按照文檔建議的去做。 下面總結一下使用時應該注意的一些和外部存儲的特點: a. 外部存儲卡不是隨時想用就能夠用的,所以一定要記得在使用之前檢查它的可用性 b. 存儲在外部存儲卡上的數據是所有應用程序都可見,用戶也可見(使用FileManager),所以安全性不是很好,雖然文檔聲稱可以在外部存儲卡上寫程序私有數據,但貌似沒用,用FileManager仍然可以刪除或編輯文件(Market上面的FileManager功能都十分的強大,能讓用戶看到SD卡中的所有文件,和操作能看到的文件)。 c. Android手機支持把外部存儲卡Mount至PC做為U盤,當連接數據線時,這時SD卡變成了U盤連接到了另外的操作系統中。什麼意思,就是在Android當中雖然有的文件屬性(隱藏,私有等),到了PC上就不一定管用了,用戶在PC上可以隨意操作文件(這就是第二點中所提及的)。 d. 如果使用外部存儲卡保存數據,一定要額外做好異常處理:外部存儲卡不可用時把數據存入哪裡;可用的時候再怎麼同步數據(這是比較頭疼的地方,可行的做法就是當SD卡不可用時不準用戶寫數據,但這用戶體驗又不是很好,但如你所知,很多應用都這么干);你的數據被破壞了。當然常見的異常也要考慮,比如空間滿了,無法寫入,磁碟壞道等。 1.SQLite Database資料庫 Android對資料庫的支持很好,它本身集成了SQLite資料庫,每個應用都可以方便的使用它,或者更確切的說,Android完全依賴於SQLite資料庫,它所有的系統數據和用到的結構化數據都存儲在資料庫中。 它具有以下優點: a. 效率出眾,這是無可否認的 b. 十分適合存儲結構化數據 c. 方便在不同的Activity,甚至不同的應用之間傳遞數據 先前有一篇文章講到了不同Activity和不同應用之間傳遞數據的麻煩,特別是對於大型數據結構,因為Activity雖是Java對象,但去無法像使用其他類對象那樣去創建一個實例然後使用它,更無法給Activity加上Setters和Getters(雖然這樣做了沒有編譯錯誤)。比較好的解決方案就是把結構化數據寫入資料庫,然後在不同的Activity之間傳遞它們的Uri。 d. 由專門的ContentProvider來幫忙管理和維護資料庫 e. 可以方便的設置訪問許可權,私有還是都可見 f. 操作方便,使用標準的CRUDE語句,ContentResolver.query(), update(), delete() insert(),詳見ContentResolver g. 良好的可移植性和通用性,用標準的SQL語句就能實現CRUDE 對於它的使用方法可以去參考文檔,這里也說不清楚。 1.Internet網路 網路是比較不靠譜的一個,因為移動終端的網路穩定性,以及所產生的流量讓人傷不起,用戶更傷不起。但若是對於非常重要的實時數據,或是需要發送給遠端伺服器處理的,也可以考慮使用網路實時發送。這已經有先例了,Apple和Google就是這樣,iPhone設備和Android設備都會在用戶不知情的情況 下收集用戶的信息,然後又在用戶不知情的情況 下發送到Apple和Google的伺服器上,也就是所謂的「跟蹤門」。除此之外,智能手機(特別是Android和火熱的iPhone)上面的應用程序都會偷偷的在後台運行,收集用戶數據,然後再偷偷的發伺服器,直接傷害是用戶流量,請看先前的文章。 對比這幾種方式,可以總結下: 1. 簡單數據和配置信息,SharedPreference是首選; 2. 如果SharedPreferences不夠用,那麼就創建一個資料庫 3. 結構化數據,一定要創建資料庫,雖然這稍顯煩鎖,但是好處無窮 4. 文件就是用來存儲文件(也即非配置信息或結構化數據),如文本文件,二進制文件,PC文件,多媒體文件,下載的文件等等。 5. 盡量不要創建文件 6. 如果創建文件,如果是私密文件或是重要文件,就存儲在內部存儲,否則放到外部存儲 7. 不要收集用戶數據,更不要發到網路上,雖然你們也有很多無奈。用戶也無奈,也無辜,但更無助 平台為開發者准備了這么多的方式固然是一件好事,但我們要認清每一種的優點和缺點,根據實際情況選擇最合適的。還有一個原則就是最簡單原則,也就是說能用簡單的方式處理,就不要用復雜的方式。
C. android cachemanager用什麼類替代
Android在framework中解析http信息,Request.java的函數readResponse通過AndroidHttpClientConnection.java的函數parseResponseHeader解析response的header部分。
存儲數據使用的是org.apache.http.util.CharArrayBuffer中的CharArrayBuffer。使用SessionInputBuffer的readline來讀取一行,進行解析。
我們主要關心的是Location部分,因為重定向主要是通過Location的值重新去請求url。Android中也是這么做的,不會去html的body中解析標記A的herf。
D. android開發文件緩存在什麼位置,可以在應用程序中清除。
android開發文件緩存的默認位置一般是在android/data目錄下,比如kindle(1st)是在/mnt/sdcard/Android/data目錄下,魅族是在/sdcard/Android/data目錄下。
將緩存在應用程序中清除:
打開關閉使用緩存,一共有五個種類
//優先使用緩存:
WebView.getSettings().setCacheMod
(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//不使用緩存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
在退出應用的時候加上如下代碼
File file = CacheManager.getCacheFileBaseDir();
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete(); }
file.delete(); }
context.deleteDatabase("WebView.db");
context.deleteDatabase("WebViewCache.db");
以上方法均可實現。
E. 如何將WebView的緩存設置到緩存至SD卡
樓主可以參考下面這個文件。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.devahead.androidwebviewcacheonsd"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="Second activity"/>
</application>
</manifest>
Here we have the permissions to write to the SD (the external storage) and access the web. We also have a custom Application class extension called ApplicationExt and a couple of activities, MainActivity and SecondActivity.
The ApplicationExt class is where most of the things are done to have the cache on the SD:
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();
}
}
}
In the onCreate method we start by checking if the external storage is actually mounted and we can write on it, then we build the base path of the app on the external storage. This path is {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd becausecom.devahead.androidwebviewcacheonsd is the package declared in the manifest file and using this path structure makes sure that the entire path and all its content will be automatically deleted by Android 2.2 and higher in case the app is uninstalled avoiding to have garbage files on the SD. Note that this works only in Android 2.2 and higher, while in Android 2.1 the path will not be deleted by the OS so you』ll have to deal with it on your own. The full path for the cache files will be{SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd/cache, so the base path plus thecache directory. We must also make sure that the path is actually available before using it, so we create all the directories with the mkdirs method in case they don』t already exist.
Now that we have the cache path on the SD, we』re ready to use it and all we have to do is override the getCacheDir method inside our ApplicationExt class. This method is invoked by the cache manager when the application is started so basically we』re saying that the cache will be stored on the SD if it』s available and writeable, while we use the default path in case we』re allowed to use only the internal memory. Android stores all the cache data for our app in the /data/data/com.devahead.androidwebviewcacheonsd/cache directory by default on the internal memory.
We』re done with the implementation for Android 2.2 and higher, but what about Android 2.1? For that version of the OS the cache manager doesn』t use the getCacheDir method of theApplication context, but it uses the one of the Activity context instead. So to make our solution work also with Android 2.1, we must override the getCacheDir method inside our activities.
To immediately understand how it works with Android 2.1, let』s take a look at the activities of the example application. We start with the MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:id="@+id/startSecondActivityBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Start second activity"/>
<WebView android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
There』s simply a button to start the SecondActivity and a WebView to test our solution. The code for MainActivity looks like this:
package com.devahead.androidwebviewcacheonsd;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener
{
protected WebView webView;
protected Button startSecondActivityBtn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = ((WebView)findViewById(R.id.webView));
startSecondActivityBtn = ((Button)findViewById(R.id.startSecondActivityBtn));
// Set the listener
startSecondActivityBtn.setOnClickListener(this);
// Initialize the WebView
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
// Load the URLs inside the WebView, not in the external web browser
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");
}
@Override
protected void onDestroy()
{
// Clear the cache (this clears the WebViews cache for the entire application)
webView.clearCache(true);
super.onDestroy();
}
@Override
public File getCacheDir()
{
// NOTE: this method is used in Android 2.1
return getApplicationContext().getCacheDir();
}
@Override
public void onClick(View v)
{
if (v == startSecondActivityBtn)
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
}
As you can see, the getCacheDir method inside the activity simply calls the same method in the Application context, that means that the ApplicationExt method is called. We』ll have to do this for every activity in the app to make sure the cache path is redirected correctly in Android 2.1, but actually in my tests I found that it looks like the cache manager calls thegetCacheDir method inside the first activity that initializes a WebView (if MainActivitydoesn』t use a WebView, but only SecondActivity does, then the getCacheDir method ofSecondActivity will be called by the cache manager and not the one of MainActivity), anyway I think it』s a good idea to make sure the cache directory is consistent across all the activities of the application.
In MainActivity there』s a button that starts SecondActivity. This is just another activity with a WebView that I used to test the calls to the getCacheDir method in Android 2.1 and see what happens if there』s a WebView also in MainActivity or not. This is the layout ofSecondActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<WebView android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
And this is its source code:
package com.devahead.androidwebviewcacheonsd;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class SecondActivity extends Activity
{
protected WebView webView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
webView = ((WebView)findViewById(R.id.webView));
// Initialize the WebView
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
// Load the URLs inside the WebView, not in the external web browser
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");
}
@Override
public File getCacheDir()
{
// NOTE: this method is used in Android 2.1
return getApplicationContext().getCacheDir();
}
}
F. android 清除緩存功能如何實現
Android清除本地數據緩存代碼:
/* * 文 件 名: DataCleanManager.java * 描 述: 主要功能有清除內/外緩存,清除資料庫,清除sharedPreference,清除files和清除自定義目錄 */
import java.io.File;
import android.content.Context;
import android.os.Environment;
/** * 本應用數據清除管理器 */
public class DataCleanManager {
/** * 清除本應用內部緩存(/data/data/com.xxx.xxx/cache) * * @param context */
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
/** * 清除本應用所有資料庫(/data/data/com.xxx.xxx/databases) * * @param context */
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/databases"));
}
/**
* * 清除本應用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param
* context
*/
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/shared_prefs"));
}
/** * 按名字清除本應用資料庫 * * @param context * @param dbName */
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/** * 清除/data/data/com.xxx.xxx/files下的內容 * * @param context */
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的內容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param
* context
*/
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/** * 清除自定義路徑下的文件,使用需小心,請不要誤刪。而且只支持目錄下的文件刪除 * * @param filePath */
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/** * 清除本應用所有的數據 * * @param context * @param filepath */
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/** * 刪除方法 這里只會刪除某個文件夾下的文件,如果傳入的directory是個文件,將不做處理 * * @param directory */
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}
}
}
主要功能清除內/外緩存,清除資料庫,清除sharedPreference,清除files和清除自定義目錄
G. android4.3下導入osc客戶端,CacheManager找不到,求解答
修改成4.0版本,並重新加入import android.webkit.CacheManager; Fix下工程即可
//清除webview緩存
// File file = CacheManager.getCacheFileBaseDir();
// if (file != null && file.exists() && file.isDirectory()) {
// for (File item : file.listFiles()) {
// item.delete();
// }
// file.delete();
// }
H. android 怎麼自動清理緩存
/**文件名:DataCleanManager.java*描述:主要功能有清除內/外緩存,清除資料庫,清除sharedPreference,清除files和清除自定義目錄*/
importjava.io.File;
importandroid.content.Context;
importandroid.os.Environment;
/***本應用數據清除管理器*/
publicclassDataCleanManager{
/***清除本應用內部緩存(/data/data/com.xxx.xxx/cache)**@paramcontext*/
(Contextcontext){
deleteFilesByDirectory(context.getCacheDir());
}
/***清除本應用所有資料庫(/data/data/com.xxx.xxx/databases)**@paramcontext*/
(Contextcontext){
deleteFilesByDirectory(newFile("/data/data/"
+context.getPackageName()+"/databases"));
}
/**
**清除本應用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)**@param
*context
*/
(Contextcontext){
deleteFilesByDirectory(newFile("/data/data/"
+context.getPackageName()+"/shared_prefs"));
}
/***按名字清除本應用資料庫**@paramcontext*@paramdbName*/
(Contextcontext,StringdbName){
context.deleteDatabase(dbName);
}
/***清除/data/data/com.xxx.xxx/files下的內容**@paramcontext*/
publicstaticvoidcleanFiles(Contextcontext){
deleteFilesByDirectory(context.getFilesDir());
}
/**
**清除外部cache下的內容(/mnt/sdcard/android/data/com.xxx.xxx/cache)**@param
*context
*/
(Contextcontext){
if(Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)){
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/***清除自定義路徑下的文件,使用需小心,請不要誤刪。而且只支持目錄下的文件刪除**@paramfilePath*/
(StringfilePath){
deleteFilesByDirectory(newFile(filePath));
}
/***清除本應用所有的數據**@paramcontext*@paramfilepath*/
(Contextcontext,String...filepath){
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
for(StringfilePath:filepath){
cleanCustomCache(filePath);
}
}
/***刪除方法這里只會刪除某個文件夾下的文件,如果傳入的directory是個文件,將不做處理**@paramdirectory*/
(Filedirectory){
if(directory!=null&&directory.exists()&&directory.isDirectory()){
for(Fileitem:directory.listFiles()){
item.delete();
}
}
}
}
I. android現在怎麼清除webview緩存不能用cachemanager.getcachefilebasedir
一、清除cookie
public static void clearCookies(Context context) {
// Edge case: an illegal state exception is thrown if an instance of
// CookieSyncManager has not be created. CookieSyncManager is normally
// created by a WebKit view, but this might happen if you start the
// app, restore saved state, and click logout before running a UI
// dialog in a WebView -- in which case the app crashes
@SuppressWarnings("unused")
CookieSyncManager cookieSyncMngr =
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
這是facebook sdk的源碼,我不知道第一句到底起了什麼作用?
二、清除webview緩存,查看root過的手機data下的文件,會發現有這個東西:webview命名的東西
刪除保存於手機上的緩存.
// clear the cache before time numDays
private int clearCacheFolder(File dir, long numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
if (child.lastModified() < numDays) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
return deletedFiles;
}
打開關閉使用緩存
//優先使用緩存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//不使用緩存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
在退出應用的時候加上如下代碼
File file = CacheManager.getCacheFileBaseDir();
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete();
}
file.delete();
}
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
發現這個問題,一個朋友在iteye上問的:
Android的CookieManager只提供了removeAllCookies方法,用來刪除所有的cookie,有什麼辦法只刪除和特定url關聯的cookie呢?本來打算使用setCookie(url, value)將指定url關聯的cookie設為空串,但試了一下發現這個方法只是在已有的基礎上繼續添加cookie,並不能重置已有的cookie。
有朋友給打答案:
/**
* 同步一下cookie
*/
public static void synCookies(Context context, String url) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();//移除
cookieManager.setCookie(url, cookies);//指定要修改的cookies
CookieSyncManager.getInstance().sync();
}
J. 如何清理android sdk manager的download cache
download cache是手機里的高速緩沖文件,可以快速打開閱讀中的小說等功能,該文件是由系統自動生成。
可以在手機中找到該文件夾直接刪除。
因為是系統自動生成,所以即使刪除該文件,下次打開文件時依然會自動生成。