0

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();
comrade
  • 4,590
  • 5
  • 33
  • 48
Lazy
  • 1,807
  • 4
  • 29
  • 49
  • 1
    The camera app that the user chooses can store the picture wherever the camera app wants. This includes many places that are not accessible to you (e.g., removable storage, internal storage of the camera app) or cannot be monitored by a `FileObserver` (e.g., a Web server). Also note that a `FileObserver` is only useful when your process is running. – CommonsWare Jun 19 '16 at 15:50
  • Thank you for your information @CommonsWare. Is it possible to know which folder chosen by user? – Lazy Jun 19 '16 at 17:52
  • No. There does not have to be a folder. – CommonsWare Jun 19 '16 at 18:00

1 Answers1

1

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
    }
};
Ozgur
  • 3,738
  • 17
  • 34
  • Is it guaranteed the camera's save path is always "DCIM/Camera"? I've seen "100ANDRO" sometimes. Also, if someone downloads a video to this folder then it will also get detected... but that isn't a camera event. – intrepidis Aug 07 '17 at 07:09
  • 1
    No it's not guaranteed. Because in Android there are a lot of ROM and they can be come with custom camera applications, which use different paths. For video event etc, as far as I know there is no way to detect if it comes from camera or external source. – Ozgur Aug 07 '17 at 10:43
  • Ok thanks, that's what I've found too. I've just resorted to checking the path for '/dcim/', '/camera/' or '/100andro/'. There should be a better way than this though... – intrepidis Aug 07 '17 at 14:15