Android 异步执行文件操作
Android Doing file operations async
在 android 中,最好的做法是在单独的线程中完成所有艰苦的工作,永远不会阻塞 ui。现在我唯一的目标是列出应用程序内部目录的所有文件,例如:
final File directory = new File( context.getFilesDir(), "images" );
if( !directory.exists() ) {
directory.mkdirs();
}
return directory.listFiles();
我应该在 Loader 还是 AsyncTaskLoader 中执行此操作?我的脑海里冒出另一个问题。 IE。如果我的 Loader 通过 FileObserver 监听目录更改,那么这个观察者 build 是否在主线程中并且这样做:
new FileObserver( new File( context.getFilesDir(), "images" ).getPath() ) ...
然后该目录也应该异步加载。
列出目录文件通常是一个非常快速的操作,不需要后台线程。
如果您想监听文件更改,这里是问题第二部分的答案,关于 FileObserver 多线程:
在哪个线程上创建 FileObserver
并不重要。所有工作都发生在一个特殊的 FileObserver 线程上。 onEvent
在此特殊线程中被调用。然后您应该手动处理您需要的线程。 onEvent
文档说得很清楚:
The event handler, which must be implemented by subclasses. This
method is invoked on a special FileObserver thread. It runs
independently of any threads, so take care to use appropriate
synchronization! Consider using Handler.post(java.lang.Runnable) to
shift event handling work to the main thread to avoid concurrency
problems.
在 android 中,最好的做法是在单独的线程中完成所有艰苦的工作,永远不会阻塞 ui。现在我唯一的目标是列出应用程序内部目录的所有文件,例如:
final File directory = new File( context.getFilesDir(), "images" );
if( !directory.exists() ) {
directory.mkdirs();
}
return directory.listFiles();
我应该在 Loader 还是 AsyncTaskLoader 中执行此操作?我的脑海里冒出另一个问题。 IE。如果我的 Loader 通过 FileObserver 监听目录更改,那么这个观察者 build 是否在主线程中并且这样做:
new FileObserver( new File( context.getFilesDir(), "images" ).getPath() ) ...
然后该目录也应该异步加载。
列出目录文件通常是一个非常快速的操作,不需要后台线程。
如果您想监听文件更改,这里是问题第二部分的答案,关于 FileObserver 多线程:
在哪个线程上创建 FileObserver
并不重要。所有工作都发生在一个特殊的 FileObserver 线程上。 onEvent
在此特殊线程中被调用。然后您应该手动处理您需要的线程。 onEvent
文档说得很清楚:
The event handler, which must be implemented by subclasses. This method is invoked on a special FileObserver thread. It runs independently of any threads, so take care to use appropriate synchronization! Consider using Handler.post(java.lang.Runnable) to shift event handling work to the main thread to avoid concurrency problems.