Пробую создать простой FileObserver. Сервис запускается и работает, но события не приходят. Разрешение READ_EXTERNAL_STORAGE есть.
public class MyService extends Service {
public MyService() {
}
public static FileObserver observer;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String pathToWatch = android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/";
File file = new File(pathToWatch);
Log.i("MyService", "My Service Started and trying to watch " + pathToWatch);
observer = new FileObserver(file,FileObserver.ALL_EVENTS) {
@Override
public void onEvent(int event, String file) {
Log.i("MyService", "File created");
}
};
observer.startWatching();
return Service.START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
запускаю вот так
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
},
1);
} else {
Intent intent = new Intent(this, MyService.class);
this.startService(intent);
}
}
file.getCanonicalPath()