0

I am running a FileObserve application to detect new file creation in a folder. Below is a snippet of the onStartCommand of the service I use to start FileObserve.

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
                Thread Scan = new Thread() {
                    public void run() {
                        Log.i(TAG,"Started");
                        fileObserver = new FileObserve(Environment.getExternalStorageDirectory().getPath(),FileObserve.CREATE){
                            public void onEvent(int i, String s){
                                try {

                                    //Modify files


                                } catch (Exception e) {

                                }
                            }
                        };

                        fileObserver.startWatching();
                    }
                };
        Scan.start();

        return START_REDELIVER_INTENT;
    }

When I run the application, for some time it runs in the background and detects any new file creation. This is validated through running services menu in settings, and also through some file modifications done by the application whenever a new file is created.

But after a while it stops running in background. Any new file created at this time does not undergo any modification. Also service not seen in listed running services menu. But sometimes it says restarting, but never starts at all.

Is it possible to solve this using some service flags? If not whats the alternative? Will sending a broadcast in OnDestroy() work?

Abhinandan
  • 159
  • 1
  • 14
  • there may be some kind of exception while modifying the files, also try using IntentService for these tasks or may be you don't even need a service for this usage – rex Oct 03 '17 at 11:35
  • @rex IntentService is different purpose. Anyways I solved using https://stackoverflow.com/questions/7265906/how-do-you-implement-a-fileobserver-from-an-android-service – Abhinandan Oct 04 '17 at 05:29

1 Answers1

0

Instead of using threads inside service. Just call it in onStart() like below.

@Override
public void onStart(Intent intent, int startid) {   
                 Log.i(TAG,"Started");
                    fileObserver = new FileObserve(Environment.getExternalStorageDirectory().getPath(),FileObserve.CREATE){
                        public void onEvent(int i, String s){
                            try {

                                //Modify files


                            } catch (Exception e) {

                            }
                        }
                    };

                 fileObserver.startWatching();

    }

This will solve the issue. But I am not sure, why this works.Would be glad if someone could give a reason for this behaviour.

Source used:How do you implement a FileObserver from an Android Service

Abhinandan
  • 159
  • 1
  • 14