Follow

Set Up Push Notifications

Set Up Push Notifications

To set up push notifications, you need to enable push. You can also perform optional steps if you want the SDK to notify you when your application receives a push notification sent from Kahuna or you if want to set custom push notification icons.

See Before You Begin for an overview of push notifications with Kahuna.

Enable Push Notifications

Follow the appropriate steps below.

If you are not using Firebase Cloud Messaging

Follow the steps below to create a Google Firebase project, add your app to that project, and obtain the Firebase Cloud Messaging Server Key.

To enable push notifications:

  1. Create a project in Firebase (see https://console.firebase.google.com), then follow the instructions in the console to add your app to the project. Download the google-services.json and copy it to the root folder in your app.

  2. Add the following to your app's gradle file:

    compile 'com.google.firebase:firebase-messaging:10.0.1'
  3. Add the Firebase Cloud Messaging Server key to your account. (To obtain the key, view the Cloud Messaging tab in your Firebase project settings.)

    1. In the Kahuna application, click on the top bar, then click Settings to open the Settings page.
    2. Scroll down to the Push Authorization section.
    3. In the Android GCM/FCM Server Key field, enter the Firebase Cloud Messaging Server key.
    4. Click Test and Save GCM/FCM Key.
  4. Update your manifest for push.

    Push requires a few receivers and services to function properly. The following is a sample manifest file which has push notifications enabled. This sample manifest serves as a guide. You must update or change the tags in the Modification and Required areas.

    Note: Improper permission settings in your manifest might prevent your application from obtaining a device token to which Kahuna can push.

    <!-- REQUIRED: Kahuna's push requires the receivers and service →
    
    <receiver android:name="com.kahuna.sdk.KahunaCoreReceiver" />
    <service
       android:name="com.kahuna.sdk.KahunaInstanceIDListenerService">
       <intent-filter>
           <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
       </intent-filter>
    </service>
    <service
       android:name="com.kahuna.sdk.KahunaFcmListenerService">
       <intent-filter>
           <action android:name="com.google.firebase.MESSAGING_EVENT" />
       </intent-filter>
    </service>
    <!-- Below is for custom push receiver -->
    <receiver android:name="[CUSTOM_PUSH_RECEIVER_REFERENCE]" />
    
    <!-- END NEW KAHUNA -->
  5. To support push notifications in your application, incorporate the following line into your Main Application class and replace YOUR_SENDER_ID with your API project number from step 1 above.

    public class SampleApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            Kahuna.getInstance().onAppCreate(this, "KAHUNA_SECRET_KEY", "YOUR_SENDER_ID");
            // Your Code Here
        }
    
    }
If you already use Firebase Cloud Messaging

Kahuna provides two options:

Option 1: You are the main service that processes tokens and messages from Firebase.

Option 2: Kahuna is the main service that processes tokens and messages from Firebase.

Choose the option that best suits your needs.

Option 1: You are the main service that processes tokens and messages from Firebase.

If you have already configured services to handle the com.google.firebase.INSTANCE_ID_EVENT and the com.google.firebase.MESSAGING_EVENT actions with your own classes (that extend the FirebaseMessagingService and FirebaseInstanceIdService classes), follow these steps.

  1. In the class that extends FirebaseMessagingService, call the Kahuna SDK to forward the RemoteMessage call you receive from Firebase.

    Note: The SDK checks for specific identifiers that indicate that the message is from Kahuna. When you forward the RemoteMessage call, Kahuna only processes the message if it is unique to Kahuna.

    public class MyFcmListenerService extends FirebaseMessagingService {
    
       @Override
       public void onMessageReceived(RemoteMessage message){
    	//process message if necessary and then pass it on to Kahuna
           Kahuna.getInstance().handlePushMessageReceived(message);
       }
    
    }
  2. In the class that extends FirebaseInstanceIdService, call the Kahuna SDK to forward the token you receive from Firebase.

    Note: It is critical that you forward the token to Kahuna, otherwise Kahuna push notifications will not work.

    public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
       /**
        * Called if InstanceID token is updated. This might occur if the security of
        * the previous token had been compromised. Note that this is also called
        * when the InstanceID token is initially generated, so this is where
        * you retrieve the token.
        */
       @Override
       public void onTokenRefresh() {
           // Get updated InstanceID token.
           String refreshedToken = FirebaseInstanceId.getInstance().getToken();
           Kahuna.getInstance().setPushToken(refreshedToken);
    
       }
    
    }

