I think that we are able to lock files for exclusive access as i saw this link: http://developer.android.com/reference/java/nio/channels/FileLock.html

I want to create a save/load a file both in a background process (service) and the real foreground app. They may try to access this file at the same time, in that case one should wait.

I couldn't find a real sample for FileLock on android, i just read many threads that this is not possible on Android. But if so, why the documentation has a section for "FileLock"?

有帮助吗?

解决方案

This works on normal Java application:

File file = ...;
FileInputStream fis = new FileInputStream(file); // or FileOutputStream fos = new FileOutputStream(file);
FileLock lock = fis.getChannel().lock(); // or FileLock lock = fos.getChannel().lock();

// do whatever you want with the file

lock.release();

其他提示

  1. You could try lock() with blocking, and trylock() without blocking
  2. FileLock does not work on FileInputStream.
  3. In Android, FileLock works between processes, but does not work between threads in a process.

FileLock does work on FileInputStream BUT only if acquired as a shared lock.

  FileInputStream fis = new FileInputStream(file + ext);
  FileChannel fileChannel = fis.getChannel();
  FileLock fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, /*shared*/true);

Actually this makes sense. Shared lock means that there could be any number of simultaneous readers, but no writers allowed. While default exclusive lock gives process exclusive access to writing. As you can't write with FileInputStream, you have to acquire shared lock on it.

I think file locking works on "internal" phone memory but doesn't work on SD card.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top