Search code examples
androidbroadcastreceiveractionintentfilterandroid-external-storage

What is the correct intentfilter for a broadcast receiver to get media changes on external storage?


I just found

ACTION_MEDIA_REMOVED

and am searching for something like:

ACTION_MEDIA_INSERTED and ACTION_MEDIA_CHANGED


Solution

  • You can use FileObserver to observe for any change in a file or directory. Example usage.

    Add the following permission in your manifest file

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

    public class MyFileObserver extends FileObserver {
    
        String absolutePath = "path to your directory";
    
        public MyFileObserver(String path) {
            super(path, FileObserver.CREATE);
            absolutePath = path;
        }
    
        @Override
        public void onEvent(int event, String path) {
            // this is where you will receive all event like file modified, file added...
            if (path != null) {
                Log.e("File created..");
            }
        }
    }
    

    and in your activity

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

    and if you want to observe external storage in the background, then refer this answer