一尘不染

如何通过Android服务实现FileObserver

java

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

这是我在服务中遇到的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);                  
                //}
            }
        };
    }

但是在那次Toast之后,如果我拍照,则onEvent永远不会触发。这是通过调试确定的。它永远不会碰到那个断点,而Toast也不会触发。

浏览该目录后,新图像将保存在该目录中。

你如何在一个FileObserver工作Service


阅读 602

收藏
2020-09-08

共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
2020-09-08