File observer stops working after some time

核能气质少年 提交于 2019-12-04 12:23:35

http://developer.android.com/reference/android/os/FileObserver.html

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.

Declare FileObserver as Static and global which will retain the instance of Fileobserver and restrict OS to take service into garbage collector.

I'll present you part of code in my application, which emails every picture you take with your phone to predefinded list of emails. The sending email and list of receiving emails are stored in Shared Preferences. I use Service class and FileObserver to watch pictures directory of the phone. In my case, this scheme resloves also the problem with FileObserver, which stops work after some period of time.

  1. Use an activity (StartServicesActivity) to start the service (FileObserverService) as Foreground service.
  2. Use BroadcastReceiver class (in example CommonReceiver) to restart your service in some special situations and in case it was killed.
  3. Each time the service is restarted (performs onStartCommand) recreate FileObserver object to watch the pictures directory.

I used this code in my app "Email Pictures Automatically" https://play.google.com/store/apps/details?id=com.alexpap.EmailPicturesFree

Here is CommonReceiver class.

public class CommonReceiver extends BroadcastReceiver {

    public void onReceive(Context paramContext, Intent paramIntent)
    {
        paramContext.startService(new Intent(paramContext, FileObserverService.class));
    }
}

Here is its definition in AndroidManifest.xml just before application closing tag.

<receiver android:name="com.alexpap.services.CommonReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.USER_PRESENT"/>
    </intent-filter>
</receiver>

Start service in StartServicesActivity activity.

Intent iFileObserver = new Intent(StartServicesActivity.this, FileObserverService.class);
StartServicesActivity.this.startService(iFileObserver);

Here is onCreate() method of the service FileObserverService.

//Class variables
MediaFileObserver observPictures = null;
String pathToWatchPic = "";

public void onCreate() {

    pathToWatchPic = Environment.getExternalStorageDirectory().toString() + "/DCIM/100MEDIA";       

    File  mediaStorageDir = new File(pathToWatchPic); 
    if (!mediaStorageDir.exists()){
        pathToWatchPic = Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera";
    }

}

Here is onStartCommand() method of the service FileObserverService.

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

    int res = super.onStartCommand(intent, flags, startId);

    if (observPictures != null){
        observPictures.stopWatching();
    }
    //each time service is restarted, observPictures object is recreated
    //and observation is restarted. This way File Observer never stops.
    observPictures = new MediaFileObserver(this, pathToWatchPic);
    observPictures.startWatching();

    startServiceForeground(intent, flags, startId);

    return Service.START_STICKY;  
}

public int startServiceForeground(Intent intent, int flags, int startId) {

    Intent notificationIntent = new Intent(this, StartServicesActivity.class); 
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this)
        .setContentTitle("File Observer Service")
        .setContentIntent(pendingIntent)
        .setOngoing(true)
            .build();

    startForeground(300, notification);

    return START_STICKY;
}

Service is restarted also each time you turn on the phone and after rebooting.

Try to link reference to Observer in your Application class. like this

private ArrayList<FileObserver> mObservers = new ArrayList<FileObserver>();

public void addObserver(FileObserver observer){
    mObservers.add(observer);
}

public void removeObserver(FileObserver observer){
    mObservers.remove(observer);
}

This works for me!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!