Push notification

Push notification is a good way to alert users on events or messages even with out app being launched. In Android system, app icon and message will appear in status bar when receiving push notification and when user touch such icon, it will redirect to app it self. Using Kakao Android SDK, you can easily delete and register push token under the circumstance that you have logged in through kakao account If you did not use kakao account to login, you must register push token and delete them with REST API. Following will describe how to set push notification using kakao account login.

Sending push message to users can only be achieved through REST API. You can use SDK to login and send push message for testing.

  • Before getting started: For using kakao push notification, this describe procedures on registering GCM service, kakao push service registration and app settings.
  • Register push token: Describe a way to register push token using by Kakao SDK.
  • Delete push token: Describe a way to delete push token using Kakao SDK.
  • Lookup push token information: If you have registered correct push token in kakao platform service, you can look up token you are using.
  • Receive push notification: Guide on building receiver and service for handling received push notification.
  • Error code: Describe a error code for sending push notification API.

Before getting started

1. Check if login API is set in the app by referring to loginbase template

2. Check if key used in app sign procedure is registered in settings > general > platform > Android > key hash.

Regarding creation of key hash, please follow app creation, step 2.

3. GCM service registration is needed in google developers center.

If application is using push service, and you are trying to migrate current push service to kakao platform service, you can skip following steps.

  • Create project in Google Developers Console and remember Project Number.
  • After selecting the project and set 'Google Cloud Messaging for Android' as 'on' in APIs & auth > APIs
  • Issue API key through APIs & auth > Credentials > Public API access > Create new key > Server key.
    • Leave the allowed IP in blank at this time. Since kakao server sends push message on behalf of yours, you will not be able to send push message if you register your own server IP address .

      For details, refer to GCM Getting Started.

4. kakao push service setting is required in kakao developer center.

Turn on push in setting > push , and set API key, attained from GCM Key, step 3. dev_015.png

5. In order to use API, additional setting must be set.

[kakao_strings.xml]

 <resources>
     <string name="kakao_app_key">AAAAAAAAAAAAAAAAAAAAAA</string>
     <string name="gcm_project_number">111111111111</string>
 </resources>
  • GCM project ID(gcm_project_number) : set Project Number from case 3.

[AndroidManifest.xml]

 <manifest … package="com.kakao.sample.push">    <!-- a. package name -->
     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

     <!-- b. using android:name="{package name}.permission.C2D_MESSAGE" -->
     <permission android:name="com.kakao.sample.push.permission.C2D_MESSAGE"
         android:protectionLevel="signature"/>
     <!-- c. using android:name="{package name}.permission.C2D_MESSAGE" -->
     <uses-permission android:name="com.kakao.sample.push.permission.C2D_MESSAGE"/>

   <application>
        …
         <meta-data android:name="com.google.android.gms.version"
             android:value="@integer/google_play_services_version" />
         <!-- 구현해야 하는 class1 -->
         <receiver
             android:name=".GCMBroadcastReceiver"
             android:permission="com.google.android.c2dm.permission.SEND" >
             <intent-filter>
                 <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                 <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                 <!-- d. android:name="{package name}" 사용 -->
                 <category android:name="com.kakao.sample.push" />
             </intent-filter>
         </receiver>
         <!--Class to be implemented class2 -->
         <service android:name=".GCMIntentService"/>

         <meta-data android:name="com.kakao.sdk.AppKey" android:value="@string/kakao_app_key"/>
         <meta-data android:name="com.kakao.sdk.GcmProjectId" android:value="@string/gcm_project_number"/>
     ...
     </application>
 </manifest>
  • Declare needed permission in order to use GCM. In the case of b. permission and c. uses-permission, match android:name attribute with a. app's package name. In our example, com.kakao.sample.push is being used, and therefore you can change the name with your own app package name.
  • Declare google play service version.
  • Declare receiver to receive push message. In our example, receiver's default descriptor name is GCMBroadcastReceiver and therefore, you must switch with your own. d. /intent-filter/category의 android:name attribute에는 a. 앱의 package 이름과 일치 시켜야 합니다.
  • Declare service in which will deal the received message. In example, the name of descriptor is GCMIntentService. You should change it to your own.
  • Set declared app key and GCM project ID in kakao_strings.xml

