虽然知道清理缓存对手机性能没啥用处,不过客户要求了嘛,开始做吧
1)npm install -g plugman
若我们需要自己编写自己的插件,则可以使用额外的一个叫做plugman的工具, 该工具可直接通过npm来安装。使用plugman的好处就是会自动帮我们生成一套代码框架,而不需要我们再自己一个个建立文件。
2)安装成功后,就可以使用plugman命令来自动生成插件代码框架,避免手工建立和输入代码文件的工作:
plugman create --name
--plugin_id --plugin_version 0.0.1
例如:plugman create --name cacheclear --plugin_id com.test. cacheclear --plugin_version 0.0.1
pluginName: 插件名称(在当前文件夹下生成项目目录)
pluginID:插件的唯一标识生成插件的唯一标识
3)这里我们给我们之前生成的插件添加Android平台的支持:
cd MyPlugin(注意,一定要到插件目录下执行)
plugman platform add --platform_name android
plugman createpackagejson 文件路径
4)进入我们想要装插件的项目的根目录,运行以下命令:
Ionic cordova plugin add 你插件的存储路径
运行完成后,我们的插件就装到我们的项目中了。
如果报以下错误,说明插件代码有问题,需要移除插件-修改-添加插件,重新run
cordova plugin list 看所有插件
ionic cordova plugin remove com.test.cacheplugin 移除某个插件
ionic cordova plugin add F:\book\cacheplugin添加插件
-------------- --------------------------------------------------------------------------------------------------------------------------------------------------
需要两个方法,一个获取缓存大小,一个清理缓存。
插件的目录如下:
在cacheclear.js中添加两个入口方法:
var exec = require('cordova/exec');
var myAPI = {}
myAPI.deleteFileCache = function(success, error) {
exec(success, error, "cacheclear", "deleteFileCache");
};
//获取缓存大小
myAPI.getCacheSize = function( success, error) {
exec(success, error, "cacheclear", "getCacheSize");
};
module.exports = myAPI;
cacheclear.java里面放置android原生代码,要先用原生调试出来,再贴过来。
package com.test.cacheclear;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.math.BigDecimal;
/**
* 缓存清理插件
*/
public class cacheclear extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("deleteFileCache")) {
this.deleteFileCache(callbackContext);
return true;
} else if (action.equals("getCacheSize")) {
this.getCacheSize(callbackContext);
return true;
}
return false;
}
/**
* 缓存清理
*
* @param callbackContext
* @return
*/
private void deleteFileCache(CallbackContext callbackContext) {
File cacheDic = cordova.getActivity().getCacheDir();
try {
deleteFilesByDirectory(cacheDic);
callbackContext.success("缓存清理成功");
} catch (Exception e) {
e.getCause();
callbackContext.error("缓存清理失败");
}
}
/**
* * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * *
*
* @param directory
*/
private static void deleteFilesByDirectory(File directory) {
File[] fileList = directory.listFiles();
for (int i = 0; i < fileList.length; i++) {
// 如果下面还有文件
if (fileList[i].isDirectory()) {
deleteFilesByDirectory(fileList[i]);
} else {
fileList[i].delete();
}
}
/*if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}*/
}
/**
* 获取格式化后文件大小
*
* @param file
* @return
* @throws Exception
*/
public void getCacheSize(CallbackContext callbackContext) {
File file = cordova.getActivity().getCacheDir();
try {
String fileSize = getFormatSize(getFolderSize(file));
callbackContext.success(fileSize);
} catch (Exception e) {
callbackContext.error("获取缓存长度失败");
}
}
/**
* 获取文件大小
*
* @param file
* @return
* @throws Exception
*/
public long getFolderSize(File file) {
long size = 0;
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
// 如果下面还有文件
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
return size;
}
/**
* 格式化长度
*
* @param size
* @return
*/
public static String getFormatSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
// return size + "Byte";
return "0KB";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
+ "TB";
}
}
ios的清理缓存不是我做的,不过我悄悄贴下代码吧,虽然我看不懂
/********* clearCache.m Cordova Plugin Implementation *******/
#import
@interface cacheclear : CDVPlugin
{
// Member variables go here.
}
- (void)getCacheSize:(CDVInvokedUrlCommand *)command;
- (void)deleteFileCache:(CDVInvokedUrlCommand *)command;
@end
@implementation cacheclear
//默认调用检查缓存
- (void)getCacheSize:(CDVInvokedUrlCommand *)command
{
[self.commandDelegate runInBackground:^{
NSLog(@"检查缓存");
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@", path); //打印缓存路径
NSFileManager *fileManager = [NSFileManager defaultManager];
float folderSize = 0.0;
CDVPluginResult *pluginResult = nil;
if ([fileManager fileExistsAtPath:path])
{
//拿到算有文件的数组
NSArray *childerFiles = [fileManager subpathsAtPath:path];
//拿到每个文件的名字,如有有不想清除的文件就在这里判断
for (NSString *fileName in childerFiles)
{
//将路径拼接到一起
NSString *fullPath = [path stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fullPath];
}
NSLog(@"%@", [NSString stringWithFormat:@"缓存大小为%.2f,确定要清理缓存吗?", folderSize]);
NSLog(@"%@", [NSString stringWithFormat:@"%.2f", folderSize]);
if (folderSize / 1024.0 / 1024.0 / 1024.0 > 1.0)
{
float cache = folderSize / 1024.0 / 1024.0 / 1024.0;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[NSString stringWithFormat:@"%.2fGB", cache]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
else if (folderSize / 1024.0 / 1024.0 > 1.0)
{
float cache = folderSize / 1024.0 / 1024.0;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[NSString stringWithFormat:@"%.2fMB", cache]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
else if (folderSize / 1024.0 > 1.0)
{
float cache = folderSize / 1024.0;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[NSString stringWithFormat:@"%.2fKB", cache]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
else
{
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"0KB"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
}
else
{
NSLog(@"清理失败");
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}];
}
//计算单个文件夹的大小
- (float)fileSizeAtPath:(NSString *)path
{
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path])
{
long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
return size;
}
return 0;
}
//清理缓存
- (void)deleteFileCache:(CDVInvokedUrlCommand *)command
{
[self.commandDelegate runInBackground:^{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path])
{
NSArray *childerFiles = [fileManager subpathsAtPath:path];
for (NSString *fileName in childerFiles)
{
//如有需要,加入条件,过滤掉不想删除的文件
NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
[fileManager removeItemAtPath:absolutePath error:nil];
}
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"缓存清理成功"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
else
{
CDVPluginResult *pluginResult = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"缓存清理失败"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}];
}
@end
在ionic项目中的应用代码:
/*获取缓存大小*/
getCache2() {
try {
cordova.plugins.cacheclear.getCacheSize(result => {
$(".span-text-kb").text(result);
}, error => console.log(error))
} catch (ev) {
console.log("ev:" + ev.toString())
}
}
/*清除缓存*/
getCache() {
this.loading = this.loadingCtrl.create({
content: ''
});
this.loading.present();
localStorage.clear();
try {
cordova.plugins.cacheclear.deleteFileCache(result => {
console.log(result);
if (this.storage.telphoneNum != null && this.storage.telphoneNum != '' && this.storage.telphoneNum != undefined) {
this.storage.setTelphoneNum(this.storage.telphoneNum);
this.storage.setPassword(this.storage.password);
this.storage.setIsLogin(this.storage.isLogin);
}
if (this.storage.getIsLogin() == "true") {
this.storage.loginBack().then(res => {
this.loading.dismiss();
ToastUtils.presentToast(this.toastCtrl, "缓存清理成功");
}, err => {
this.loading.dismiss();
}).catch(error => {
this.loading.dismiss();
});
} else {
this.loading.dismiss();
ToastUtils.presentToast(this.toastCtrl, "缓存清理成功");
}
SettingPage.pageThis.getCache2();
}, error => {
this.loading.dismiss();
ToastUtils.presentToast(this.toastCtrl, "缓存清理失败")
});
} catch (ev) {
ToastUtils.presentToast(this.toastCtrl, "缓存清理失败");
console.log("ev:" + ev.toString());
this.loading.dismiss();
}
}