0

There are answered questions regarding FileObserver in Android and I am following them but still my code doesn't work. Here I am posting my code, I am trying to set fileObserver via service so it work even if the app itself is closed. When running, it is invoking the DirectoryObserver Constructor but adding or deleting a file doesn't invoke the event

public class MainActivity extends AppCompatActivity
{
    private String sharedPreferencesKey = "IsThisFIrstTime";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (!preferences.contains(sharedPreferencesKey)) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(sharedPreferencesKey, false);
        editor.apply();

        try {
            startTheServices();
        }
        catch (Exception ex) {
        }
    }

    setContentView(R.layout.activity_main);
}

private void startTheServices()
{
    Intent intent = new Intent(this, BackgroundServices.class);
    startService(intent);
}
}



public class BackgroundServices extends Service {

@Override
public void onCreate(){
    super.onCreate();
    Toast.makeText(this, "This is on Create", Toast.LENGTH_LONG).show();


}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "This is on onStartCommand", Toast.LENGTH_LONG).show();
     Thread thread = new Thread(new ThreadClass(startId));
    thread.start();
    return super.onStartCommand(intent, flags, startId);
    //return START_STICKY;
}

@Override
public void onDestroy(){
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


final class ThreadClass implements Runnable {
    int _serviceId;

    ThreadClass(int serviceId) {
        _serviceId = serviceId;
    }

    @Override
    public void run() {
        DirectoryObserver directoryObserver = new DirectoryObserver(new File(Environment.getExternalStorageDirectory(), Constants.Camera_Directory).getAbsolutePath(), getApplicationContext());
        directoryObserver.startWatching();
    }
}
}





public class DirectoryObserver extends FileObserver {
    private static final String TAG = "DIRECTORY_OBERSVER";
    private String directoryPath;
    private Context _context;

public DirectoryObserver(String path, Context context) {
    super(path);

    Log.i(TAG, "Something Happening " + path);
    _context = context;
    directoryPath = path;
}

@Override
public void onEvent(int event, @Nullable String path) {
    if (path == null) {
        return;
    }
    //a new file or subdirectory was created under the monitored directory
    if ((FileObserver.CREATE & event)!=0) {
        Log.i(TAG, "A file is added to the path " + path);

        Toast.makeText(_context, "A new file has been added", Toast.LENGTH_LONG).show();
    }

    if ((FileObserver.DELETE & event)!=0) {
        Log.i(TAG, "A file is deleted to the path " + path);
        //Context.getApplicationContext();
    }
}
}

And following is the menifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="someone.package">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".BackgroundServices" android:exported="false"></service>
    </application>

</manifest>
Manoj Pathak
  • 209
  • 1
  • 5
  • 15

3 Answers3

0

Have You Added The Permission? I Don't Have Enough Reps Otherwise I Would have Commented.

Shashank Mishra
  • 542
  • 4
  • 12
0

The problem here is that the FileObserver is probably being garbage collected, as you can see here:

Warning: If a FileObserver is garbage collected, it will stop sending events. To ensure you keep receiving events, you must keep a reference to the FileObserver instance from some other live object.

Android might be getting rid of your service, or even the FileObserver itself. Try to see if the code is entering the "startWatching()" method, or even if the service is starting.

miguelarc
  • 791
  • 7
  • 13
0

The solution I found is that move the following initialization of DirectoryObserver

 DirectoryObserver directoryObserver = new DirectoryObserver(new File(Environment.getExternalStorageDirectory(), Constants.Camera_Directory).getAbsolutePath(), getApplicationContext());

to

public int onStartCommand(Intent intent, int flags, int startId)

method in BackgroundService Class before following lines

Thread thread = new Thread(new ThreadClass(startId));
    thread.start();
Manoj Pathak
  • 209
  • 1
  • 5
  • 15