For details, refer Implementing GCM Client. For other settings, follow loginbase template's AndroidManifest.xml.

Register push token

In order to receive push notification through application, you must follow steps on registering to GCM server. If registration has succeeded, you can receive registration ID as response. Since registration ID is used for sending messages, it must be given to kakao push service.

For app's using kakao account login, this step can be completed automatically with Android SDK. After login is successful, in the shown Activity, if you extends com.kakao.widget.PushActivity , push token will be registered automatically based on Activity's lifecycle

Since this is based on login, abstract method, redirectLoginActivity() must be implemented. In a case where Activity method override, make sure to not forget about calling super().

In a case where single user using multiple devices, device's unique ID is required beside user's unique ID when registering push token.For appropriate algorithm regarding creation of unique ID, getDeviceUUID() of abstract method, can be used to register push token by device. Beware of the fact that this only support up to 64 characters.

public class PushMainActivity extends PushActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    @Override
    protected void redirectLoginActivity() {
        final Intent intent = new Intent(this, PushLoginActivity.class);
        startActivity(intent);
        finish();
    }

    // Below is an example using SharedPreferencesCache.
    protected String getDeviceUUID() {
        if(deviceUUID != null)
            return deviceUUID;

        final SharedPreferencesCache cache = Session.getAppCache();
        final String id = cache.getString("device_id");

        if (id != null) {
            deviceUUID = id;
            return deviceUUID;
        } else {
            // Create unique ID using appropriate algorithm.
            // For creating unique ID, you must be granted on permission to use user's private information.
            String newDeviceUUID = ...;

            Bundle bundle = new Bundle();
            bundle.putString("device_id", newDeviceUUID);
            cache.save(bundle);

            deviceUUID = newDeviceUUID;
            return deviceUUID;
        }
    }
}

Auto push token registration, completed by com.kakao.widget.PushActivity, is described below. If you must implement this manually due to the fact that you have not logged in with kakao account, refer below.

  1. Look up saved registration ID to check if it has been registered.
  2. After registering in GCM, retrieve registration ID. At this point use project number retrieved from getting started case 3.
  3. Pass Registration ID to kakao open platform push server, which is retrieved from GCM server through rest API.

    In case where you have not logged in with kakao account and have to implement steps using REST API, you must call REST API from the server since you will be using admin key not token it self.

  4. You must save registration ID to make sure that you do not have to re-register in GCM afterwards.

Delete push token

