Using ResultReceiver in Android

AndroidServiceCallbackAndroid Activity

Android Problem Overview


Fundamentally, I would like to establish a callback to an Activity from an IntentService. My question is very similar to the one answered here:

https://stackoverflow.com/questions/3197335/android-restful-api-service

However, in the answer code, the activity code is seen as implementing a ResultReceiver. Unless I'm missing something, ResultReceiver is actually a class, so it cannot perform this implementation.

So essentially, I'm asking what would be the correct way to wire up a ResultReceiver to that service. I get confused with Handler and ResultReceiver concepts with respect to this. Any working sample code would be appreciated.

Android Solutions


Solution 1 - Android

  1. You need to make custom resultreceiver class extended from ResultReceiver

  2. then implements the resultreceiver interface in your activity

  3. Pass custom resultreceiver object to intentService and in intentservice just fetch the receiver object and call receiver.send() function to send anything to the calling activity in Bundle object.

    here is customResultReceiver class :

     public class MyResultReceiver extends ResultReceiver {
     
        private Receiver mReceiver;
     
        public MyResultReceiver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }
     
        public interface Receiver {
            public void onReceiveResult(int resultCode, Bundle resultData);
     
        }
     
        public void setReceiver(Receiver receiver) {
            mReceiver = receiver;
        }
     
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
     
            if (mReceiver != null) {
                mReceiver.onReceiveResult(resultCode, resultData);
            }
        }
     
    }
    

implements the Myresultreceiver.receiver interface in you activity, create a class variable

Public MyResultReceiver mReceiver;

initialize this variable in onCreate:

mReceiver = new MyResultReceiver(new Handler());
	 
mReceiver.setReceiver(this);

Pass this mReceiver to the intentService via:

intent.putExtra("receiverTag", mReceiver);

and fetch in IntentService like:

ResultReceiver rec = intent.getParcelableExtra("receiverTag");

and send anything to activity using rec as:

Bundle b=new Bundle();
rec.send(0, b);

this will be received in onReceiveResult of the activity. You can view complete code at:IntentService: Providing data back to Activity

Edit: You should call setReceiver(this) in onResume and setReceiver(null) in onPause() to avoid leaks.

Solution 2 - Android

You override a method by subclassing. It doesn't have to be an interface to do that.

For example:

intent.putExtra(StockService.REQUEST_RECEIVER_EXTRA, new ResultReceiver(null) {
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        if (resultCode == StockService.RESULT_ID_QUOTE) {
            ...
        }
    }
});

Solution 3 - Android

I have created a simple example that demonstrates how to use ResultReceiver.

MainActivity:

public class MainActivity extends AppCompatActivity {

    private final static String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent serviceIntent = new Intent(this, MyService.class);
        serviceIntent.putExtra("logName", "MAIN_ACTIVITY");
        serviceIntent.putExtra(MyService.BUNDLED_LISTENER, new ResultReceiver(new Handler()) {
            @Override
            protected void onReceiveResult(int resultCode, Bundle resultData) {
                super.onReceiveResult(resultCode, resultData);

                if (resultCode == Activity.RESULT_OK) {
                    String val = resultData.getString("value");
                    Log.i(TAG, "++++++++++++RESULT_OK+++++++++++ [" + val + "]");
                } else {
                    Log.i(TAG, "+++++++++++++RESULT_NOT_OK++++++++++++");
                }
            }
        });
        startService(serviceIntent);
    }
}

MyService:

public class MyService extends Service {

    private final static String TAG = MyService.class.getSimpleName();
    public final static String BUNDLED_LISTENER = "listener";

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String logName = intent.getStringExtra("logName");
        ResultReceiver receiver = intent.getParcelableExtra(MyService.BUNDLED_LISTENER);

        Bundle bundle = new Bundle();
        bundle.putString("value", "30");
        receiver.send(Activity.RESULT_OK, bundle);
        return Service.START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

Solution 4 - Android

for use Resulteceiver in android

  1. Create SomeResultReceiver extends from resultReceiver

  2. Create interface someReceiver with on method for example onReceivResult(int resultCode,Bundle resultData);

3.use someReceiver in someResultreceiver

  1. create someService extends IntentService and use someresultReceiver.send() method for send result from service to someOne class (ex: MyActivity)

  2. Implement somereceiver on Activity

6.instantiation someResultReceiver in MyActivity class and setreceiver

  1. startService with Intent and putExtra someResultreceiver instanse

for more details ResultReceiver Class see enter link description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBill EisenhauerView Question on Stackoverflow
Solution 1 - AndroidSohailAzizView Answer on Stackoverflow
Solution 2 - AndroidEric Bowman - abstracto -View Answer on Stackoverflow
Solution 3 - Androiduser2121View Answer on Stackoverflow
Solution 4 - AndroidMehdi AbbaspourView Answer on Stackoverflow