卡多瓦 3.0 文件写入器 线程警告: exec() 调用 File.write 阻塞了主线程... 应该使用 CordovaInterface.getThreadPool()。

6

我正在使用FileWriter,对于各种大小的较大文件写入时,它运行良好,但日志中会出现以下这些消息。

我查看了FileUtils.java源代码,发现write函数不使用getThreadPool()接口(读取器使用)。

为了测试,我想将filewriter调整为使用runnable接口,并能够使代码编译和执行——不幸的是,日志仍然会显示出来……

迄今为止,我得到的阻塞时间介于25ms和1200ms之间。我没有进行任何严格的比较测试来确定此更改是否有任何真正的区别——我只是在寻找无日志消息。

以下更改是否会产生真正的差异?我应该担心这些消息吗?

我的Java基础知识比较基础——但是这里是我所做的更改——遵循读取器实现。

else if (action.equals("write")) {
    this.write(args.getString(0), args.getString(1), args.getInt(2), args.getBoolean(3), callbackContext);
}
/* this is the original code
else if (action.equals("write")) {
    long fileSize = this.write(args.getString(0), args.getString(1), args.getInt(2), args.getBoolean(3));
    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));

在下面的写函数中...
public void write(String filename, final String data, final int offset, final boolean isBinary, final CallbackContext callbackContext) throws FileNotFoundException, IOException, NoModificationAllowedException {
if (filename.startsWith("content://")) {
    throw new NoModificationAllowedException("Couldn't write to file given its content URI");
}

final String fname = FileHelper.getRealPath(filename, cordova);

this.cordova.getThreadPool().execute(new Runnable() {
    public void run() {
        Log.d(LOG_TAG, "Starting write");
        try {
            boolean append = false;
            byte[] rawData;
            if (isBinary) {
                rawData = Base64.decode(data, Base64.DEFAULT);
            } else {
                rawData = data.getBytes();
            }
            ByteArrayInputStream in = new ByteArrayInputStream(rawData);
            FileOutputStream out = new FileOutputStream(fname, append);
            byte buff[] = new byte[rawData.length];
            in.read(buff, 0, buff.length);
            out.write(buff, 0, rawData.length);
            out.flush();
            out.close();
            Log.d(LOG_TAG, "Ending write");
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, rawData.length));
        } catch (IOException e) {
            Log.d(LOG_TAG, e.getLocalizedMessage());
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
        }
    }
});

}

1个回答

0

是的,这些消息很重要,对于复杂的任务(例如文件写入),您应该使用后台线程。这个问题的原因是这些任务会阻塞 Cordova,您可能会遇到 UI 卡顿等问题。

如果您的下一步操作依赖于此任务完成,我建议您使用回调方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接