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 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 Push Notifications 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

In order to start integrating QuickBlox Push Notifications module you have to do the following:

Then you can start use QuickBlox Push Notification API.

Migrate to FCM

Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.

Google prepared great guide how to Migrate a GCM Client App for Android to Firebase Cloud Messaging

QuickBlox backend does support FCM endpoints so you need to update only client-side code.

How QuickBlox Push Notifications work

In order to use QuickBlox Push Notifications APIs you must Create a session & Sign In to QuickBlox.

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 -> Push Notifications -> type your message in Simple mode -> and hit "Send" for all of your users to receive the message; 2) Send a push using Push Notifications 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 code sample 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. Initializing Push Notifiocations via Android SDK

Initializing Push Notifiocations via Android SDK

Setup Push Notifications SDK 3.2 - Auto subscription

Since version 3.2 android SDK provides new feature - auto subscription to push notification out of the box. It means you don’t need bother how to get GCM or FCM token, create QBPushNotifications.createSubscription and what to do with received data in your code anymore. Thus, you can reduce your code.

Some requirement to integrate auto push subscription to app:

  1. As part of enabling Google APIs or Firebase services in your Android application you may have to add the google-services plugin to your Project build.gradle file:
    dependencies {
    classpath 'com.google.gms:google-services:3.0.0'}

    Note: If you use google play services in your project, use version 9.8.0 (version we use in our SDK) as all com.google.android.gms libraries must use the exact same version specification.

  2. Include gms plugin in the bottom of your module build.gradle :
    apply plugin: 'com.google.gms.google-services'
  3. Add empty current_key settings into your google-services.json file for your package name:
    "client": [
        {
          "client_info": {
            "mobilesdk_app_id": "1:761750217637:android:c4299bc46191b0d7",
            "client_id": "android:com.your.app",
            "client_type": 1,
            "android_client_info": {
              "package_name": "com.your.app"
            }
          },
          ...
          "api_key": [
            {
              "current_key": ""
            }
          ],

Steps to setup SDK Settings.

  1. Setting android manifest.
    To integrate Auto push subscription you just need set values in AndroidManifest:
    <meta-data android:name="com.quickblox.messages.TYPE" android:value="GCM" />
    <meta-data android:name="com.quickblox.messages.SENDER_ID" android:value="@string/sender_id" />
    <meta-data android:name="com.quickblox.messages.QB_ENVIRONMENT" android:value="DEVELOPMENT" />
    com.quickblox.messages.TYPE - can be GCM or FCM
    com.quickblox.messages.SENDER_ID - your project id from google console (for ex. 761750217637)
    com.quickblox.messages.QB_ENVIRONMENT - can be DEVELOPMENT or PRODUCTION

    and as usual, setting for GCM GcmPushListenerService:

            <service
                android:name="com.quickblox.messages.services.gcm.QBGcmPushListenerService"
                android:exported="false">
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                </intent-filter>
            <service
                android:name="com.quickblox.messages.services.gcm.QBGcmPushInstanceIDService"
                android:exported="false">
                <intent-filter>
                    <action android:name="com.google.android.gms.iid.InstanceID" />
                </intent-filter>
            </service>

    and other stuff like permissions (look here for details https://developers.google.com/cloud-messaging/android/client).


    Note, if you are using type FCM, it is a little bit easier, to get message you just need set FcmPushListenerService:

            <service
                android:name="com.quickblox.messages.services.fcm.QBFcmPushListenerService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
            </service>

  2. Different push types
    Now Google Cloud Messaging can be two types: Google Cloud Messaging (GCM) or Firebase Cloud Messaging (FCM). Our SDK provides both. You can set this type in meta-data.

  3. Receiving push notifications
    To receive push notification you need: register BroadcastReceiver:
       private BroadcastReceiver pushBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String message = intent.getStringExtra(“message”);
                String from = intent.getStringExtra("from");
                Log.i(TAG, "Receiving message: " + message + ", from " + from);
            }
        };
     
            LocalBroadcastManager.getInstance(this).registerReceiver(pushBroadcastReceiver,
                    new IntentFilter("new-push-event"));

    And that’s all! You are ready now to receive push notifications.


  4. Enable and disable delivering push to application
    SDK has some setting for push notification. You can use global setting to enable or disable delivering pushes via QBSettings (means set this parameter once):
    QBSettings.getInstance().setEnablePushNotification(false); as default true

    To check this parameter

    QBSettings.getInstance().isEnablePushNotification();


  5. Tracking subscriptions status
    To be aware about what is happening with push subscription, are you subscribed successful or not, there is QBSubscribeListener. Add QBSubscribeListener right after QBSettings.getInstance().init(); Code snippet:
    QBPushManager.getInstance().addListener(new QBPushManager.QBSubscribeListener() {
                @Override
                public void onSubscriptionCreated() {
                    Log.d(TAG, "onSubscriptionCreated");
                }
     
                @Override
                public void onSubscriptionError(final Exception e, int resultCode) {
                    Log.d(TAG, "onSubscriptionError" + e);
                    if (resultCode >= 0) {
                        Log.d(TAG, "Google play service exception" + resultCode);
                    }
                    Log.d(TAG, "onSubscriptionError " + e.getMessage());
                }
            });
  6. Disabling subscribing at all.
    If you don’t want to use auto subscribe feature at all, just do not set meta-data. In case you were subscribed, now want to unsubscribe and do not subscribe again use global setting SubscribePushStrategy.NEVER like this:
    // default SubscribePushStrategy.ALWAYS
    QBSettings.getInstance().setSubscribePushStrategy(SubscribePushStrategy.NEVER)

    And of cause you can subscribe or unsubscribe from pushes whatever you need just use:

    SubscribeService.subscribeToPushes(context, false);
    SubscribeService.unSubscribeFromPushes(context);
     
    //second param true - if you use InstanceIDListenerService and google token onTokenRefresh
     @Override
        public void onTokenRefresh() {
     	SubscribeService.subscribeToPushes(context, true);
        }

Setup Push Notifications SDK version prior 3.2

Create session with user's parameters & subscribe to receive Push Notifications
Use login & password from previous step

// Set your QuickBlox application credentials here
static final String APP_ID = "961";
static final String AUTH_KEY = "PBZxXW3WgGZtFZv";
static final String AUTH_SECRET = "vvHjRbVFF6mmeyJ";
static final String ACCOUNT_KEY = "961";
//
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
 
private GoogleCloudMessaging googleCloudMessaging;
 
// Create quickblox session with user
QBAuth.createSession("bob", "bob67pass", new QBEntityCallback<QBSession>() {
    @Override
    public void onSuccess(QBSession session, Bundle params) {
 
        // request registration ID
        //
        // See https://github.com/QuickBlox/quickblox-android-sdk/blob/master/sample-messages/src/com/quickblox/simplesample/messages/main/helper/PlayServicesHelper.java
 
 
        String registrationId = "...";
 
        // Subscribe to Push Notifications
        subscribeToPushNotifications(registrationId)
 
    }
 
    @Override
    public void onError(QBResponseException errors) {
 
    }
});
 
 
//
// Subscribe to Push Notifications
public void subscribeToPushNotifications(String registrationID) {
    QBSubscription subscription = new QBSubscription(QBNotificationChannel.GCM);
    subscription.setEnvironment(QBEnvironment.DEVELOPMENT);
    //
    String deviceId;
    final TelephonyManager mTelephony = (TelephonyManager) activity.getSystemService(
                Context.TELEPHONY_SERVICE);
    if (mTelephony.getDeviceId() != null) {
        deviceId = mTelephony.getDeviceId(); //*** use for mobiles
    } else {
        deviceId = Settings.Secure.getString(activity.getContentResolver(),
                    Settings.Secure.ANDROID_ID); //*** use for tablets
    }
    subscription.setDeviceUdid(deviceId);
    //
    subscription.setRegistrationID(registrationID);
    //
    QBPushNotifications.createSubscription(subscription, new QBEntityCallback<ArrayList<QBSubscription>>() {
 
        @Override
        public void onSuccess(ArrayList<QBSubscription> subscriptions, Bundle args) {
 
        }
 
        @Override
        public void onError(QBResponseException error) {
 
        }
    });
}

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

After that you are ready to receive Push Notifications! </ol>

Removing a user's Push Notification subscription

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

// unregister from QuickBlox
QBPushNotifications.getSubscriptions(new QBEntityCallback<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)){
                 QBPushNotifications.deleteSubscription(subscription.getId(), new QBEntityCallback<Void>() {
                     @Override
                     public void onSuccess() {
 
                     }
 
                     @Override
                     public void onError(QBResponseException errors) {
 
                     }
                 });
                 break;
             }
         }
    }
 
    @Override
    public void onError(QBResponseException errors) {
 
    }
});

Sending Push Notifications

Send Push Notifications from Admin panel

Just go to Push Notifications 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);
 
QBPushNotifications.createEvent(event, new QBEntityCallback<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(QBResponseException 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);
 
QBPushNotifications.createEvent(event, new QBEntityCallback<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(QBResponseException 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!");
 
QBPushNotifications.createEvent(event, new QBEntityCallback<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(QBResponseException 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 {
    // standart parameters
    // read more about parameters formation http://quickblox.com/developers/Messages#Use_custom_parameters
    json.put("message", "hello");
 
    // custom parameters
    json.put("user_id", "234");
    json.put("thread_id", "8343");
 
} catch (Exception e) {
    e.printStackTrace();
}
 
event.setMessage(json.toString());
 
QBPushNotifications.createEvent(event, new QBEntityCallback<QBEvent>() {
    @Override
    public void onSuccess(QBEvent qbEvent, Bundle args) {
        // sent
    }
 
    @Override
    public void onError(QBResponseException errors) {
 
    }
});