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?
from Synchronization between Context.openFileInput and Context.openFileOutput
No comments:
Post a Comment