I would like to receive an event whenever a file was added to a specific folder, e.g. the download folder. To reach this I tried 3 different approaches without any success. The
Actually, right now there is no known work-around for Android 6.0 and above. In Android 4/5/5.1 the FileObserver
is working fine mostly, but for Android 6 you simply can't get any kind of response from the system when a file is added to an external directory. Knowing this FileObserver
is completely useless in Android 6.
But eventually you can detect added content in the Android system, with the Content Observer which is also working fine in Android 6. Maybe this can solve your problem until Google provides a fix.
This is how I currently use the ContenObserver:
mycontentobserver = new MyContentObserver(handler,**Your path**,this);
getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, mycontentobserver);
An than the MyContentOberserver.class I just check for last edited files in my specific path and if they are not older than 5-10 seconds I assume that this triggered the ContentObserver Event.
This is how it should work for you:
In your BackgroundService.class:
mycontentobserver = new MyContentObserver(handler,**Your download folder path**,this);
getContentResolver().registerContentObserver(MediaStore.Files.getContentUri("external"), true, mycontentobserver);
And than inside the MyContentObserver.class:
public MyContentObserver(Handler handler, String workpath, ContentModificationService workcontext) {
super(handler);
downloadfolderpath = workpath;
contentcontext = workcontext;
}
@Override
public void onChange(boolean selfChange, Uri uri) {
if(downloadfolderpath != null) {
File file = new File(downloadfolder);
if (file.isDirectory()) {
listFile = file.listFiles();
if (listFile != null && listFile.length > 0) {
// Sort files from newest to oldest (this is not the best Method to do it, but a quick on)
Arrays.sort(listFile, new Comparator() {
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
if (listFile[listFile.length - 1].lastModified() >= System.currentTimeMillis() - 5000) { //adjust the time (5000 = 5 seconds) if you want.
//Some file was added !! Yeah!
//Use the contentcontext to launch some Method in you Service
//For example:
contentcontext.SomeMethodToContinue();
}
}
}
}
}
I hope this helps, let me now If it works for you. It work's for me with the download folder on android 6.1 :)