在我的片段中,我有一个AlertDialog
和一个蓝牙连接管理器。我想用蓝牙连接过程的新状态更新AlertDialog,所以我使用了runOnUiThread(...)
方法:
getActivity().runOnUiThread(new Runnable() {
@Override
void run() {
interactor = new BluetoothInteractor(getActivity(), new OnBluetoothStatusChangedListener() {
@Override
public void OnConnectionStopped() {
alertDialog.setMessage("Disconnected.");
}
@Override
public void OnConnectionStopping() {
alertDialog.setMessage("Stopping connection...");
}
@Override
public void OnConnectionStarting() {
alertDialog.setMessage("Connecting to device...");
}
@Override
public void OnConnectionStarted() {
alertDialog.setMessage("Streaming data...");
}
});
}
});
我第一次更新AlertDialog
消息(OnConnectionStarting
事件)时一切正常,但是第二次我收到android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
这里会发生什么?
答案 0 :(得分:1)
替换为
interactor = new BluetoothInteractor(getActivity(), new OnBluetoothStatusChangedListener() {
@Override
public void OnConnectionStopped() {
getActivity().runOnUiThread(new Runnable() {
@Override
void run() {
alertDialog.setMessage("Disconnected.");
}
});
}
@Override
public void OnConnectionStopping() {
getActivity().runOnUiThread(new Runnable() {
@Override
void run() {
alertDialog.setMessage("Stopping connection...");
}
});
}
@Override
public void OnConnectionStarting() {
getActivity().runOnUiThread(new Runnable() {
@Override
void run() {
alertDialog.setMessage("Connecting to device...");
}
});
}
@Override
public void OnConnectionStarted() {
getActivity().runOnUiThread(new Runnable() {
@Override
void run() {
alertDialog.setMessage("Streaming data...");
}
});
}
});