Android 异步执行文件操作

标签 android file asynchronous loader

在 android 中,最好的做法是在一个单独的线程中完成所有艰苦的工作,以免阻塞 ui。现在我唯一的目标是列出应用程序内部目录的所有文件,例如:

final File directory = new File( context.getFilesDir(), "images" );
if( !directory.exists() ) {
    directory.mkdirs();
}
return directory.listFiles();

我应该在 Loader 还是 AsyncTaskLoader 中执行此操作?我的脑海里冒出另一个问题。 IE。如果我的 Loader 通过 FileObserver 监听目录更改,那么这个观察者是否在主线程中构建并像这样:

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 异步执行文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44779984/

相关文章:

c# - "async Task then await Task"与 "Task then return task"

android - MediaMuxer HEVC "no codec config"

android - 如何在android中播放m3u文件?

java - 从文件中读取直到特定的字符序列

Javascript 判断一个文件夹是否是另一个文件夹的子文件夹

node.js - 在事件发射器中使用异步

asynchronous - 从EJB @Asynchronous调用访问CDI SessionScoped bean

javascript - React-Native TouchableNativeFeedback.Ripple 不起作用

android - 将android studio 1.2项目导入android studio 3.0

c# - 从文件中获取原始文件名