我在 android 的 webview 中使用 geo-location 特征。使用 javascript (onload) 來調用Android 方法:
public void getLocation() {
_context.getLocation();
}
當程序執行到以下的位置時:
public void locationUpdated(Location location) {
NumberFormat frm = NumberFormat.getNumberInstance(new Locale("en_US"));
// call javascript function
webView.loadUrl("javascript:locationChangedHandler(" + frm.format (location.getLatitude()) + "," + frm.format(location.getLongitude()) + ")");
}
獲得以下的異常:
03-10 01:17:06.262: ERROR/AndroidRuntime(659): FATAL EXCEPTION: Timer-1
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
at android.view.View.invalidate(View.java:5139)
at android.view.View.onFocusChanged(View.java:2664)
at android.widget.TextView.onFocusChanged(TextView.java:6469)
at android.widget.AutoCompleteTextView.onFocusChanged(AutoCompleteTextView.java:1048)
at android.webkit.WebTextView.onFocusChanged(WebTextView.java:357)
at android.view.View.clearFocusForRemoval(View.java:2577)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:2188)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:2181)
at android.view.ViewGroup.removeView(ViewGroup.java:2129)
at android.webkit.WebTextView.remove(WebTextView.java:583)
at android.webkit.WebView.clearTextEntry(WebView.java:1830)
at android.webkit.WebView.loadUrl(WebView.java:1542)
at android.webkit.WebView.loadUrl(WebView.java:1553)
at com.binus.MainView$1.gotLocation(MainView.java:33)
at com.binus.GeoLocation$GetLastLocation.run(GeoLocation.java:88)
at java.util.Timer$TimerImpl.run(Timer.java:289)
有什麼方法可以從其它線程中訪問UI線程?使用非UI線程上執行的 javascript (onload) 來調用Android方法嗎?
如何使我的代碼線程安全?
如果是在一個 View 中使用 post:
public void locationUpdated(final Location location) {
post(new Runnable() {
@Override
public void run() {
webView.loadUrl(...);
}
});
}
如果是在一個 Activity 中,把 post 換成 runOnUiThread。