我有webview,并且正在使用android中的地理位置功能。
我正在使用JavaScript(加载)调用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()) + ")");
}
有时候我遇到这个例外
04-04 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线程有关吗?
从Javascript调用Android(Java)方法是否在非UI线程上执行?
以及如何使我的代码线程安全?
最佳答案
我不确定您如何离开UI线程,但是要重新使用,可以使用post
:
public void locationUpdated(final Location location) {
post(new Runnable() {
@Override
public void run() {
webView.loadUrl(...);
}
});
}
如果您在
View
中。如果您在Activity
中,则将post
更改为runOnUiThread
。