【发布时间】:2015-03-06 04:13:09
【问题描述】:
我在使用 StrictMode 时遇到问题,我有以下 AsyncTask
class pruneDiskCacheTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
pruneRecursive(DiskCache);
return null;
}
void pruneRecursive(File fileOrDirectory){
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
pruneRecursive(child);
}
}else {
if(checkForPruningAsync(fileOrDirectory)){
fileOrDirectory.delete();
}
}
}
public boolean checkForPruningAsync(File file){
String fileName = file.getName();
String type = fileName.substring(fileName.lastIndexOf(".")+1);
Date lastModified = new Date(file.lastModified());
if(type.equals("json")){
Date cacheLifetime = new Date(new Date().getTime() - keepJsonFor);
if(lastModified.before(cacheLifetime)){
return true;
}
}else if(type.equals("txt")) {
Date cacheLifetime = new Date(new Date().getTime() - keepTxtFor);
if(lastModified.before(cacheLifetime)){
return true;
}
}else{
Date cacheLifetime = new Date(new Date().getTime() - keepImagesFor);
if(lastModified.before(cacheLifetime)){
return true;
}
}
return false;
}
}
它抛出一个 StrictMode 错误(似乎没有使程序崩溃,但我不喜欢它弹出)
android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk
我的理解是,如果您将某些内容放入 Async Task 中,则它符合 StrictMode 的要求。但在这种情况下,我似乎错了。有人可以告诉我我做错了什么吗?
编辑
这是我按要求调用异步任务的方式
public void pruneDiskCache(){
synchronized (mDiskCacheLock) {
// Wait while disk cache is started from background thread
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {
}
}
if(DiskCache.exists()) {
new pruneDiskCacheTask().execute();
}
}
}
这是从我创建的缓存类中调用的
mActivity = this;
cacheHandeler = new Cache(mActivity);
在我的主线程中。
【问题讨论】:
-
您能否包括调用 AsyncTask 的位置?
-
对严格模式进行了更多研究。似乎是一个调试工具,可确保您的程序尽可能快地运行。所以问题是:有没有更好的(更少的资源消耗)方法来做到这一点?因为这只发生在用户强制重新加载数据集时,我会将其标记为必要的邪恶。
-
StrictMode 仅在您在主线程上执行操作时触发(当然,您不应该这样做) - 再次,我们需要查看您在哪里调用 AsyncTask 以了解它的原因正在发生。
-
添加了它被调用的地方。感谢您的快速回复:)
标签: android android-strictmode disk-access