Option 2: Kahuna is the main service that processes tokens and messages from Firebase.

To configure Kahuna to be the primary handler of push messages within your app (to obtain tokens and receive push notifications), change the service name to point to the Kahuna SDK and add the Kahuna receiver to your AndroidManifest.xml file.

Your AndroidManifest.xml file contains code similar to the following (as required for Firebase Cloud Messaging):

<service
   android:name="com.mycompany.MyFirebaseInstanceIDService">
   <intent-filter>
       <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
   </intent-filter>
</service>
<service
   android:name="com.mycompany.MyFirebaseMessagingService">
   <intent-filter>
       <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>
  1. Change the service name to point to the Kahuna SDK:
    <service
       android:name="com.kahuna.sdk.KahunaInstanceIDListenerService">
       <intent-filter>
           <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
       </intent-filter>
    </service>
    <service
       android:name="com.kahuna.sdk.KahunaFcmListenerService">
       <intent-filter>
           <action android:name="com.google.firebase.MESSAGING_EVENT" />
       </intent-filter>
    </service>
  2. Add the Kahuna receiver:
    <receiver android:name="com.kahuna.sdk.KahunaCoreReceiver" />
    <service
       android:name="com.kahuna.sdk.KahunaInstanceIDListenerService">
       <intent-filter>
           <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
       </intent-filter>
    </service>
    <service
       android:name="com.kahuna.sdk.KahunaFcmListenerService">
       <intent-filter>
           <action android:name="com.google.firebase.MESSAGING_EVENT" />
       </intent-filter>
    </service>

If you want to continue to track push tokens in your system, you can obtain the push token from the Kahuna SDK. Make the following call to obtain the push token after you initialize the Kahuna SDK.

 Kahuna.getInstance().onAppCreate(this, "KAHUNA_SECRET_KEY", "YOUR_SENDER_ID");
String token = Kahuna.getInstance().getPushToken();

After you obtain the push token, you can send the token to your servers to be stored.

Android O Notification Channels

If your app is targeting Android O (8.0) and higher, add one or more Notification Channels to display notifications to your users.

				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
				addNotificationChannel("transactional", "Messages", "Transactional notifications", false);
				addNotificationChannel("marketing", "Promotional", "Promotional Notifications", true);
			}

The addNotificationChannel routine creates, customizes and registers a NotificationChannel with Android and Kahuna
You should write your Notification Channel code to meet your organization's requirements. The following code can be used as a guideline.

				private void addNotificationChannel(String channelName, String channelNameUserFacing, String channelDescription, boolean defaultChannel) {
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				// The id of the channel.
				String id = channelName;
				// The user-visible name of the channel.
				CharSequence name = channelNameUserFacing;
				// The user-visible description of the channel.
				String description = channelDescription;
				int importance = NotificationManager.IMPORTANCE_HIGH;
				NotificationChannel mChannel = new NotificationChannel(id, name, importance);
				// Configure the notification channel.
				mChannel.setDescription(description);
				mChannel.enableLights(true);
				mChannel.setLockscreenVisibility(VISIBILITY_PUBLIC);
				// Sets the notification light color for notifications posted to this
				// channel, if the device supports this feature.
				mChannel.setLightColor(Color.RED);
				mChannel.enableVibration(true);
				mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
				// This is the important part for working on Android 8.0 and higher
				mNotificationManager.createNotificationChannel(mChannel);
				Kahuna.getInstance().addPushNotificationChannel(mChannel.getId(), defaultChannel);
			}

Optional - Receive Broadcast