If you wish not to use push token any longer, such as logging out from account or wishing to delete account from app, you must delete push token. Call com.kakao.PushService#deregisterPushToken.

    private void deregisterPushToken() {
        PushService.getInstance().deregisterPushToken(new PushDeregisterHttpResponseHandler() {
            @Override
            protected void onHttpSuccess(Void resultObj) {
                super.onHttpSuccess(resultObj);
                Toast.makeText(getApplicationContext(), "success to deregister push token", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onHttpSessionClosedFailure(APIErrorResult errorResult) {
                redirectLoginActivity();
            }

            @Override
            protected void onHttpFailure(APIErrorResult errorResult) {
                super.onHttpFailure(errorResult);
                Toast.makeText(getApplicationContext(), errorResult.toString(), Toast.LENGTH_LONG).show();
            }
        }, deviceUUID);
    }
Send callback, [PushDeregisterHttpResponseHandler](/docs/android-reference/com/kakao/PushDeregisterHttpResponseHandler.html) as a result of request API using parameter.
* <a href="/docs/android-reference/com/kakao/PushDeregisterHttpResponseHandler.html#onHttpSuccess(java.lang.Void)">onHttpSuccess(T)</a> : This is an API request success example where success toast will be viewed.
* <a href="/docs/android-reference/com/kakao/PushDeregisterHttpResponseHandler.html#onHttpSessionClosedFailure(com.kakao.APIErrorResult)">onHttpSessionClosedFailure(APIErrorResult)</a> : Error will be returned due to session closure. Redirect to login window in our example.
* <a href="/docs/android-reference/com/kakao/PushDeregisterHttpResponseHandler.html#onFailure(com.kakao.APIErrorResult)">onFailure(APIErrorResult)</a> : Will show reasons for failure through toast.For failure due to reasons beside session being closed. Error result will be returned.

<a name="푸시토큰-조회"></a>
#####Push token information lookup
Able to look up on whether push token is registered in kakao platform service or what other push token exists related to current user. User token is needed to use this functionality which can be retrieved after successful login.
Call a <a href="/docs/android-reference/com/kakao/PushService.html#getPushTokens(com.kakao.PushTokensHttpResponseHandler)">com.kakao.PushService#getPushTokens</a>.

Example follows.

```java
    private void getPushTokens() {
            PushService.getInstnace().getPushTokens(new PushTokensHttpResponseHandler<PushTokenInfo[]>() {
                @Override
                protected void onHttpSuccess(PushTokenInfo[] pushTokenInfos) {
                    Toast.makeText(getApplicationContext(), "succeeded to get push tokens." +
                        "\ncount=" + pushTokenInfos.length +
                        "\nstories=" + Arrays.toString(pushTokenInfos), Toast.LENGTH_SHORT).show();
                }

                @Override
                protected void onHttpSessionClosedFailure(APIErrorResult errorResult) {
                    redirectLoginActivity();
                }

                @Override
                protected void onHttpFailure(APIErrorResult errorResult) {
                    Toast.makeText(getApplicationContext(), errorResult.toString(), Toast.LENGTH_LONG).show();
                }
            });
    }

Succession result is provided through SArray, including multiples of PushTokenInfo, and PushTokenInfo의 information is as below.

Elements Type Description
getUserId() String Registered push token user id
getDeviceId() String Registered push token user id
getPushToken() String Registered push token
getPushType() String Push token type. For example, "apns" or "gcm"
getCreatedAt() String Time in which push token was created
getUpdatedAt() String Time in wich push token renewal happened

Receive push notification

In order to receive message, class1, class2, which in this case are GCMBroadcastReceiver and GCMIntentService, declared to be implemented at app setting file, must be implemented.

1.BroadcastReceiver implementation

BroadcastReceiver dealing com.google.android.c2dm.intent.RECEIVE intent must be implemented. Which means,when message is sent, BroadcastReceiver#onReceive() will be called. WakefulBroadcastReceiver is a extended version of BroadcastReceiver, which helps on dealing with message not correctly processed during sleep status of a device. In need of such cases, implement either WakefulBroadcastReceiver or BroadcastReceiver. In our example, we will implement WakefulBroadcastReceiver. Unlike startService, WakefulBroadcastReceiver#startWakefulService need wake lock to start the service. Actual message is processed through GCMIntentService, and when message processing is complete, WakefulBroadcastReceiver#completeWakefulIntent() is called to unlock.

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

2.IntentService Implementation

It's a service for dealing with intent in message received from WakefulBroadcastReceiver. Below is a receiving of a message and showing it in BigTextStyle through notification center. When clicking such, it will be redirected to app. When dealing with message is over, WakefulBroadcastReceiver#completeWakefulIntent() will be called and unlock wake lock which BroadcastReceiver held on to.

public class GcmIntentService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            sendNotification("Received: " + extras.toString());
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notifyIntent = new Intent(this, PushLoginActivity.class);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "put your channel name here")
        .setSmallIcon(R.drawable.push_noti_icon)
        .setContentTitle(getApplicationContext().getString(R.string.push_notification_title))
        .setStyle(new NotificationCompat.BigTextStyle().bigText(message.getData().get("content")))
        .setContentText(message.getData().get("content"));

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    }
}

For details, refer Google Open Source Site sample.

Error code


Last Modified : 2018-03-19