如何实现从一个Android服务一个FileObserver如何实现、Android、FileObserver

2023-09-13 23:46:13 作者:与往事干杯

你如何构建一个Android应用程序启动服务使用 FileObserver ,这样,当观察到的目录被修改(即用户需要图片)一些其他的code执行。调试时的onEvent方法不会被触发。

How do you structure an Android app to start a Service to use a FileObserver so that when the observed directory is modified (ie user takes picture) some other code executes. When debugging, the onEvent method is never triggered.

下面是ONSTART事件中,我在我的服务。该吐司火的我的服务启动...

Here is the onStart event I have in my Service. The Toast fires for "My Service Started..."

public final String TAG = "DEBUG";
public static FileObserver observer;    

@Override
public void onStart(Intent intent, int startid) {       
        Log.d(TAG, "onStart");

        final String pathToWatch = android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/";       
        Toast.makeText(this, "My Service Started and trying to watch " + pathToWatch, Toast.LENGTH_LONG).show();

        observer = new FileObserver(pathToWatch) { // set up a file observer to watch this directory on sd card
            @Override
            public void onEvent(int event, String file) {
                //if(event == FileObserver.CREATE && !file.equals(".probe")){ // check if its a "create" and not equal to .probe because thats created every time camera is launched
                    Log.d(TAG, "File created [" + pathToWatch + file + "]");

                    Toast.makeText(getBaseContext(), file + " was saved!", Toast.LENGTH_LONG);                  
                //}
            }
        };
    }

但是,敬酒之后,如果我拍照的onEvent永远不会触发。这是通过调试确定。它从来没有命中断点和吐司永远不会触发。

But after that Toast, if I take a picture the onEvent never fires. This is determined by debugging. It never hits that breakpoint and the Toast never fires.

在该目录浏览,新的图像保存在那里。

When that directory is browsed, the new image is saved there.

你如何获得一个 FileObserver 工作中的一个服务

How do you get a FileObserver working in a Service?

推荐答案

请see这一职务。我认为你缺少你设置你的观察后observer.startWatching()调用。

Please see this post. I think you are missing the observer.startWatching() call after you setup your observer.

 observer = new FileObserver(pathToWatch) { // set up a file observer to watch this directory on sd card

     @Override
     public void onEvent(int event, String file) {
         //if(event == FileObserver.CREATE && !file.equals(".probe")){ // check if its a "create" and not equal to .probe because thats created every time camera is launched
         Log.d(TAG, "File created [" + pathToWatch + file + "]");

         Toast.makeText(getBaseContext(), file + " was saved!", Toast.LENGTH_LONG);
         //}
     }
 };
 observer.startWatching(); //START OBSERVING