The use and brief principle of Android FileObserver

FileObserver is an Android class that monitors a specified file or directory for changes. It can help developers detect the creation , deletion , renaming , modification and other operations of files or directories in real time. By using FileObserver, developers can respond to these file system changes in a timely manner and perform specific operations when corresponding events occur.


Use of FileObserver:

class MainActivity : AppCompatActivity() {

    var fileObserver: FileObserver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val path = "/sdcard/xxxx/xxxx" // 监视的文件或目录路径

        fileObserver = object : FileObserver(path) {
            override fun onEvent(event: Int, path: String?) {
                when (event) {
                    CREATE -> {}       // 文件或目录创建
                    DELETE -> {}       // 文件或目录删除
                    DELETE_SELF -> {}  // 自身删除
                    MODIFY -> {}       // 文件或目录修改
                    MOVED_FROM -> {}   // 移动或重命名
                    MOVED_TO -> {}     // 移动或重命名后
                    ATTRIB -> {}       // 文件或目录属性变化
                }
            }
        }
        fileObserver?.startWatching()
    }

    override fun onDestroy() {
        super.onDestroy()
        fileObserver?.stopWatching()
    }

}

Note: You need to ensure that the monitored file path has read and write permissions before the program can run normally


FileObserver interacts with C/C++ code through JNI (Java Native Interface) at the bottom layer, and calls the system's inotify interface . When the FileObserver instance starts, it will create an underlying inotify instance and request the kernel to monitor the specified file or directory .

When the monitored file or directory changes, the kernel will generate a corresponding event and pass the event information to the FileObserver. FileObserver will capture these events and trigger corresponding callback methods, such as onEvent().


It should be noted that the underlying implementation of FileObserver uses Linux-specific features, so it can only be used on Android , and is not applicable to other operating systems or platforms.

Guess you like

Origin blog.csdn.net/weixin_47592544/article/details/132627060