import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class CacheUtils {
public void clearCache(Context context) {
try {
// 清除内部缓存
File internalCacheDir = context.getCacheDir();
if (internalCacheDir != null && internalCacheDir.isDirectory()) {
deleteDirectoryContents(internalCacheDir);
}
// 清除外部缓存(如果存在)
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalCacheDir = context.getExternalCacheDir();
if (externalCacheDir != null && externalCacheDir.isDirectory()) {
deleteDirectoryContents(externalCacheDir);
}
}
new Handler(Looper.getMainLooper()).post(() ->
Toast.makeText(context, "Successfully deleted cache", Toast.LENGTH_SHORT).show()
);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void deleteDirectoryContents(File directory) throws IOException {
if (directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectoryContents(file);
} else {
if (!file.delete()) {
throw new IOException("Failed to delete file: " + file.getAbsolutePath());
}
}
}
}
}
}
}
当然你也可以加一个小动画,
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginTop="100dp"/>
这个一个类似于load的加载动画
progressBar.setVisibility(View.GONE);
在onCreate中找到该控件,并标明不显示
rl_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
ObjectAnimator animator = ObjectAnimator.ofFloat(progressBar, "rotation", 0f, 360f);
animator.setDuration(1000);
animator.setInterpolator(new LinearInterpolator());
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.start();
// 延时1秒钟关闭进度条
handler.postDelayed(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
cacheUtils.clearCache(SettingActivity.this);
}
}, 1000);
}
});
点击clear按钮后执行该效果,1s后关闭该效果