cordova 3.0 FileWriter THREAD WARNING:exec()调用File.write阻塞主线程...应该使用CordovaInterface.getThreadPool()

时间:2013-08-09 04:08:41

标签: android cordova threadpool filewriter

我正在使用FileWriter,当我编写各种大小大约3MB的大文件时,除了logcat中的这些消息之外它工作正常。

我查看了FileUtils.java源代码,而write函数没有使用getThreadPool()接口(读者会这样做)。

作为测试,我认为我会调整文件编写器以使用runnable接口,并且能够获取编译和执行的代码 - 遗憾的是,logcat消息仍然显示...

到目前为止,我得到的阻塞时间是25ms到1200ms之间的任何时间。我没有运行任何严肃的比较测试来确定这种变化是否有任何真正的区别 - 我只是在寻找没有logcat消息。

以下这些变化是否会产生任何真正的差异?

这些消息是我应该担心的吗?

我的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 :(得分:0)

是的,这些消息很重要,您应该使用后台线程来处理复杂的任务,例如文件写入。这个问题的原因是这些任务阻止了cordova,你可能会遇到例如UI滞后。

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