How to create FileObserver in Android

A FileObserver in Android is an interface that monitors file access and modification. It triggers an event any time a file is accessed or changed by any process on the device.

Each FileObserver instance monitors either a file or a directory. And if the instance is observing a directory, events will be triggered for all files and sub-directories inside the monitored directory.

Warning

If a FileObserver is garbage collected, it will stop sending events. Also, FileObserver must be referenced from some live project to ensure that it works properly.

Geeky Stuff

  • FileObserver is an abstract class. Consequently, one must create a subclass that extends the FileObserver class.
  • The subclass also must implement the OnEvent method.
  • FileObserver is based on Linux’s iNotify. iNotify is a simple but powerful file change notification system built into the Linux 2.6.13 kernel and above.

The Code

Today, we will be creating a FileObserver that will observe a particular directory aka Directory FileObserver. And this FileObserver will fire an event when any file is created in the Observing Directory.

Step 1: Add Read External Storage Permission to Manifest File

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Step 2: Create a subclass that extends FileObserver.

public class DirectoryFileObserver extends FileObserver { 
String aboslutePath = "path to your directory"; 
public DirectoryFileObserver(String path) { super(path,FileObserver.CREATE); 
aboslutePath = path;
}
@Override public void onEvent(int event, String path) { 
if(path != null)
{
Log.e("FileObserver: ","File Created");
}
}
}

Step 3: Call the FileObserver from Activity

public class MainActivity extends AppCompatActivity { 
DirectoryFileObserver directoryFileObserver; 
@Override protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main); 
context = this;
directoryFileObserver = new DirectoryFileObserver(Path of the directory);
directoryFileObserver.startWatching();
}
}

When you execute the above code, it will display a log message “File Created”, every time a new File or Directory is created in the directory referred by the variable absolutePath.

FileObserver in Android supports many types of events. For complete list click here.


Originally published at theengineerscafe.com on March 27, 2017.