Android

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

Contents

Download Android SDK

Quickblox Android SDK, version 2.2.1

Transition guide from 1.2 to 2.0 version

Main changes

  • New generic callbacks, Result entity is deprecated
  • Synchronous requests
  • New Chat API


New result callback

1.2 SDK

QBAuth.createSession(new QBCallbackImpl() {
    @Override
    public void onComplete(Result result) {
        // result comes here
        // check if result success
        if (result.isSuccess()) {
            // do stuff you need
        }
    }
});

2.0 SDK

QBAuth.createSession(new QBEntityCallbackImpl<QBSession>() {
    @Override
     public void onSuccess(QBSession session, Bundle params) {
        Log.i(TAG, "session created, token = " + session.getToken());
     }
     @Override
     public void onError(List<String> errors) {
 
     }
});

Synchronous request example

1.2 SDK

no equivalents

2.0 SDK

QBSession session = null;
try {
    session = QBAuth.createSession();
} catch (QBResponseException e) {
    setException(e);
}
if(session != null){
    Log.i(TAG, "session created, token = " + session.getToken());
}

Chat API

SDK 2.0 contains a new Chat API. Follow Snippets project to understand how new Chat API works.



Code samples

Run samples on IDEA IDE

Gradle
Go to menu File - Import Project. Select path to sample, select Import project from external model, select Gradle, select Use default gradle wrapper(recommended) and click OK.

IDEA
Go to menu File - Import Project. Select path to sample, select Create project from existing sources, click some times Next and Finish.

Run samples on Android Studio

Go to menu File - Import Project. Select path to sample, select Use default gradle wrapper(recommended) and click OK.

How to change gradle version

To change gradle version you need to:

  • set version of plugin in <quickblox-android-sdk>/build.gradle
classpath 'com.android.tools.build:gradle:0.13.+'
  • set version of wrapper in <quickblox-android-sdk>/gradle/wrapper/gradle-wrapper.properties
distributionUrl=http\://services.gradle.org/distributions/gradle-2.1-all.zip


Run samples on Eclipse IDE

Go to menu File - New - Project. Select Android Project from Existing Code and Browse to your project-directory, click Finish.

Run samples on Terminal

Go to project-directory and perform:

 $ gradle installDebug

Start sample on your device.


Code samples

Learn how to enable Push Notifications, create a Chat room, authenticate users via Facebook, show users' locations and POIs, store and retrieve files from the cloud - these code samples are really simple so that even beginner developers can understand:

Title APIs used Description
Simple Android WebRTC (VideoChat) code sample Chat, VideoChat The VideoChat code sample allows you to easily add video calling and audio calling features into your iOS app. Enable a video call function similar to FaceTime or Skype using this code sample as a basis.


User List Android.png Video Call Android.png Incoming Call Android.png

Simple Android Chat code sample Chat, Users The Chat sample connects and socializes your users with the chat module. Features include: Peer to Peer Chat; Group chat; Location based chat; Push notification for offline users.


Simple Android Location code sample Location The Location sample connects app users with each other and their environment. Using GPS locations, map integrations and local data, end users can literally 'see' each other on the map and engage with other users


Simple Android Push Notifications (Messages) code sample Messages, Users Push notifications to your user base — even when your app is not running! This sample enables you to send notifications and alerts to users at any time through an API or easy-to-use admin panel. You can filter who you send messages to through additional parameters.


Simple android Custom Objects (key value data store) code sample Сustom Objects This Custom Objects sample allows to create any server side data structure, use it as you want, create any logic and a lot of others custom features.


Simple android Users authentication code sample Users The Users sample helps you manage and retain your user base across all platforms. It includes a simple authentication process with Single Sign-On and integration across all popular platforms.


Simple android content storage and update code sample Content The Content sample allows send, stream, store, share and save content, update your app's content without having to republish.



How to: add SDK to IDE and connect to the cloud

Import needed jars file(quickblox-android-sdk/jars) to your project.

We provide next jars:

  • quickblox-android-sdk-core.jar (contains core, auth and users classes)
  • quickblox-android-sdk-chat.jar (contains chat class)
  • quickblox-android-sdk-customobjects.jar (contains custom objects class)
  • quickblox-android-sdk-location.jar (contains location class)
  • quickblox-android-sdk-content.jar (contains content class)
  • quickblox-android-sdk-messages.jar (contains messages class)
  • quickblox-android-sdk-ratings.jar (contains ratings class)
  • quickblox-android-sdk-videochat.jar (contains video chat classes)
  • quickblox-android-sdk-videochat-webrtc.jar (contains video chat webrtc classes)


All jars depends on quickblox-android-sdk-core, video chat jars depends on quickblox-android-sdk-chat jar. So add these jars also in your project.


QuickBlox Android SDK uses next external libs:

  • asmack-android-4.0.4
  • qb-gson-2.2.1
  • httpmime-4.2.1
  • javabase64-1.3.1