The SDK can notify you if your application receives a push notification sent from Kahuna. You can even pass extra parameters to your own application and receive them from a Broadcast.

  1. Implement a Broadcast Receiver and set that class in the SDK as shown below.

    public class SampleReceiver extends BroadcastReceiver {
    
        private static final String LOG_TAG = "PushSample";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(Kahuna.ACTION_PUSH_CLICKED.equals(action)){
                /* Push notification was clicked. */
                Bundle extras = intent.getBundleExtra(Kahuna.EXTRA_LANDING_DICTIONARY_ID);
                if(extras != null) {
                    // Make sure to check all values in case you receive pushes
                    // without any parameters
                    String value = extras.getString("YOUR_PARAM_KEY");
                    if(value != null) {
                        Log.i(LOG_TAG, "Received Kahuna push with your value:" + value);
                    }
                }
            }
        }
    
    }

    Note: Decide what custom params (if any) your app will support and add any error handling logic in case a push you receive does not contain any extra parameters.

    Note: If the push message alert field is an empty string, this is a ghost push and should be ignored.

    Important: To determine app uninstalls, Kahuna sends all your users a ghost push on a daily basis. However, your push receiver also receives these ghost pushes (empty messages). If you have set up your push receiver to contact your server to log the receipt of any message (regular or ghost), the server might see large daily spikes of activity. Kahuna recommends you filter out ghost push messages and not log them to your server.

  2. Add your receiver to your manifest. Follow the example below, and replace the Kahuna sample package and receiver name with your own package and receiver name.

    <receiver android:name="com.kahuna.sample.SampleReceiver" />
  3. Register your receiver in your Main Application class right after you call onAppCreate().

    Kahuna.getInstance().onAppCreate(this, "KAHUNA_SECRET_KEY", "YOUR_SENDER_ID");
    Kahuna.getInstance().setPushReceiver(SampleReceiver.class);

Optional - Get Push Token or Disable Push

Push is controlled entirely by the application. Kahuna recommends that your application expose a setting to the user to enable and disable push notifications depending on their preferences. Push is enabled by default. To disable push, add the following code after calling onAppCreate().

Kahuna.getInstance().disablePush();

To obtain the push token for the device, use the following method call.

Kahuna.getInstance().getPushToken();

You can call this method as soon as your Main Activity starts. Because the push token can change over time, you need to call the method every time your app launches. For example, the token has the value null if you disable push notifications.

In the Android operating system, each app controls push notifications. You can design your Android app to allow each user the choice of receiving or blocking push notifications, independent of other apps on the device. The Kahuna SDK provides several ways to query, enable, or disable push notifications, which allows you to provide a push toggle control in your app. By default, the SDK enables push notifications.

The following API call returns the state of push enabling.

Kahuna.getInstance().getIsPushEnabled();

The following API calls disable and enable push notifications in the SDK.

Kahuna.getInstance().disablePush();
Kahuna.getInstance().enablePush();

After you turn off push notifications, you need to enable them again before the device receives them. The SDK automatically stores the state of push enabling so that you do not have to save the state when your app goes into the background or restore the state when your app comes back to the foreground.

Note: Because Android expects each app to handle push notifications, the Kahuna APIs only control push notifications sent by Kahuna. Your app must handle push enabling separately for each third-party system that sends push notifications.

Optional - Set Custom Push Notification Icons

By default, Android push messages use your app's icon as both the small and large icons when showing notifications. However, you can change the notification icons with the SDK as shown below:

Kahuna.getInstance().onAppCreate(this, "KAHUNA_SECRET_KEY", "YOUR_SENDER_ID");
Kahuna.getInstance().setPushNotificationLargeIconResourceId(R.drawable.PUSH_ICON_LARGE);
Kahuna.getInstance().setPushNotificationSmallIconResourceId(R.drawable.PUSH_ICON_SMALL);

After you complete these steps, your team has a robust push notification delivery system capable of targeting key groups of users. Now, follow the steps in Set Up In-App Messaging.

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments