Implement Your Application

Now we will start implementing the initialization logic and the reception handler for push messages.

Adding the initialization code

Please find a sample code block for initialization. In this sample, we are running it when the main activity is created.

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    // Initialize JPush interface
    JPushInterface.init(this);

    // If the id is saved in the preference, it skip the registration and just install push.
    String regId = JPushPreference.getRegistrationId(this.getApplicationContext());
    if (regId.isEmpty()) {
      registerJPush();
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    JPushInterface.onResume(this);
  }

  @Override
  protected void onPause() {
    JPushInterface.onPause(this);
    super.onPause();
  }

  private void registerJPush() {
    JPushInterface.resumePush(this.getApplicationContext());
    final String regId = JPushInterface.getUdid(this.getApplicationContext());
    JPushInterface.setAlias(this.getApplicationContext(), regId, null);

    // login
    String username = "user1";
    String password = "123ABC";
    KiiUser.logIn(new KiiUserCallBack() {
      public void onLoginCompleted(int token, KiiUser user, Exception e) {
        if (e != null) {
          Toast.makeText(MainActivity.this, "Error login: " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
          return;
        }
        // install user device
        boolean development = true;
        KiiUser.pushInstallation(PushBackend.JPUSH, development).install(regId, new KiiPushCallBack() {
          public void onInstallCompleted(int taskId, Exception e) {
            if (e != null) {
              Toast.makeText(MainActivity.this, "Error install: " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
              return;
            }
            // if all succeeded, save registration ID to preference.
            JPushPreference.setRegistrationId(MainActivity.this.getApplicationContext(), regId);
          }
        });
      }
    }, username, password);
  }
  ...
}

To leverage JPush, you need to register the device to the JPush server and get the registration ID.

In the sample code, we first create an interface for calling JPush with the JPushInterface.init() method.

The JPushPreference class in the sample code is the original class for managing the registration ID. The registration ID is reusable, so your application can perform the registration upon the initial launch, save the registration ID obtained in the shared preferences and reuse it thereafter.

The registration is implemented in the registerJPush(). As you can see, we are registering the registration ID with the JPushInterface.getUdid().

For the username and password, specify the Kii Cloud user's information that will be used for testing. For the test user we've created in Create an Android Application, we will specify the username and password as user1 and 123ABC, respectively.

We are initializing the push notification for the development environment in this example. If you are going to build the application for the distribution, set the development to false.

In the above sample code, we assume that the JPushPreference is implemented like below. This piece of code is maintaining the registration ID using the Android's shared preferences:

class JPushPreference {
  private static final String PREFERENCE_NAME = "KiiTest";
  private static final String PROPERTY_REG_ID = "JPushRegId";

  static String getRegistrationId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    return registrationId;
  }

  static void setRegistrationId(Context context, String regId) {
    SharedPreferences prefs = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.commit();
  }
}

Adding the reception handler

When a device receives a JPush push message, the BroadcastReceiver will be executed. This is the class that is defined in the AndroidManifest.xml file.

The push message can be handled with the code like the following. After creating a new class, insert the following code and configure the import.

public class KiiPushBroadcastReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    String jpushMessageType = intent.getAction();
    if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(jpushMessageType)) {
      Bundle extras = intent.getExtras();
      ReceivedMessage message = PushMessageBundleHelper.parse(extras);
      KiiUser sender = message.getSender();
      MessageType type = message.pushMessageType();
      switch (type) {
      case PUSH_TO_APP:
        PushToAppMessage appMsg = (PushToAppMessage)message;
        ...
        break;
      case PUSH_TO_USER:
        PushToUserMessage userMsg = (PushToUserMessage)message;
        ...
        break;
      case DIRECT_PUSH:
        DirectPushMessage directMsg = (DirectPushMessage)message;
        ...
        break;
      }
    }
  }
}

This sample only shows the skeleton. When testing the push feature, add the necessary logics in the section marked with .... For example, you might want to add some logics to print some logs, popup some messages in UI or insert some break points so that you will know that your device successfully received push messages.

This is all for the implementation. Let us more to Send Test Messages to check if the push notification really works.


<< Configure the Manifest File Send Test Messages >>