0

I'm having some issues with my callbacks. Here is my code:

Activity:

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();
}

Manager:

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");
    }
}

Service:

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();
}

My callbacks get notified but I run into this when it try to set the textview text:

E/JavaBinder﹕ * Uncaught remote exception! (Exceptions are not yet supported across processes.) android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

iGio90
  • 3,251
  • 7
  • 30
  • 43

1 Answers1

0

Like the error message says, you try to update a View from the wrong Thread. As the fire() method is called from the remote Service that runs in another Thread, you need to make sure, that the code that updates the UI runs in the UI Thread. To achieve this, try the following:

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");
        }
    })
}
tknell
  • 9,007
  • 3
  • 24
  • 28
  • what if i'm not running it inside an activity? – iGio90 Jun 26 '14 at 12:36
  • 1
    Depends on where you run it. If you are inside a Fragment you can call `getActivity.runOnUiThread()`, if you are inside of another component, you might need to pass your activity to it or provide a callback to your activity that runs the code inside the UI Thread. If you don't need to update your UI, you don't neccessarily need to run the code in the UI Thread. – tknell Jun 26 '14 at 13:22