我有我的回调一些问题。这里是我的代码:
活动:
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:只有创建视图层次可以触摸其观点原来的线程。
像错误消息说,您尝试更新从错误的线程视图。由于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");
}
})
}