Android Dev Summit, October 23-24: two days of technical content, directly from the Android team. Sign-up for livestream updates.

CallbackReceiver

interface CallbackReceiver<T : Any!>
androidx.remotecallback.CallbackReceiver

An objects that can receive remote callbacks.

Remote callbacks provide an easy way to bundle arguments and pass them directly into a method rather than managing PendingIntents manually.

Example:

public class MyReceiver extends BroadcastReceiverWithCallbacks {
    public PendingIntent getPendingIntent(Context context, int value1, int value2) {
      return createRemoteCallback().doMyAction(value1, value2)
          .toPendingIntent(context);
    }
 
    \@RemoteCallable
    public MyReceiver doMyAction(int value1, int value2) {
      ...
      return this;
    }
  }

The following types are supported as parameter types for methods tagged with RemoteCallable.

  • byte/Byte/byte[]
  • char/Character/char[]
  • short/Short/short[]
  • int/Integer/int[]
  • long/Long/long[]
  • float/Float/float[]
  • double/Double/double[]
  • boolean/Boolean/boolean[]
  • String/String[]
  • Uri
  • Context *
* Context is a special kind of parameter, in that it cannot be specified during createRemoteCallback, it instead is passed directly through to provide a valid context at the time of the callback in case no other one is available.

This interface shouldn't be implemented in apps, instead extend one of the implementations of it provided.

Just like PendingIntents, Remote Callbacks don't require components be exported. They also ensure that all parameters always have a value in the PendingIntent generated, which ensures that the caller cannot inject new values except when explicitly requested by the receiving app. They also generate the intent Uris to ensure that the callbacks stay separate and don't collide with each other.

Summary

Public methods

abstract T

Creates a RemoteCallback that will call the method with method specified with the arguments specified when triggered.

Public methods

createRemoteCallback

abstract fun createRemoteCallback(context: Context!): T

Creates a RemoteCallback that will call the method with method specified with the arguments specified when triggered. Only methods tagged with RemoteCallable can be used here. This method returns a stub implementation of the class calling it to record the arguments/method being used. This should only be used in a chain of 2 calls, starting with createRemoteCallback(), then followed up with a call to any method tagged with RemoteCallable.

createRemoteCallback().callMyMethod("My arguments", 43, 2.4)
                   .toPendingIntent(context);
      
\@RemoteCallable
          public RemoteCallback callMyMethod(String argStr, int argInt, double argDouble) {
              ...
              return RemoteCallback.LOCAL;
          }