jjzjj

android - cordova 3.0 FileWriter THREAD WARNING : exec() call to File. write blocked the main thread...应该使用 CordovaInterface.getThreadPool()

coder 2023-12-06 原文

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

我查看了 FileUtils.java 源代码,写入函数不使用 getThreadPool() 接口(interface)(读者使用)。

作为测试,我想我应该调整文件编写器以使用可运行的接口(interface),并且能够让代码编译和执行——不幸的是,logcat 消息仍然显示...

到目前为止,我得到的阻塞时间在 25 毫秒到 1200 毫秒之间。我没有运行任何认真的比较测试来确定此更改是否有任何真正的区别 - 我只是在寻找是否缺少 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));
        }
    }
});

最佳答案

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

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

关于android - cordova 3.0 FileWriter THREAD WARNING : exec() call to File. write blocked the main thread...应该使用 CordovaInterface.getThreadPool(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18139898/

有关android - cordova 3.0 FileWriter THREAD WARNING : exec() call to File. write blocked the main thread...应该使用 CordovaInterface.getThreadPool()的更多相关文章

随机推荐