Oh, please, please show me the code

Android SDK is really simple to use. In just a few minutes you can power up your mobile app with huge amount of awesome communication features & data services.

The common way to interact with QuickBlox can be presented with the following sequence of actions:

  1. Initialize framework with application credentials
  2. Create session
  3. Login with existing user or register new one
  4. Perform actions with QuickBlox communication services and any data entities (users, locations, files, custom objects, pushes etc.)

Initialize framework with application credentials

QBSettings.getInstance().fastConfigInit("961", "PBZxXW3WgGZtFZv", "vvHjRbVFF6mmeyJ");

It's also possible to initialise the SDK with an existent QuickBlox token. It can be interesting in cases when you build a big system and you have the server side which generates QuickBlox tokens for example:

try {
    BaseService.createFromExistentToken("31ed199120fb998dc472aea785a1825809ad5c04", date);
} catch (BaseServiceException e) {
    e.printStackTrace();
}

A couple of words about Authentication and Authorization

To be able to use QuickBlox API you have to create a session.

There are 2 types of session:

  • Application session. It provides only READ access to data.
  • User session. It provides CRUD(Create, Read, Update, Delete) access to data.


To create an application session use this code:

QBAuth.createSession(new QBEntityCallbackImpl<QBSession>() {
    @Override
    public void onSuccess(QBSession session, Bundle params) {
        // success
    }
 
    @Override
    public void onError(List<String> errors) {
        // errors
    }
});

With an Application session you can READ any data you need and only have to do one Create operation - User Sign Up:

// Register new user
final QBUser user = new QBUser("userlogin", "userpassword");
 
QBUsers.signUp(user, new QBEntityCallbackImpl<QBUser>() {
    @Override
    public void onSuccess(QBUser user, Bundle args) {
        // success
    }
 
    @Override
    public void onError(List<String> errors) {
       // error
    }
});

To update an Application session to a User session you have to login to QuickBlox:

// Login
QBUsers.signIn(user, new QBEntityCallbackImpl<QBUser>() {
    @Override
    public void onSuccess(QBUser user, Bundle args) {
        // success
    }
 
    @Override
    public void onError(List<String> errors) {
        // error
    }
});

You can create a User session in single query as well:

QBAuth.createSession(new QBUser("garrysantos", "garrysantospass"), new QBEntityCallbackImpl<QBSession>() {
    @Override
    public void onSuccess(QBSession session, Bundle params) {
        // success
    }
 
    @Override
    public void onError(List<String> errors) {
        // errors
    }
});

A session will remain valid for 2 hours after the last request to QuickBlox was performed. To check a session's expiration date use this next snippet of code:

try {
    Date expirationDate =  BaseService.getBaseService().getTokenExpirationDate();
}catch (BaseServiceException e) {
    e.printStackTrace();
}

Login to Chat

// initialize Chat service
QBChatService chatService;
if (!QBChatService.isInitialized()) {
    QBChatService.init(context);
    chatService = QBChatService.getInstance();
}
 
final QBUser user = new QBUser("indianajones", "indianapassword");
 
chatService.login(qbUser, new QBEntityCallbackImpl() {
    @Override
    public void onSuccess() {
        // success
    }
 
    @Override
    public void onError(List errors) {
        // errror
    }
});

Performing actions

Send Chat message

QBPrivateChat privateChat = privateChatManager.getChat(35);
if (privateChat == null) {
    privateChat = privateChatManager.createChat(35, privateChatMessageListener);
}
 
try {
    privateChat.sendMessage("Hi there!");
} catch (XMPPException e) {
 
} catch (SmackException.NotConnectedException e) {
 
}

Creating a new location for Indiana Jones

double lat = 25.224820; // Somewhere in Africa
double lng = 9.272461;
String statusText = "trying to find adventures";
QBLocation location = new QBLocation(lat, lng, statusText);
QBLocations.createLocation(location, new QBEntityCallbackImpl<QBLocation>() {
    @Override
    public void onSuccess(QBLocation qbLocation, Bundle args) {
        // success
    }
 
    @Override
    public void onError(List<String> errors) {
        // error
    }
});

To put an Image into storage

File file = new File("holy_grail.txt");
Boolean fileIsPublic = true;
QBContent.uploadFileTask(file1, fileIsPublic, null, new QBEntityCallbackImpl<QBFile>() {
    @Override
    public void onSuccess(QBFile qbFile, Bundle params) {
        // success
    }
 
    @Override
    public void onError(List<String> errors) {
        // error
    }
});

Android Framework provides the following classes to interact with QuickBlox API (each class has suite of static methods):

  1. QBAuth
  2. QBUsers
  3. QBChatService
  4. QBCustomObjects
  5. QBLocations
  6. QBContent
  7. QBRatings
  8. QBMessages
  9. QBVideoChat

Performing actions synchronously

It's possible to perform any request synchronously. Context helps you to detect a result's source.

