【发布时间】:2020-01-31 11:04:38
【问题描述】:
我正在尝试使用以下软件包 https://github.com/arrrrny/tesseract_ocr 在 Flutter 中使用 Tesseract
我已经下载了应用并运行了。
问题是 extractText 挂起 UI。
看Java代码:
Thread t = new Thread(new Runnable() {
public void run() {
baseApi.setImage(tempFile);
recognizedText[0] = baseApi.getUTF8Text();
baseApi.end();
}
});
t.start();
try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); }
result.success(recognizedText[0]);
我可以看到它正在一个新线程上运行,所以我希望它不会挂起应用程序,但它仍然会挂起。
我找到了这个例子:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Call the desired channel message here.
baseApi.setImage(tempFile);
recognizedText[0] = baseApi.getHOCRText(0);
baseApi.end();
result.success(recognizedText[0]);
}
});
但它也会挂起 UI。
文档也说
**Channels and Platform Threading**
Invoke all channel methods on the platform’s main thread when writing code on the platform side.
有人能澄清一下这句话吗?
根据Richard Heap的回答,我尝试从native调用一个方法到dart,传递结果:
飞镖方面:
_channel.setMethodCallHandler((call) {
print(call);
switch (call.method) {
case "extractTextResult":
final String result = call.arguments;
print(result);
}
var t;
return t;
});
Java端:
channel.invokeMethod("extractTextResult","hello");
如果我从主线程调用这个方法,这工作正常,但线程阻塞。
如果我这样做
Thread t = new Thread(new Runnable() {
public void run() {
channel.invokeMethod("extractTextResult","test1231231");
}
});
t.start();
result.success("tst"); // return immediately
然后应用程序崩溃并显示以下消息:
我也试过了:
Thread t = new Thread(new Runnable() {
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Call the desired channel message here.
baseApi.setImage(tempFile);
recognizedText[0] = baseApi.getHOCRText(0);
baseApi.end();
result.success(recognizedText[0]);
// channel.invokeMethod("extractTextResult", "test1231231");
}
});
}
});
t.start();
result.success("tst");
这就是我理解 Richard Heap 最后评论的意思,但它仍然挂起 ui。
【问题讨论】: