Search code examples
androidandroid-camerafileobserver

Android detect camera capture event using FileObserver


How can I detect when user take a picture in their camera? I'm running in service. I want to get byte data of it.

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera";
fileObserver = new FileObserver(path) {
    @Override
    public void onEvent(int event, String file) {

        Log("File: " + file);
    }
};

fileObserver.startWatching();

Solution

  • You have to watch CREATE event of FileObserver.

    String PATH = Environment.getExternalStorageDirectory().getAbsolutePATH() + "/DCIM/Camera";
    observer = new FileObserver(PATH) {
        @Override
        public void onEvent(int event, String file) {
    
            //if it's not CREATE event, return
            if(event != FileObserver.CREATE)
                return;
    
            byte[] bytes = new byte[0];
            String filePath = PATH + "/" + file;
    
            try {
                bytes = org.apache.commons.io.FileUtils.readFileToByteArray(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            if(bytes.length == 0)
                return;
    
            //use byte data here
        }
    };