For example, let's sign in a user:

QBUser user = new QBUser();
user.setLogin("userlogin");
user.setPassword("userpassword");
 
QBUser userResult = null;
try {
    userResult =  QBUsers.signIn(user);
} catch (QBResponseException e) {
 
}
 
if(userResult != null){
    // success
}


Read on: Android SDK documentation (Javadoc)

Full reference on classes and interfaces used in QuickBlox Android SDK:
Quickblox Android SDK framework documentation

Currently only auth, users and chat are covered. Other modules will be ready soon.


Framework changelog


v2.2.1 — April 3, 2015

  • Group chat blocks
  • Fixed the NPE issue when use an old way to create group chat rooms


v2.2 — March 30, 2015

  • Updated WebRTC API for Video calling


v2.1.1 — March 17, 2015

  • Added all filter to QBRequestGetBuilder
  • QBUsers.getUsers now returns a param Consts.TOTAL_PAGES in a response bundle
  • Fixed an issue with exception in QBParticipantListener interface
  • Fixed an issue with NullPointerException in QBGroupChat class
  • Added an ability to set fileId as -1 to QBUser to clear it


v2.1 — January 19, 2015

  • Features:
    • Added QBParticipantListener that will be notified of any new Presence packets sent to the group chat.
    • Added QBMessageListenerImpl - an implementation of QBMessageListener.
    • API to remove multiple chat messages in a single query
    • API to create a chat message via REST
    • New filters in QBRequestGetBuilder: outputInclude, outputExclude, near
    • Added a method getRecipientId to QBDialog class.
    • Added a method getSession to QBAuth to get an info about current session.
    • New filters in QBRequestUpdateBuilder: addToSet, updateArrayValue.
    • Added put<type> methods to QBCustomObject class.
    • Added a method setId to QBChatMessage to set the custom Id.
    • Upload/Download files progress callbacks for Content and CustomObjects modules.
    • API to create the geodata with the location-push
    • Updated core of the XMPP library
    • Removed classes QBMessage and QBChatHistoryMessage. Now QBChatMessage must be used anywhere.
  • Fixes:
    • Don't add extraParams to the chat message if there are no any extra parameters or attachments added to chat message.
    • deleteDialog method in QBGroupChatManager and QBPrivateChatManager classes is marked as none static.
    • Issue with chat logout where it wasn't possible to login with another user without doing QBChatService.getInstance().destroy();


v2.0 — October 31, 2014

  • New generic callbacks
  • Result entity is deprecated
  • Synchronous requests
  • New Chat API
  • API to remove chat dialog
  • Added an ability to track 'user is typing' status in chat
  • Added an ability to track 'delivered' status in chat
  • Added an ability to track 'read' status in chat
  • Added an ability to init SDK with existent QuickBlox token
  • Set the chat message packet ID to MongoDB ObjectID
  • Message Carbons (XEP-0280)


v1.2.4 — August 12, 2014

  • Fixed an issue with filter location in geo rect request
  • Fixed an issue with get users with phone numbers request
  • Fixed some crashes in video chat


v1.2.3 — June 26, 2014


v1.2.2 — May 23, 2014

  • Content: translated File public url to new format


v1.2.1 — May 19, 2014

  • Fixed an issue with getting users with fullname with spaces
  • Fixed an issue with uploading content file with spaces in name
  • Fixed parser crash on HTC devices with Android 2.3
  • Set XMPP room name in QBChatService.getInstance().createRoom method


v1.2 — April 25, 2014
  • Chat
    • Renamed SessionListener to SessionCallback
    • Added ConnectionListener
  • General
    • Reduced amount of methods in jar file
    • bug fixes
v1.1 — January 14, 2014
  • Chat
    • Roster(contact list) API
    • Added methods to add/remove users to chat room
v1.0.2 — January 9, 2014
  • Errors handling fixes
v1.0.1 — December 30, 2013
  • Chat
    • Chat API wrapper
  • CustomObjects
    • Permissions API
    • Files API
    • Added ‘output’, ‘or’, ‘ctn’ operators
    • Multi creation of records
    • Multi update of records
    • Multi delete of records
  • Content
    • Ability to update blob’s file
  • General
    • Ability to set custom endpoints for API server, Chat server, TURN server, Content bucket name
    • Access to token expiration date
v0.8.2 — December 9, 2013
  • Improved the stability
v0.8.1 — April 29, 2013
  • Added method QBUsers.getUsersByPhoneNumbers - retrieve users by phone numbers
  • Improved the stability
v0.8 — March 14, 2013
  • Added method QBUsers.getUsersByLogins - retrieve users by logins
  • Added method QBUsers.getUsersByEmails - retrieve users by emails
  • Improved the stability
v0.7 — January 16, 2013
  • All APIs are covered
  • Renamed QBAuth.authorizeApp method to QBAuth.createSession

Comments

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

blog comments powered by Disqus