Android 使用 FileObserver 检测相机捕获事件

Android detect camera capture event using FileObserver

如何检测用户何时用相机拍照?我 运行 在服役。我想获取它的字节数据。

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

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

fileObserver.startWatching();

您必须观看 FileObserver 的 CREATE 事件。

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
    }
};