Getting the registration identifier

A Registration Identifier (also called Registration Token or Push Token) is, by default, automatically fetched by Batch when starting.

For various reasons, you might want to get this identifier: you might be using another library which requires it, or simply want to handle it on your own.

There are two ways to accomplish this.

Listening to the broadcast

Batch will broadcast a message to your application when a registration identifier is fetched, whether it changed or not.

As any standard broadcast receiver, you can either register it in your manifest, or at runtime.

Example receiver implementation

  • Kotlin
  • Java
class MyTokenReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent != null) {
            val provider = intent.getStringExtra(Batch.EXTRA_REGISTRATION_PROVIDER_NAME)
            val identifier = intent.getStringExtra(Batch.EXTRA_REGISTRATION_IDENTIFIER)
            Log.i("MyTokenReceiver", "Got registration (from provider $provider): $identifier")
        }
    }
}

Manifest registration

<receiver android:name=".MyTokenReceiver"
    android:permission="${applicationId}.batch.permission.INTERNAL_BROADCAST">
    <intent-filter>
        <action android:name="com.batch.android.intent.action.push.REGISTRATION_IDENTIFIER_OBTAINED" />
    </intent-filter>
</receiver>

Note: ${applicationId} is a Gradle macro, which will automatically be replaced when building

Runtime registration

  • Kotlin
  • Java
class MyApplication: Application() {
    var tokenReceiver = MyTokenReceiver()

    override fun onCreate() {
        super.onCreate()
        // [...]
        registerReceiver(tokenReceiver,
            IntentFilter(Batch.ACTION_REGISTRATION_IDENTIFIER_OBTAINED),
            Batch.getBroadcastPermissionName(this), null)
    }
}

Note: Even though the broadcast is scoped to the current package, it can be protected by a permission so that other apps cannot inject a broadcast into your app.

Pulling the value

If you do not want to setup a listener, but want to simply fetch the registration identifier, you can call Batch.Push.getLastKnownPushToken().

This method will return null if no registration identifier has been fetched or if Batch isn't started, meaning that you have to call this method after Batch.onStart(). It is useful if you want to show the token in your UI, for example in a debug view.