SimpleSample-messages users-android

Ask tech team
From QuickBlox Developers (API docs, code samples, SDK)
Jump to: navigation, search

Contents

Sources

Project homepage on GIT — https://github.com/QuickBlox/quickblox-android-sdk/tree/master/sample-messages

Download ZIP - https://github.com/QuickBlox/quickblox-android-sdk/archive/master.zip


Overview

This sample demonstrates how to work with QuickBlox Messages (Push Notifications) API.
It allows to send and receive push notifications.

It shows how to:

  1. Subscribe user to start receiving push notifications
  2. Send a push notification to a user


Guide: Get Started with Messages API

Get QuickBlox account

http://admin.quickblox.com/register

Create application on Admin panel

http://admin.quickblox.com/apps/new

Also you can look through 5 min guide.

Connect QuickBlox to your application

To get the information on how to connect to the quickblox.jar, please, refer to the Android-how-to-connect-quickblox-jar page.

Setup GCM

If you want to use Messages module, you need:

  • Create a Google API project. Save project number to your app (in sample this is Consts.PROJECT_NUMBER)
  • Enable the GCM Service
  • Obtain an API Key. Next - put Server API Key to QuickBlox Admin panel, Messages module, Settings tab, Google Cloud Messaging (GCM) API key section. Use the same key for development and production zones.
  • Connect Google Play Services to your project.
  • Setup AndroidManifest.xml and write my_app_package.GCMIntentService class. Just refer to this code sample.

How QuickBlox Push Notifications work

In order to use QuickBlox Messages APIs you must Create a session & Sign In to QuickBlox OR just create a session with a User.

There are 2 ways that you can integrate Push Notifications into your app:

  1. Broadcasting the same message to all users. It's a simple method which can be used in informational apps that do not authenticate users and where same push notification messages are broadcasted to everybody. This way when you want to send a push message you may 1) simply go to Admin panel -> Messages -> type your message in Simple mode -> and hit "Send" for all of your users to receive the message; 2) Send a push using Messages API (explained below). Following this way you only need to create ONE QuickBlox User which will have all of your users' devices associated with it. Then simply send your pushes to that User.
  2. Send individual push alerts. This is when you want to individually send push notifications to a particular user or a group of users (for example notify users of a new chat message sent while they are offline or tell them about some deal/event happening in close proximity to their location). Following this way you need to have a QuickBlox User created for each of your app users. Note that there are easy ways to transparently create QB Users along with your existing users authentication system or have them sign up with Facebook/Twitter/OAuth (described in Users API reference) so your end users don't have to type any additional login credentials or know anything about QuickBlox.

Giving a user a Push Notification subscription

  1. Let's create test User on Admin panel and subscribe it to receive Push Notifications. Go to Users module on Admin panel & press Add new user button:

    AddNewUser.png

    Fill at least login & password fields and press Add user button

    SaveNewUser.png

    Also you can create new User through Users APIs

  2. Create session with user's parameters & subscribe to receive Push Notifications
    Use login & password from previous step
    // Set your QuickBlox application credentials here
    QBSettings.getInstance().fastConfigInit("99", "63ebrp5VZt7qTOv", "YavMAxm5T59-BRw");
     
    //
    // Create quickblox session with user
    QBAuth.createSession("bob", "bob67pass", new QBEntityCallbackImpl<QBSession>() {
        @Override
        public void onSuccess(QBSession session, Bundle params) {
     
            // request registration ID
            /*
                 The checkDevice() method verifies that the device supports GCM  
                 and throws an exception if it does not (for instance, if it is 
                 an emulator that does not contain the Google APIs). Similarly, 
                 the checkManifest() method verifies that the application manifest
                 contains meets all the requirements (this method is only necessary
                 when you are developing the application; once the application is
                 ready to be published, you can remove it).
     
                 Once the sanity checks are done, the device calls 
                 GCMRegsistrar.register() to register the device, passing the 
                 SENDER_ID you got when you signed up for GCM. But since the 
                 GCMRegistrar singleton keeps track of the registration ID upon the 
                 arrival of registration intents, you can call 
                 GCMRegistrar.getRegistrationId() first to check if the device is 
                 already registered.
            */
            //
     
            GCMRegistrar.checkDevice(this);
            GCMRegistrar.checkManifest(this);
     
            final String regId = GCMRegistrar.getRegistrationId(this);
            if (regId.equals("")) {
                GCMRegistrar.register(this,  Consts.GSM_SENDER);
            } else {
                Log.v(LOG_TAG, "Already registered");
     
                // Subscribe to Push Notifications
                subscribeToPushNotifications(regId)
            }
        }
     
        @Override
        public void onError(List<String> errors) {
     
        }
    });
     
    //
    // Subscribe to Push Notifications
    public void subscribeToPushNotifications(String registrationID) {
        String deviceId = ((TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
     
        QBMessages.subscribeToPushNotificationsTask(registrationID, deviceId, QBEnvironment.DEVELOPMENT, new QBEntityCallbackImpl<ArrayList<QBSubscription>>() {
            @Override
            public void onSuccess(ArrayList<QBSubscription> subscriptions, Bundle args) {
                Log.d(LOG_TAG, "subscribed");
            }
     
            @Override
            public void onError(List<String> errors) {
     
            }
        });
    }

    In GCMIntentService:

    @Override
    protected void onRegistered(Context context, final String registrationId) {
     
        // access to your acivity
        if(MessagesActivity.getInstance() != null){
            MessagesActivity.getInstance().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                     MessagesActivity.getInstance().subscribeToPushNotifications(registrationId);
                }
            });
        }
    }

    Note: Use QBEnvironment.DEVELOPMENT while developing application and QBEnvironment.PRODUCTION for application store.

    After that you are ready to receive Push Notifications!

Removing a user's Push Notification subscription

You can also unsubscribe the user which stops them from receiving any further push notifications:

// unregister from Google GCM
GCMRegistrar.unregister(this);
 
...
 
// unregister from QuickBlox
QBMessages.getSubscriptions(new QBEntityCallbackImpl<ArrayList<QBSubscription>>() {
    @Override
    public void onSuccess(ArrayList<QBSubscription> subscriptions, Bundle args) {
 
        String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
 
        for(QBSubscription subscription : subscriptions){
            if(subscription.getDevice().getId().equals(deviceId)){
                 QBMessages.deleteSubscription(subscription.getId(), new QBEntityCallbackImpl<Void>() {
                     @Override
                     public void onSuccess() {
 
                     }
 
                     @Override
                     public void onError(List<String> errors) {
 
                     }
                 });
                 break;
             }
         }
    }
 
    @Override
    public void onError(List<String> errors) {
 
    }
});

Sending Push Notifications

Send Push Notifications from Admin panel

Just go to Messages module on Admin panel, choose Environment, Channel, type message and press Send message button:

506px-SendPushNotificationsAndroid.png

Your message will be delivered to all your users. You will see

NotifySuccess.png

and

AndroidPushOnDevice.png

Note: You choose byself how to show push to user. There is no standart Android mechanism.


Also you can set more options through Advanced mode like:

  • Group of users (using tags), that will receive message

    PushNotificationsTags.png

  • Delivery settings

    PushNotificationsDeliverySettings.png


Send Push Notifications from Application

It's possible to send 2 types of push notifications:

  1. Platform based Push Notifications
  2. Universal push notifications


Refer to the Push Notification Formats document to better understand what happens under hood.

Platform based Push Notifications

Send Platform based push notifications (GCM) (only works for Android). Platform based push notification will be delivered to specified platform only - in our case it's Android:


Send Push Notification to particular users (through their IDs)

// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(53779);
userIds.add(960);
 
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, String> data = new HashMap<String, String>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
 
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(List<String> errors) {
 
    }
});


Send push notification to a group of users (via Tags)

// recipients
StringifyArrayList<String> usersTags = new StringifyArrayList<String>();
usersTags.add("Man");
usersTags.add("Car");
 
QBEvent event = new QBEvent();
event.setUserTagsAny(usersTags);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, String> data = new HashMap<String, String>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
 
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(List<String> errors) {
 
    }
});

Universal push notifications

Universal push notifications will be delivered to all possible platforms and devices for specified users. With universal push notifications there are 2 ways to send it:

  1. Just send a simple push with text only
  2. With custom parameters


Simple push with text:

// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(53779);
userIds.add(960);
 
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setMessage("Gonna send Push Notification!");
 
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(List<String> errors) {
 
    }
});


With custom parameters:

// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(53779);
userIds.add(960);
 
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
 
 
JSONObject json = new JSONObject();
try {
    json.put("message", "hello");
    json.put("user_id", "234");
} catch (Exception e) {
    e.printStackTrace();
}
 
event.setMessage(json.toString());
 
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(List<String> errors) {
 
    }
});

Conclusion

Now you can play around QuickBlox Messages API, integrate simple and rich Push Notifications into your apps and build some interesting use cases combining this with Chat, Location and other modules from QuickBlox!

Comments

Feel free to comment on this page using the form below.

blog comments powered by Disqus