androidkotlinfileobserver

Alternative to the deprecated FileObserver constructor for API level <29


According to the documentation, both FileObserver(path: String!) and FileObserver(path: String!, mask: Int) are deprecated (I don't know when). However, all other constructors were only added in API 29 (10/Q) and I'm trying to support from API 19 (4/KitKat) onwards.

What will be the alternative to monitor a file once these two constructors get removed in later APIs?


Solution

  • To answer this directly,

    1. The new api requires a File type as the first parameter instead of a string. IE FileObserver(File(path), mask)

    2. If you need to support APIs before and after deprecation, consider writing a wrapper function. Example (in kotlin)

    open class FileObserverApiWrapper(path: String, mask: Int) {
      private var fileObserver: FileObserver? = null
    
      init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
          fileObserver = object : FileObserver(File(path), mask) {
            override fun onEvent(event: Int, path: String?) {
              this@FileObserverApiWrapper.onEvent(event,path)
            }
          }
        } else {
          @Suppress("DEPRECATION")
          fileObserver = object : FileObserver(path, mask) {
            override fun onEvent(event: Int, path: String?) {
              this@FileObserverApiWrapper.onEvent(event,path)
            }
          }
        }
      }
    
      /**
       * @description does nothing, can be overridden. Equivalent to FileObserver.onEvent
       */
      open fun onEvent(event: Int, path: String?){}
    
      open fun startWatching() {
        fileObserver?.startWatching()
      }
    
      open fun stopWatching() {
        fileObserver?.stopWatching()
      }
    }