导航:首页 > 操作系统 > cachemanagerandroid

cachemanagerandroid

发布时间:2022-05-29 09:48:23

A. android开发中怎样清除本地缓存文件夹

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是手机里的高速缓冲文件,可以快速打开阅读中的小说等功能,该文件是由系统自动生成。
可以在手机中找到该文件夹直接删除。
因为是系统自动生成,所以即使删除该文件,下次打开文件时依然会自动生成。

阅读全文

与cachemanagerandroid相关的资料

热点内容
自己购买云主服务器推荐 浏览:419
个人所得税java 浏览:761
多余的服务器滑道还有什么用 浏览:189
pdf劈开合并 浏览:28
不能修改的pdf 浏览:751
同城公众源码 浏览:488
一个服务器2个端口怎么映射 浏览:297
java字符串ascii码 浏览:78
台湾云服务器怎么租服务器 浏览:475
旅游手机网站源码 浏览:332
android关联表 浏览:945
安卓导航无声音怎么维修 浏览:332
app怎么装视频 浏览:430
安卓系统下的软件怎么移到桌面 浏览:96
windows拷贝到linux 浏览:772
mdr软件解压和别人不一样 浏览:904
单片机串行通信有什么好处 浏览:340
游戏开发程序员书籍 浏览:860
pdf中图片修改 浏览:288
汇编编译后 浏览:491