如何从 Android 服务实现 FileObserver

2022-09-01 11:23:30

你如何构建一个Android应用程序来启动一个使用,以便在修改观察到的目录(即用户拍照)时执行一些其他代码。调试时,永远不会触发 onEvent 方法。ServiceFileObserver

这是我的服务中的 onStart 事件。“我的服务已开始...”的火灾Toast

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永远不会开火。这是通过调试确定的。它永远不会碰到那个断点,Toast永远不会触发。

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

你如何得到一个工作在?FileObserverService


答案 1

请参阅此帖子。我认为您在设置观察器后错过了呼叫。observer.startWatching()

 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).show();
         //}
     }
 };
 observer.startWatching(); //START OBSERVING 

答案 2

在 之后添加 ,即.show()toast

Toast.makeText(getBaseContext(), file + " was saved!", toast.LENGTH_LONG).show();                  

推荐