判断当前线程是否为主线程

1
Looper.myLooper() == Looper.getMainLooper()

在主线程中执行代码

1
2
3
4
5
6
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// ...
}
});

Tips:

1 . @JavascriptInterface 注解下的函数调用,执行线程并非主线程,而是 JavaBridge 线程。如果在此处执行 webView.loadUrl 以期望对 JS 回调的话,是不行的,会爆出如下错误;正确的方式应该是在主线程中执行 webView.loadUrl

Caused by: java.lang.Throwable: A WebView method was called on thread ‘JavaBridge’. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {31303094} called on Looper (JavaBridge, tid 20613) {2e893026}, FYI main Looper is Looper (main, tid 1) {31303094})