2

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?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
vesperto
  • 804
  • 1
  • 6
  • 26
  • First deprecated means you can use it but it will be released in a few years. Therefore you can use conditional execution based on the device API version: https://stackoverflow.com/q/15502935/150978 – Robert Jul 21 '21 at 12:38
  • @Robert which means in a few years I won't have the option to use that method, even with API filtering, hence my question. – vesperto Jul 22 '21 at 08:27
  • Ah... well as long as the filters work, then I could segment by API... makes sense, I'll test that. Make it an answer! – vesperto Jul 22 '21 at 10:20

1 Answers1

0

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()
  }
}
fengelhardt
  • 965
  • 11
  • 24