我的回调有些问题。这是我的代码:
的活动:
private ICallback callback = new ICallback.Stub() {
@Override
public void fire() throws RemoteException {
mTextView.setText("fired");
}
};
//then in onCreate i add:
mManger.registerCallback(callback);
ICallback(AIDL)
interface ICallback {
void fire();
}
管理器:
public void registerCallback(ICallback callback) {
try {
mService.registerCallback(callback);
} catch (RemoteException e) {
Log.e(TAG, "Service is dead");
}
}
private void notifyCallbacks() {
try {
mService.notifyCallbacks();
} catch (RemoteException e) {
Log.e(TAG, "Service is dead");
}
}
服务:
public void registerCallback(ICallback callback) {
if (callback != null) {
mCallbacks.register(callback);
}
}
public void notifyCallbacks() {
final int N = mCallbacks.beginBroadcast();
for (int i=0;i<N;i++) {
try {
mCallbacks.getBroadcastItem(i).fire();
} catch (RemoteException e) {
}
}
mCallbacks.finishBroadcast();
}
我的回调会收到通知,但在尝试设置textview文本时遇到此问题:
E / JavaBinder: * 未捕获的远程异常! (例外还没有 跨进程支持。) android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。
答案 0 :(得分:0)
与错误消息一样,您尝试从错误的线程更新View。当从在另一个线程中运行的远程服务调用fire()
方法时,您需要确保更新UI的代码在UI线程中运行。要实现此目的,请尝试以下操作:
public void fire() throws RemoteException {
//the activity provides this method to be able to run code in the UI Thread
runOnUiThread(new Runnable(){
@Override
public void run(){
mTextView.setText("fired");
}
})
}