I have an Android Service
running daily which does some data synchronization. Once a day it downloads a file and caches it to disk via context.openFileOutput
:
String fileName = Uri.parse(url).getLastPathSegment();
try (FileOutputStream outputStream =
context.openFileOutput(fileName, Context.MODE_PRIVATE)) {
outputStream.write(bytes);
// ...
} catch (IOException e) {
// logging ...
}
This happens on a background thread.
I also have a UI which contains a WebView
. The WebView
uses those cached resources if they are available via context.openFileInput
:
@Override
public WebResourceResponse shouldInterceptRequest(
WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (shouldUseCache(url)) {
try {
return new WebResourceResponse(
"video/webm",
Charsets.UTF_8.name(),
context.openFileInput(obtainFileName(url)));
} catch (IOException e) {
// If a cached resource fails to load, just let the WebView load it the normal way.
// logging ...
}
}
return super.shouldInterceptRequest(view, request);
}
This happens on another background thread independently from the service.
Can I rely on Context
implementation and be sure that file reads and writes are safe, or do I have to take care of the synchronization myself?
E.g. if the Service
is currently writing data to a file and the WebView
is trying to access it, will I run into a problem? If so, how should I implement the synchronization?
shouldInterceptRequest
is actually called by the web view, so it will work independently from the file observer so I don't see how it's going to help.. Regarding the lock, are you saying that I do need to implement synchronization, i.e. it's not synchronized already when I callcontext.openFileInput
? if so, how do I share the lock if those are two different background threads? One in a service and one in a web view. This seems very complicated and I still hope that the synchronization is actually implemented by Android for me. – FrazzleFileInputStream
andFileOutputStream
objects (See ContextImpl). So you are reliant upon the OS handling the locking of the files. As a result I'd be cautious and manually do the file locking. You could look atFileChannel
(accessible fromFileInputStream
andFileOutputStream
) andFileLock
, perhaps they are sufficient. – Record