TextView setText() 在错误上下文的回调中调用
TextView setText() called in callbacks from wrong context
我尝试实现网络服务发现并在成功注册后将名称设置到 textView 中。但是我收到 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
异常。我的基本结构如下所示:
NsdManager.RegistrationListener mRegistrationListener;
onCreate() {
mRegistrationListener = new NsdManager.RegistrationListener() {
onServiceRegistered(serviceInfo) {
TextView textView = (TextView) findViewById(R.id.nsdServiceNameText);
textView.setText(serviceInfo.getServiceName());
}
}
mNsdManager = (NsdManager) this.getBaseContext().getSystemService(Context.NSD_SERVICE);
mNsdManager.registerService(
serviceInfo,
NsdManager.PROTOCOL_DNS_SD,
mRegistrationListener);
}
对我来说,我可能在错误的上下文中编辑视图是有道理的,但我是如何到达那里的,更重要的是我如何解决这个问题?
如果您在此处阅读 NsdManager
的文档:https://developer.android.com/reference/android/net/nsd/NsdManager
上面写着:
The API is asynchronous, and responses to requests from an application
are on listener callbacks on a separate internal thread.
因此它离开了 UI 线程,您应该在该线程中更新您的 UI,正如评论中指出的,如下所示:
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(serviceInfo.getServiceName());
}
});
我尝试实现网络服务发现并在成功注册后将名称设置到 textView 中。但是我收到 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
异常。我的基本结构如下所示:
NsdManager.RegistrationListener mRegistrationListener;
onCreate() {
mRegistrationListener = new NsdManager.RegistrationListener() {
onServiceRegistered(serviceInfo) {
TextView textView = (TextView) findViewById(R.id.nsdServiceNameText);
textView.setText(serviceInfo.getServiceName());
}
}
mNsdManager = (NsdManager) this.getBaseContext().getSystemService(Context.NSD_SERVICE);
mNsdManager.registerService(
serviceInfo,
NsdManager.PROTOCOL_DNS_SD,
mRegistrationListener);
}
对我来说,我可能在错误的上下文中编辑视图是有道理的,但我是如何到达那里的,更重要的是我如何解决这个问题?
如果您在此处阅读 NsdManager
的文档:https://developer.android.com/reference/android/net/nsd/NsdManager
上面写着:
The API is asynchronous, and responses to requests from an application are on listener callbacks on a separate internal thread.
因此它离开了 UI 线程,您应该在该线程中更新您的 UI,正如评论中指出的,如下所示:
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(serviceInfo.getServiceName());
}
});