[英]React Native Android Bridge Error: Must be called on main thread
I am using the Sumup SDK to create a bridge to React Native.我正在使用 Sumup SDK 创建到 React Native 的桥梁。 Most of the hard work is done but I am trying to call a specific function to wake up the card reader before a transaction is processed.
大多数艰苦的工作已经完成,但我试图在处理交易之前调用一个特定的函数来唤醒读卡器。
The original code I had was this:我的原始代码是这样的:
@ReactMethod
public void prepareCardTerminal() {
SumUpAPI.prepareForCheckout();
}
}
The RN bridge then calls this function like this: RN 网桥然后像这样调用这个函数:
static prepareCardTerminal() {
NativeRNSumup.prepareCardTerminal();
}
How ever this gives me a React Native error of:这如何给我一个 React Native 错误:
Must be called on main thread
I read that this could mean it needs to be run on the UI thread so I rewrote the function to be:我读到这可能意味着它需要在 UI 线程上运行,所以我将函数重写为:
@ReactMethod
public void prepareCardTerminal() {
new Thread(new Runnable() {
public void run() {
SumUpAPI.prepareForCheckout();
}
});
}
However this doesn't have the intended results (even though it doesn't show any errors).然而,这没有预期的结果(即使它没有显示任何错误)。
Any tips would be much appreciated.任何提示将不胜感激。
Edit: I found a solution to this issue.编辑:我找到了解决此问题的方法。 I used UiThreadUtil:
我使用了 UiThreadUtil:
import com.facebook.react.bridge.UiThreadUtil;
...
@ReactMethod
public void prepareCardTerminal() {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
SumUpAPI.prepareForCheckout();
}
});
}
You can do something like this:你可以这样做:
@ReactMethod
public void prepareCardTerminal() {
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
SumUpAPI.prepareForCheckout();
}
};
mainHandler.post(myRunnable);
}
Or even simpler:或者更简单:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
SumUpAPI.prepareForCheckout();
}
});
The answer posted as an edit to the question is correct.作为对问题的编辑发布的答案是正确的。 The answer by @waquar-ulhaq is technically correct but using
UiThreadUtil
is way simpler and internally does use a Handler
@waquar-ulhaq的答案在技术上是正确的,但使用
UiThreadUtil
更简单,并且在内部确实使用了Handler
import com.facebook.react.bridge.UiThreadUtil;
...
@ReactMethod
public void prepareCardTerminal() {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
SumUpAPI.prepareForCheckout();
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.