Android FileObserver events not working as expected

54 views Asked by At

I have implemented FileObserver inside my Service class to observe deletion and insertion of file inside .Statuses directory. I am using service so that I can observe file change even if my app is in background but the problem is when I am checking for delete or insert file using event==FileObserver.DELETE or event==FileObserver.CREATE the event value are completely different from DELETE or CREATE value. For example in case of delete file, event value is 32 and sometimes some large number when trying to delete multiple files but actual value of FileObserver.DELETE is 512.Is there any fix for this?

Here is my FileMonitorService code:

class FolderMonitorService : Service() {

companion object {
    private const val TAG = "FolderMonitorService"
    const val FILE_CHANGED_ACTION = "file_changed_action"
    const val FILE_PATH_EXTRA = "file_path_extra"
}

private var fileObserver: FileObserver? = null

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    // Retrieve the folder path from the intent
    val folderPath = intent?.getStringExtra("folderPath")
    val folder = File(folderPath.toString())
    Log.i(TAG, "Folder changed: ${folder}")

    // Set up FileObserver to monitor the specified folder
    fileObserver = object : FileObserver(folder, FileObserver.ALL_EVENTS) {
        override fun onEvent(event: Int, path: String?) {
            // Handle file system event
            Log.i(TAG, "File system event: $path")
            if (event == 32) {
                // Notify the local broadcast receiver about the file change
                path?.let { filePath ->
                    if (filePath.endsWith(".jpg") || filePath.endsWith(".webp")) {
                        val broadcastIntent = Intent(FILE_CHANGED_ACTION)
                        broadcastIntent.putExtra(
                            FILE_PATH_EXTRA,
                            "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses/document/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses%2F$filePath"
                        )
                        LocalBroadcastManager.getInstance(applicationContext)
                            .sendBroadcast(broadcastIntent)
                        Log.i(TAG, "File Delete event: $filePath")
                    }
                }
            }
        }
    }

    // Start watching the folder
    fileObserver?.startWatching()

    return START_STICKY
}

override fun onDestroy() {
    super.onDestroy()
    Log.i(TAG, "Folder changed: destroyed")
    // Stop watching the folder when the service is destroyed
    fileObserver?.stopWatching()
}

override fun onBind(intent: Intent): IBinder? {
    return null
}
}
0

There are 0 answers