Gen*_*kin 7 java android synchronization caching android-webview
我有一个Service每天运行的Android ,可以进行一些数据同步.每天一次下载文件并通过context.openFileOutput以下方式将其缓存到磁盘:
String fileName = Uri.parse(url).getLastPathSegment();
try (FileOutputStream outputStream =
     context.openFileOutput(fileName, Context.MODE_PRIVATE)) {
   outputStream.write(bytes);
   // ...
} catch (IOException e) {
   // logging ...
}
Run Code Online (Sandbox Code Playgroud)
这发生在后台线程上.我也有一个包含一个的UI WebView.在WebView使用它们是否可用通过这些缓存的资源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);
}
Run Code Online (Sandbox Code Playgroud)
这发生在独立于服务的另一个后台线程上.
我可以依赖Context实现并确保文件读写是安全的,还是我必须自己处理同步?例如,如果Service当前正在将数据写入文件并且WebView正在尝试访问它,我是否会遇到问题?如果是这样,我该如何实现同步?
如果服务当前正在将数据写入文件并且 WebView 正在尝试访问它,我会遇到问题吗?
在这种情况下,您可以通过在文件名中附加某些内容并在下载完成后将其名称更改回来将数据写入文件。例如
context.openFileOutput(fileName + ".downloading", Context.MODE_PRIVATE))
下载完成后,将文件重命名为原始fileName. 我确信您检查文件是否存在,shouldUseCache(url)以便它能够继续正常工作。这将避免您尝试读取文件时仍在下载文件的情况。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           199 次  |  
        
|   最近记录:  |