您的位置:首页 > 其它

98利用反射清理应用程序的缓存以及清理所有应用程序的缓存

2015-01-01 22:27 295 查看
当使用缓存得到单个应用程序的缓存之后,查看源码,得到清除缓存的方法,同样,这里也需要使用反射区清理,当完成后,提示我们需要添加权限:

<uses-permission android:name="android.permission.DELETE_CACHE_FILES"/>


但是当我们保存的时候,发现这条权限居然报错了,意思是:这个权限是授权给系统程序的,所以我们的程序不能使用清楚缓存的功能,当单击清除缓存的功能的时候,弹出到设置界面的清楚缓存的功能。

清理全部的缓存的思路是:

利用了系统的BUG,当系统内存不足的时候,系统会回收应用程序的缓存,我们可以发送信息给系统,告诉系统我们需要Integer.MAX_VALUE的内存空间。

/**
     * Free storage by deleting LRU sorted list of cache files across
     * all applications. If the currently available free storage
     * on the device is greater than or equal to the requested
     * free storage, no cache files are cleared. If the currently
     * available storage on the device is less than the requested
     * free storage, some or all of the cache files across
     * all applications are deleted (based on last accessed time)
     * to increase the free storage space on the device to
     * the requested value. There is no guarantee that clearing all
     * the cache files from all applications will clear up
     * enough storage to achieve the desired value.
     * @param freeStorageSize The number of bytes of storage to be
     * freed by the system. Say if freeStorageSize is XX,
     * and the current free storage is YY,
     * if XX is less than YY, just return. if not free XX-YY number
     * of bytes if possible.
     * @param observer call back used to notify when
     * the operation is completed
     *
     * @hide
     */
    public abstract void freeStorageAndNotify(long freeStorageSize, IPackageDataObserver observer);


public void cleanAll(View view){
//		/freeStorageAndNotify
		Method[] methods = PackageManager.class.getMethods();
		for(Method method:methods){
			if("freeStorageAndNotify".equals(method.getName())){
				try {
					method.invoke(pm, Integer.MAX_VALUE, new IPackageDataObserver.Stub() {
						@Override
						public void onRemoveCompleted(String packageName,
								boolean succeeded) throws RemoteException {
							System.out.println(succeeded);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		}
	}


最后,还要添加权限:

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