Backendless API for Android
-
Upload
duong-huu-trang -
Category
Documents
-
view
221 -
download
0
Transcript of Backendless API for Android
-
7/25/2019 Backendless API for Android
1/271
2015 Backendless Corp.
Backendless API for Android
-
7/25/2019 Backendless API for Android
2/271
All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or
mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the
written permission of the publisher.
Products that are referred to in this document may be either trademarks and/or registered trademarks of the
respective owners. The publisher and the author make no claim to these trademarks.
While every precaution has been taken in the preparation of this document, the publisher and the author ass ume no
responsibil ity for errors or omis sions, or for damages resulting from the use of information contained in this
document or from the use of programs and source code that may accompany it. In no event shall the publis her and
the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused
directly or indirectly by this document.
Generated on: December 2015
Backendless API for Android
2015 Backendless Corp.
All the people who contributed to this document, to everyone who
has helped us out with the vision for the product, feature
suggestions and ideas for improvements. Special thanks to our
families for your support, encouragement and patience.
Special thanks to:
-
7/25/2019 Backendless API for Android
3/271
3Contents
2015 Backendless Corp.
Table of Contents
User Service 6
................................................................................................................................... 61 Overview
................................................................................................................................... 62 Setup
................................................................................................................................... 93 Core Classes
................................................................................................................................... 114 Error Handling
................................................................................................................................... 115 User Properties
................................................................................................................................... 136 Retrieve User Entity Properties
................................................................................................................................... 147 User Registration
................................................................................................................................... 178 Login
................................................................................................................................... 219 Facebook Login
................................................................................................................................... 2510 Update User Properties
................................................................................................................................... 2811 Get Current User
................................................................................................................................... 2812 Logout
................................................................................................................................... 2913 Password Recovery
................................................................................................................................... 3114 Security
................................................................................................................................... 3515 Role To User Mapping
Data Service 37
................................................................................................................................... 371 Overview
................................................................................................................................... 382 Setup
................................................................................................................................... 413 Sync and Async Calls
................................................................................................................................... 424 Error Handling
................................................................................................................................... 425 Native vs External Databases
................................................................................................................................... 436 Using External Databases
................................................................................................................................... 477 Data Object
................................................................................................................................... 488 Saving Data Objects
................................................................................................................................... 529 Updating Data Objects
................................................................................................................................... 5910 Deleting Data Objects
................................................................................................................................... 6511 Retrieving Schema Definition
................................................................................................................................... 6712 Basic Search
................................................................................................................................... 7313 Advanced Search
................................................................................................................................... 8014 Using Dates in Search
................................................................................................................................... 8115 Relations Overview
................................................................................................................................... 8716 Relations (Save/Update)
................................................................................................................................... 9717 Relations (Delete)
-
7/25/2019 Backendless API for Android
4/271
Backendless API for Android
2015 Backendless Corp.
4................................................................................................................................... 10418 Relations (Retrieve)
................................................................................................................................... 11419 Relations with Geo Points
................................................................................................................................... 12220 Security
................................................................................................................................... 12821 Permissions API
Messaging Service 131
................................................................................................................................... 1311 Overview
................................................................................................................................... 1312 Setup
................................................................................................................................... 1353 Core Classes
................................................................................................................................... 1384 Sync and Async Calls
................................................................................................................................... 1395 Error Handling
................................................................................................................................... 1396 Push Notification Setup (Android)
................................................................................................................................... 1437 Push Notification Setup (iOS)
................................................................................................................................... 1538 Device Registration
................................................................................................................................... 1549 Retrieve Device Registration
................................................................................................................................... 15510 Managing Registrations
................................................................................................................................... 15611 Cancel Device Registration
................................................................................................................................... 15712 Message Publishing
................................................................................................................................... 16413 Publish Push Notifications
................................................................................................................................... 16514 Cancel Scheduled Message
................................................................................................................................... 16615 Message Subscription
................................................................................................................................... 17216 Cancel Subscription
................................................................................................................................... 17317 Sending Email
File Service 175
................................................................................................................................... 1751 Overview
................................................................................................................................... 1752 Setup
................................................................................................................................... 1793 Sync and Async Calls
................................................................................................................................... 1804 Error Handling
................................................................................................................................... 1805 Handling Files via Console
................................................................................................................................... 1846 File Upload
................................................................................................................................... 1897 Save Files From Byte Arrays
................................................................................................................................... 1918 File Download
................................................................................................................................... 1929 File Deletion
................................................................................................................................... 19310 Directory Deletion
................................................................................................................................... 19311 Git Integration
................................................................................................................................... 19512 Web Hosting
................................................................................................................................... 19613 Custom Domain Name
................................................................................................................................... 19714 Custom Web Template Hosting
................................................................................................................................... 20015 Files Security
-
7/25/2019 Backendless API for Android
5/271
5Contents
2015 Backendless Corp.
Geo Service 201
................................................................................................................................... 2011 Overview
................................................................................................................................... 2032 Setup
................................................................................................................................... 2063 Sync and Async Calls
................................................................................................................................... 2074 Error Handling
................................................................................................................................... 2075 Adding a Geo Category
................................................................................................................................... 2116 Deleting a Geo Category
................................................................................................................................... 2137 Retrieving Geo Categories
................................................................................................................................... 2158 Adding a GeoPoint
................................................................................................................................... 2179 Updating a GeoPoint
................................................................................................................................... 21710 Deleting a GeoPoint
................................................................................................................................... 21911 Importing Geo Data
................................................................................................................................... 22112 Search in Category
................................................................................................................................... 22413 Search in Radius
................................................................................................................................... 23214 Search in Rectangular Area
................................................................................................................................... 23915 Geo Point Clustering
................................................................................................................................... 24816 Relations with Data Objects
................................................................................................................................... 25217 Geofence Designer
................................................................................................................................... 26318 Geofence API
Index 269
-
7/25/2019 Backendless API for Android
6/271
Backendless API for Android
2015 Backendless Corp.
6
1 User Service
1.1 Overview
The Backendless User Service empowers applications with the functionality related to the user accountssuch as user registrations, logins, password recovery and logouts. The core concept which the User
Service relies on is the Userentity. The structure of the entity is configurable, that is a developer can
decide which properties "describe" a user in the context of a given version of the application. Typically,
properties describing a user are the ones collected during the user registration process. The User
Service provides the API enabling the following functionality for the applications built on top of
Backendless:
User Registration- Applications use the Backendless' registration API to let the users register
and create accounts for subsequent logins. Application developers can restrict access to the
server-side resources for specific user accounts or based on roles.
User Login- the API lets the registered users login to establish their identity within the
application.
Password Recovery- Backendless supports a complete workflow allowing users to recover lost orforgotten passwords.
User Logout- the API lets the logged in users terminate their session and disassociate their
identity from the application.
Updating User Registration- the API supports the operation of updating user information.
1.2 Setup
Pure Java and Android clients can consume the Backendless services using the class library (JAR)
provided in the Backendless SDK for Java. Make sure to reference backendless.jar located in the /lib
folder of the SDK in the project dependencies and the runtime classpath to get access to the API.
Download SDKThe SDK can be downloaded from the Backendless website.
Maven integrationThe backendless client library for Android and Java is available through the Maven repository. To add a
dependency for the library, add the following to pom.xml:
com.backendless
android
1.0
Before the Java/Android client uses any of the APIs, the code must initialize the Backendless
Application using the following call:
Backendless.initApp( application-id, secret-key, version );
Proguard ConfigurationIf your Android application uses Proguard, it is necessary to add the following configuration parameters
to proguard.cfg:
http://developer.android.com/tools/help/proguard.htmlhttps://backendless.com/downloads -
7/25/2019 Backendless API for Android
7/271
User Service
2015 Backendless Corp.
7
-dontwarn
-keep class weborb.** {*;}
Apps with Google Maps and GeolocationAndroid applications using Google Maps, for instance, the Geo service sample app generated byBackendless code generator, require additional configuration in order for Google maps to be displayed.
The process of configuring an app to support Google maps consists of the following tasks:
1. Display the debug certificate fingerprint
1. Locate your debug keystore file. The file name is debug.keystore, and is created the first time
you build your project. By default, it is stored in the same directory as your Android Virtual Device
(AVD) files:
OS X and Linux: ~/.android/
Windows Vista and Windows 7: C:\Users\your_user_name\.android\
2. If you are using Eclipse with ADT, and you are not sure where your debug keystore is located, you
can select Windows> Prefs> Android>Buildto check the full path, which you can then paste
into a file explorer to locate the directory containing the keystore.
3. List the SHA-1 fingerprint.
For Linux or OS X, open a terminal window and enter the following:
keytool -list -v -keystore ~/.android/debug.keystore -alias
androiddebugkey -storepass android -keypass android
For Windows Vista and Windows 7, run:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.
keystore" -alias androiddebugkey -storepass android -keypass
android
4. You should see output similar to this:Alias name: androiddebugkey
Creation date: Jan 01, 2013
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 4aa9b300
Valid from: Mon Jan 01 08:04:04 UTC 2013 until: Mon Jan 01
18:04:04 PST 2033
Certificate fingerprints:
MD5: AE:9F:95:D0:A6:86:89:BC:A8:70:BA:34:FF:6A:AC:F9
SHA1: BB:0D:AC:74:D3:21:E1:43:07:71:9B:62:90:AF:
A1:66:6E:44:5D:75
Signature algorithm name: SHA1withRSA
Version: 3
5. The line that begins SHA1 contains the certificate's SHA-1 fingerprint. The fingerprint is the
sequence of 20 two-digit hexadecimal numbers separated by colons.
2. Create an API project in the Google APIs Console
1. In a browser, navigate to the Google APIs Console.
https://code.google.com/apis/console/?noredirect -
7/25/2019 Backendless API for Android
8/271
Backendless API for Android
2015 Backendless Corp.
8
If you haven't used the Google APIs Console before, you're prompted to create a project that
you use to track your usage of the Google Maps Android API. Click Create Project; the
Console creates a new project called API Project. On the next page, this name appears in
the upper left hand corner. To rename or otherwise manage the project, click on its name.
If you're already using the Google APIs Console, you will immediately see a list of your
existing projects and the available services. It's still a good idea to use a new project forGoogle Maps Android API, so select the project name in the upper left hand corner and then
click Create.
2. You should see a list of APIs and services in the main window. If you don't, select Servicesfrom
the left navigation bar.
3. In the list of services displayed in the center of the page, scroll down until you see Google Maps
Android API v2. To the right of the entry, click the switch indicator so that it is on.
4. This displays the Google Maps Android API Terms of Service. If you agree to the terms of service,
click the checkbox below the terms of service, then click Accept. This returns you to the list of
APIs and services.3. Obtain a Google Maps API key
If your application is registered with the Google Maps Android API v2 service, then you can request
an API key. It's possible to register more than one key per project.
1. Navigate to your project in the Google APIs Console.2. In the Servicespage, verify that the "Google Maps Android API v2" is enabled.
3. In the left navigation bar, click API Access.
4. In the resulting page, click Create New Android Key....
5. In the resulting dialog, enter the SHA-1 fingerprint, then a semicolon, then your application's
package name. For example:
BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75;com.
example.android.mapexample
6. The Google APIs Console responds by displaying Key for Android apps (with certificates) followed
by a forty-character API key, for example:
AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0
4. Add the API key to your applicationFollow the steps below to include the API key in your application's manifest, contained in the file
AndroidManifest.xml. From there, the Maps API reads the key value and passes it to the Google
Maps server, which then confirms that you have access to Google Maps data.
1. In AndroidManifest.xml, add the following element as a child of the element, by
inserting it just before the closing tag :
2. Substitute your API key for API_KEYin the value attribute. This element sets the key com.google.
android.maps.v2.API_KEYto the value of your API key, and makes the API key visible to any
MapFragmentin your application.
3. Save AndroidManifest.xml and re-build your application.
Application ID and Secret KeyValues for the application-idand secret-keyheaders must be obtained through the Backendless
Console:
1. Login to your account and select the application.
2. Click the Manage icon from the vertical icon-menu on the left.
https://code.google.com/apis/console/?noredirecthttps://developers.google.com/maps/terms -
7/25/2019 Backendless API for Android
9/271
User Service
2015 Backendless Corp.
9
3. The "App Settings" section is selected by default. The interface contains the text fields for
"Application ID" and secret keys for each supported client-side environment.
4. Use the "Copy" button to copy the value into the system clipboard.
Make sure to use the "Android Secret Key" for the secret-keyargument.
The versionargument must contain the name of the targeted version. When a new application is
created, the default version name is "v1". To manage versions, login to the console, select the
"Manage" icon and click "Versioning".
1.3 Core Classes
The Backendless User Service uses the following core classes:
Backendless.UserService- provides access to the user service API. All user-related operations,
such as user registration, user update, login, logout and password recovery are available through this
class.
BackendlessUser- represents a user registered with the application. The class is used in:
User Registration- an instance of the class contains a list of user properties
User Registration/Properties Update- an instance of the class contains a list of properties to be
updated
The Login methodreturns an instance of the class upon successful login.
BackendlessUser Class Definition
The BackendlessUserclass is defined as:
-
7/25/2019 Backendless API for Android
10/271
Backendless API for Android
2015 Backendless Corp.
10
package com.backendless;
import java.util.HashMap;
import java.util.Map;
public class BackendlessUser{
// Returns all properties of the user object
public Map getProperties()
// sets the properties of the user to the values from the
specified map
public void setProperties( Map properties )
// adds properties from the specified map to the existing
properties collection
public void putProperties( Map properties )
// retrieves the value of the property
public Object getProperty( String key )
// sets the value of the property
public void setProperty( String key, Object value )
// returns internal id of the user object assigned by
Backendless.
// The value is available only for registered user accounts.
public String getUserId()
// sets the password for the account
public void setPassword( String password )
// retrieves the password for the user account
public String getPassword()
}
AsyncCallBack- an interface used in the asynchronous API calls. An implementation of the
interface must provide two methods. One accepting a result from the server (with the generic type T as
the argument) and the other for handling errors reported by the server.
AsyncCallback Class Definition
The AsyncCallbackinterface is defined as:
package com.backendless.async;
import com.backendless.exceptions.BackendlessFault;
public interface AsyncCallback
{
public void handleResponse( T response );
public void handleFault( BackendlessFault fault );
}
-
7/25/2019 Backendless API for Android
11/271
User Service
2015 Backendless Corp.
11
BackendlessFaultand BackendlessException - Used in error handling, asynchronous and
synchronous respectfully.
1.4 Error Handling
When the server reports an error, it is delivered to the client through an instance of theBackendlessFaultclass. A BackendlessFault object provides access to an error code which uniquely
identifies the root cause of the error. Currently all the error codes are numbers, however the method
returning the error code returns the String type. This is done for future expansion of the error code
system which may include characters. In addition to the error code, the fault object may include an error
message which provides additional information about the error:
package com.backendless.exceptions;
public class BackendlessFault
{
// returns the error code
public String getCode();
// returns the error message which provides additional
information about the error
public String getMessage();
//
public String getDetail();
public String toString();
}
The asynchronous calls receive the fault through the following method in the callback object:
public void handleFault( BackendlessFault fault )
For the synchronous calls the fault object can be obtained through the BackendlessException
exception which the synchronous method may throw. The exception class provides access to a
BackendlessFaultobject through the following method:
package com.backendless.exceptions;
public class BackendlessException extends Throwable
{
public BackendlessFault getFault();
}
1.5 User Properties
When a user registers with an application, he provides information which establishes the person's
identity. For one application these properties may include name, phone number and email address, for
another it could be user id, age and gender. Backendless User Service allows each application to have a
custom set of properties associated with the user entity. There are two ways to define what properties
the User entity should have in a Backendless application:
Defining properties with ConsoleUser property management is available on the User Properties screen of the console. To get to the
-
7/25/2019 Backendless API for Android
12/271
Backendless API for Android
2015 Backendless Corp.
12
screen:
1. Login to the console
2. Select the desired application and version
3. Click the Users icon on the left side of the interface. The "User Properties" panel is selected by
default.
The interface consists of two lists: Available Properties and Selected Properties. The Selected
Properties list contains the properties assigned to the User entity - these are the effective properties for
the selected version of the application. The Available Properties list is simply a storage for the non-
effective properties which can be moved to the Selected list if needed. A property can be moved between
the lists by c licking its name.
Identity Property
Among the Selected Properties, one must be marked as identity. This is the property Backendless
uses for the Loginand Restore Passwordoperations.. As users register, Backendless ensures the
provided value for the property selected as identity is unique in the context of a specific version for
an application.
Password Property"password" is a special property. Backendless automatically adds the property when an application
is created. The following rules apply to the password property:
Password cannot be moved out of the Available Properties list.
Password cannot be marked as Identity.
Password is always a required property
To add a property, click the "Add Custom Property" button. New properties automatically added to the
Selected Properties list. To move a property to the other list, simply click its name.
Defining properties with APIUser properties can be defined with the user registration API call. For any property specified in the
-
7/25/2019 Backendless API for Android
13/271
User Service
2015 Backendless Corp.
13
object with the user registration information Backendless creates a user property. This behavior can be
turned off/on using the Dynamic User Definition configuration setting in the console (select the Users >>
User Properties). The sett ing is turned on by default:
1.6 Retrieve User Entity Properties
Application developers can get a list of the properties associated with the user entity using the following
API:
Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.describeUserClass
( AsyncCallback callback );
where:
callback - an object which receives either a return value or an error from the server. The return
value from the server is a collection of the UserProperty objects. The class of the
callback object must implement the AsyncCallback
interface.
The UserPropertyclass is defined as:
public class UserProperty
{
// The method returns true if the property is marked as
'identity'
public boolean isIdentity();
// Returns the name of the property
public String getName();
// Returns true if the property is required during user
registration
public boolean isRequired();
// Returns the data type of the property
public DateTypeEnum getType();
}
Synchronous Call Method Signature:
public List Backendless.UserService.describeUserClass
();
Asynchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.UserService.describeUserClass( new
AsyncCallback()
{
public void handleResponse( List properties )
-
7/25/2019 Backendless API for Android
14/271
Backendless API for Android
2015 Backendless Corp.
14
{
for( UserProperty userProp : properties )
{
System.out.println( "Property name - " + userProp.getName();
System.out.println( "\trequired - " + userProp.isRequired();
System.out.println( "\tidentity - " + userProp.isIdentity(); System.out.println( "\tdata type - " + userProp.getType();
}
}
public void handleFault( BackendlessFault fault )
{
}
});
Synchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
List properties = Backendless.UserService.
describeUserClass();
for( UserProperty userProp : properties )
{
System.out.println( "Property name - " + userProp.getName();
System.out.println( "\trequired - " + userProp.isRequired();
System.out.println( "\tidentity - " + userProp.isIdentity();
System.out.println( "\tdata type - " + userProp.getType();
}
1.7 User Registration
The user registration API can be used to create user accounts in the application. The registration
request must provide a user object as a collection of key/value properties. The collection must contain
all the required properties which must include a property marked as identity as well as the "password"
property. Unless the properties are modified in the console, the default property marked as identity is
"email". Additionally, the "email"property is required if the application is configured to confirm email
addresses for the registered users.
Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallbackargument receives either
the response or the fault returned by the Backendless servers.
Backendless.UserService.register( user, new
AsyncCallback() );
where:
user - an instance of the BackendlessUserclass which contains property values for the
account registration.
callback - an object which receives either a return value or an error from the server. The return
value from the server is an instance of the BackendlessUserclass with the ID assigned
by the server-side. The class of the callback object must implement the
AsyncCallback interface.
-
7/25/2019 Backendless API for Android
15/271
User Service
2015 Backendless Corp.
15
Synchronous Call Method Signature:
public BackendlessUser Backendless.UserService.register
( BackendlessUser userObj ) throws BackendlessException;
Error Codes:
The following errors may occur during User Registration API calls. See the Error Handling sectionfor
details on how to retrieve the error code when the server returns an error.
Error
Code
Description
2002 Version is disabled or provided wrong application info (application id or
secret key)
3009 User registration is disabled for the version of the application
3010 User registration has an unknown property and dynamic properties are
disabled for this version of the application
3011 Missing "password" property3012 Required property is missing
3013 Missing value for the identity property
3014 External registration failed with an error.
3021 General user registration error. Details included with the error message.
3033 User with the same identity already exists
3038 Missing application-id, version name or collection of properties for the
registering user
3039 Property "id" cannot be used in the registration call
3040 Email address is in the wrong format
3041 A value for a required property is missing
3043 Duplicate properties in the registration request
8000 Property value exceeds the length limit
Asynchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user = new BackendlessUser();
user.setProperty( "email", "[email protected]" );
user.setPassword( "iAmWatchingU" );
Backendless.UserService.register( user, new
AsyncCallback()
{
public void handleResponse( BackendlessUser registeredUser )
{
// user has been registered and now can login
}
-
7/25/2019 Backendless API for Android
16/271
Backendless API for Android
2015 Backendless Corp.
16
public void handleFault( BackendlessFault fault )
{
// an error has occurred, the error code can be retrieved with
fault.getCode()
}
} );
Synchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user = new BackendlessUser();
user.setProperty( "email", "[email protected]" );
user.setPassword( "iAmWatchingU" );
try
{
user = Backendless.UserService.register( user );
}
catch( BackendlessException exception )
{
BackendlessFault fault = exception.getFault();
// an error has occurred, the error code can be retrieved with
fault.getCode()
}
Turning Registration OffUser registration can be disabled for a particular version of the application using the Backendless
Console:
1. Login to the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.3. Click "Registration".
The "Registration" toggle turns the registration API on or off. When the registration is turned off and a
user attempts to register, the system returns error 3009.
Email Confirmations
Backendless can send out an email requesting new registered users to confirm their email address. Thisfeature can be configured in the Backendless Console:
1. Log into the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Registration".
-
7/25/2019 Backendless API for Android
17/271
User Service
2015 Backendless Corp.
17
When email confirmations are required (the feature is enabled by default), the "email"user property is
required and must contain a value formatted as an email address. To configure the text of the email
message, select "Communication & Email Templates" from the Users menu in the console and select
the "User registers" event.
External RegistrationUser registrations can be duplicated in an external system through the External Registration Callback.
Developer can specify a URL where Backendless sends a POST request to with the user registration
data as a JSON object. The external registration callback is synchronous and takes place in the same
transaction as the Backendless registration call. As a result, the external system must return result as
fast as possible. The format of the request and response for the external registration is the same as the
request/response body of the Backendless registration API.
To configure the callback:1. Login to the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Registration".
4. Turn on the "Execute registration callback" toggle.
5. Enter the URL of the script into the "Callback URL" text field.
1.8 Login
Registered users can login to establish their identity with the application using the API below. The login
operation requires two properties: one marked as user identityand the second is password.
Backendless automatically assigns the "AuthenticatedUser"role to all successfully logged in users.
The role can be used to differentiate access to various resources (persistent objects, messaging
channels, media streams) between authenticated users and guests.
Asynchronous Methods:
The method call does not block - it returns immediately. The AsyncCallbackargument receives
either the response or the fault returned by the Backendless servers.
publicvoidBackendless.UserService.login(Stringlogin,
Stringpassword,AsyncCallback
callback);
publicvoidBackendless.UserService.login(Stringlogin,
Stringpassword,
booleanstayLoggedIn,
AsyncCallback
callback);
where:
-
7/25/2019 Backendless API for Android
18/271
Backendless API for Android
2015 Backendless Corp.
18
login - a value for the property marked as identity.
password - user's password
stayLoggedIn - requests to store the user's login information so the login form can be
skipped next time the user launches the app. Use the following API to check
if the application has user login information from previous runs:
// UserTokenStorageFactory is available in the com.
backendless.persistence.local package
StringuserToken=UserTokenStorageFactory.instance().
getStorage().get();
if(userToken!=null&&!userToken.equals(""))
{ // user login is available, skip the login activity/login
form }
callback - an object which receives either a return value or an error from the server.
The class must implement the AsyncCallback
interface.
Synchronous Method:
publicBackendlessUserBackendless.UserService.login(Stringlogin,String
password,booleanstayLoggedIn)throwsBackendlessException;
where:
login - a value for the property marked as identity.
password - user's password
stayLoggedIn - requests to store the user's login information so the login form can be
skipped next time the user launches the app. Use the following API to check
if the application has user login information from previous runs:
// UserTokenStorageFactory is available in the com.
backendless.persistence.local package
StringuserToken=UserTokenStorageFactory.instance().
getStorage().get();
if(userToken!=null&&!userToken.equals(""))
{ // user login is available, skip the login activity/login
form }
Error Codes:
The following errors may occur during the Login API call. See the Error Handling sectionfor details
on how to retrieve the error code when the server returns an error.
Error
Code
Description
2002 Version is disabled or provided wrong application info (application id
or secret key)
3000 Login has been disabled for the user account.
3001 Missing login settings, possibly invalid application id or version.
3002 User cannot login because Multiple Logins disabled and there is a
logged in user for the account.
3003 Invalid login or password.
-
7/25/2019 Backendless API for Android
19/271
User Service
2015 Backendless Corp.
19
3006 Either login or password is an empty string value.
3034 User logins are disabled for the version of the application.
3036 Account locked out due to too many failed logins.
3038 One of the required parameters (application id, version, login or
password) is null
3044 Multiple login limit for the same user account has been reached.
8000 Property value exceeds the length limit
Asynchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.UserService.login( username, password, new
AsyncCallback()
{
public void handleResponse( BackendlessUser user )
{
// user has been logged in
}
public void handleFault( BackendlessFault fault )
{
// login failed, to get the error code call fault.getCode()
}
});
Synchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user;
try
{
user = Backendless.UserService.login( username, password );
}
catch( BackendlessException exception )
{
// login failed, to get the error code, call exception.getFault
().getCode()
}
External AuthenticationSimilar to external registration, Backendless supports external authentication. When configured,Backendless delegates the authentication process to an external system by sending the provided
user credentials to a URL. The URL of the external authentication system can be configured in
Backendless Console:
1. Log into the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Login".
4. The "External authentication" section contains the configuration settings.
-
7/25/2019 Backendless API for Android
20/271
Backendless API for Android
2015 Backendless Corp.
20
When the external authentication is enabled and user attempts to login, Backendless sends the
following request to the specified URL:
POST http://external-authentication-url
Authorization: Basic base64-encoded-login:password
Where base64-encoded-login:password is constructed as follows:
1. login and password are combined into a string "login:password"
2. The resulting string literal is then encoded using Base64
Multiple Logins
The Multiple Logins feature enables login using the same account from different computers ordevices. Multiple logins can be configured in the Backendless Console:
1. Log into the console and select the application.
2. Click the "Users" icon in the vertical icon menu on the left.
3. Click "Login".
4. The "Multiple Logins" section contains the configuration settings.
When the feature is turned on (multiple logins allowed), the configuration setting may include the
maximum number of simultaneous logins for the selected version of the application. When the
feature is disabled (multiple logins are not allowed), the configuration must indicate whether which
login should be invalidated (first or second for the account):
Session TimeoutBackendless supports session expiration which can be configured in console. Along with the
session timeout interval, the configuration can also include a forwarding URL which is used to
redirect requests to for the expired sessions.
http://en.wikipedia.org/wiki/Base64 -
7/25/2019 Backendless API for Android
21/271
User Service
2015 Backendless Corp.
21
Account LockoutAn application powered by Backendless can be configured to lock out accounts with failed logins.
The console has two configuration options: number of failed logins before the account is locked and
a time interval to wait before the account is available for logins again.
1.9 Facebook Login
Backendless integrates with Facebook to support user authentication and login into a Backendlessapplication with a Facebook account. Using the integration application developer can provide a way to
skip the application registration step and allow users to use their Facebook identity to enter and
experience the application. Backendless provides two ways to handle Facebook logins:
Easy Facebook Login- The Facebook SDK is not required on the client. The client application
makes a Backendless API call to initiate the login and the user authenticates in a Facebook
popup window.
Login with Facebook SDK- The client application uses the Facebook SDK to authenticate the
user and then delegates to a Backendless API call to link the Facebook identity to a
BackendlessUserinstance.
Both approaches - Easy Login and Login with SDK, rely on the concepts and a configuration change
described below:
Property MappingSince a Backendless application has its own set of user properties, they need to be mapped to the
corresponding Facebook Graph API user fields. A mapping references a Facebook user field and the
name of a Backendless property. The mapping is a required argument in the Backendless API call to
login. Once the user is authenticated, Backendless obtains the field values from the Facebook user
graph object and populates the mapped properties in the BackendlessUserobject. For the very first
login, Backendless also registers the user. In this case the returned BackendlessUserobject will have
https://developers.facebook.com/docs/reference/api/user/ -
7/25/2019 Backendless API for Android
22/271
Backendless API for Android
2015 Backendless Corp.
22
the "user-registered" property set to true.
PermissionsThe client application can request the permissions from the user to access additional user information or
perform various actions. Requested permissions is a collection of string objects passed as an argument
in the Backendless API call to login a Facebook user.
Backendless ConfigurationBackendless backend must be configured with Facebook's application App ID and secret key. See the "
Social Settings" chapter of the user guide (the Manage section) for detailed instructions for configuring
Backendless with Facebook.
Easy Facebook LoginBackendless client SDK and the server-side implementation follows the following process to support the
easy login option:
1. The client application initiates the Facebook login sequence by calling a method from the
Backendless SDK.2. The invocation results in a UI dialog where the user enters their Facebook credentials and
submits the form.
3. The form submission is sent to Facebook.
4. Upon successful login, Facebook executes a redirect to the Backendless servers.
5. Backendless receives the user information from Facebook and returns it back to the client.
The diagram below illustrates the process:
APIDescription:
Perform Facebook user login with the default permission. Backendless will obtain the Facebook
fields which are available without access token - see the complete list of available fields.
http://developers.facebook.com/docs/reference/api/user/ -
7/25/2019 Backendless API for Android
23/271
User Service
2015 Backendless Corp.
23
Backendless SDK constructs a UI dialog to show the Facebook login screen.
public void Backendless.UserService.loginWithFacebook(
android.app.Activity
context,
Map
facebookFieldsMappings,AsyncCallback responder )
where:
context - must be the current activity context.
facebookFieldMappings - a mapping between the Facebook fields and Backendless user
properties. Keys must be the names of the Facebook fields,
values - the names of the Backendless properties. See the
Property Mapping sectionfor additional details.
responder - an object which receives either a return value or an error from
the server. The class must implement the
AsyncCallback interface.
Description:
Perform Facebook user login and request the specified permissions. Backendless SDK
constructs a UI dialog to show the Facebook login screen.
public void Backendless.UserService.loginWithFacebook(
android.app.Activity
context,
Map
facebookFieldsMappings,
List permissions,
AsyncCallback responder )
where:context - must be the current activity context.
facebookFieldMappings - a mapping between the Facebook fields and Backendless user
properties. Keys must be the names of the Facebook fields,
values - the names of the Backendless properties. See the
Property Mapping sectionfor additional details.
permissions - a collection of the Facebook permissions/scopes which the
application requests access to.
responder - an object which receives either a return value or an error from
the server. The class must implement the
AsyncCallback interface.
Description:
Perform Facebook user login and request the specified permissions. Backendless SDK usesthe provided WebView to host the Facebook login screen.
public void Backendless.UserService.loginWithFacebook(
android.app.Activity
context,
android.webkit.WebView
webView,
Map
facebookFieldsMappings,
-
7/25/2019 Backendless API for Android
24/271
Backendless API for Android
2015 Backendless Corp.
24
List permissions,
AsyncCallback responder )
where:
context - must be the current activity context.webView - a view component where the Facebook login dialog will be
rendered.
facebookFieldMappings - a mapping between the Facebook fields and Backendless user
properties. Keys must be the names of the Facebook fields,
values - the names of the Backendless properties. See the
Property Mapping sectionfor additional details.
permissions - a collection of the Facebook permissions/scopes which the
application requests access to.
responder - an object which receives either a return value or an error from
the server. The class must implement the
AsyncCallback interface.
Login With Facebook SDKAs the name suggests this option uses the Facebook SDK to handle the login to a Backendlessapplication. The end result is an instance of the BackendlessUserclass which contains the property
values initialized from the Facebook user account. Using the Facebook SDK with Backendless consists
of four steps:
1. Configure the environment with the Facebook SDK. Complete instructions are available at:
https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/
2. Configure Backendless applicationwith the Facebook App ID/API Key.
3.AddonActivityResult()method to the activity class (Android Activity).
4. Use an API call described below.
Adding onActivityResult() method
Before using API for logging in, you need to add onActivityResult()method to the activity
class (Android Activity) of your application as follows:
@Override publicvoidonActivityResult( intrequestCode, intresultCode, Intent
data )
{
super.onActivityResult( requestCode, resultCode, data );
Session.getActiveSession().onActivityResult( this, requestCode,
resultCode, data );
}
If onActivityResult()method is already defined, add the following line to the activity class
(Android Activity) of your application:
Session.getActiveSession().onActivityResult( this, requestCode, resultCode,data );
Description
Logs in a Facebook user into a Backendless application. Uses the SDK to display the login
dialog with the specified permissions.
public void Backendless.UserService.loginWithFacebookSdk(
android.app.Activity
https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/ -
7/25/2019 Backendless API for Android
25/271
User Service
2015 Backendless Corp.
25
context,
Map
facebookFieldsMappings,
List permissions,
AsyncCallback responder )
where:
context - must be the current activity context.
facebookFieldMappings - a mapping between the Facebook fields and Backendless user
properties. Keys must be the names of the Facebook fields,
values - the names of the Backendless properties. See the
Property Mapping sectionfor additional details.
permissions - a collection of the Facebook permissions/scopes which the
application requests access to.
responder - an object which receives either a return value or an error from
the server. The class must implement the
AsyncCallback interface.
Description:
Associates a Facebook user with BackendlessUser. Can be used when the Facebook login
must be handled independently.
public void Backendless.UserService.loginWithFacebookSession(
com.facebook.Session
facebookSession,
com.facebook.model.
GraphUser facebookUser,
Map
facebookFieldsMappings,
AsyncCallback responder )
where:
facebookSession - established and current Facebook session. Provided Facebook
session should use NonCachingTokenCachingStrategy. You
may use com.backendless.helpers.NonCachingTokenFacebookSession.openActiveSession
( Activity activity, List permissions,
Session.StatusCallback callback ), which wrappes the
creation of the non-caching session.
facebookUser - currently logged in Facebook user.
facebookFieldMappings - a mapping between the Facebook fields and Backendless user
properties. Keys must be the names of the Facebook fields,
values - the names of the Backendless properties. See the
Property Mapping sectionfor additional details.responder - an object which receives either a return value or an error from
the server. The class must implement the
AsyncCallback interface.
1.10 Update User Properties
Backendless supports the operation of user properties update for the logged in users. This operation is
useful if an application needs to provide to the users the functionality for updating user profiles and
registration properties. User must be logged in in order to update his registration properties.
-
7/25/2019 Backendless API for Android
26/271
Backendless API for Android
2015 Backendless Corp.
26
Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.update( BackendlessUser user,
AsyncCallback );
where:
user - an instance of the BackendlessUser class which contains property values to update
the user account with.
callback - an object which receives either a return value or an error from the server. The return
value from the server is an updated instance of the BackendlessUser class. The class of
the callback object must implement the AsyncCallback
interface.
Synchronous Call Method Signature:
public BackendlessUser Backendless.UserService.update
( BackendlessUser user );
where:
user - an instance of the BackendlessUserclass which contains property values to update
the user account with.
Error Codes:
The following errors may occur during the Update User Properties API call. See the Error Handling
sectionfor details on how to retrieve the error code when the server returns an error.
Error
Code
Description
2002 Version is disabled or provided wrong application info (application id or
secret key)3018 The property marked as "identity" is being updated and another user
already has the specified value which must be unique.
3024 General "update registration" error. Error message should contain
additional details.
3028 User is not logged in.
3029 Cannot modify properties of another user. Returned when one user is
logged and the call attempts to modify properties of another user.
3030 Unable to locate user account - invalid user id.
3031 A new "dynamic" property is being added, but dynamic property
definition is disabled.
3045 Required properties in the provided object do not contain values.
Asynchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.UserService.login( username, password, new
AsyncCallback()
{
-
7/25/2019 Backendless API for Android
27/271
User Service
2015 Backendless Corp.
27
public void handleResponse( BackendlessUser user )
{
// user has been logged in, now user properties can be updated
user.setProperty( "phoneNumber", "5551212" );
Backendless.UserService.update( user, new
AsyncCallback(){
public void handleResponse( BackendlessUser user )
{
// user has been updated
}
public void handleFault( BackendlessFault fault )
{
// user update failed, to get the error code call fault.
getCode()
}
});
}
public void handleFault( BackendlessFault fault )
{
// login failed, to get the error code call fault.getCode()
}
});
Synchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user;
try
{
user = Backendless.UserService.login( username, password );
}
catch( BackendlessException exception )
{
// login failed, to get the error code, call exception.getFault
().getCode()
}
try
{
user.setProperty( "phoneNumber", "5551212" ); user = Backendless.UserService.update( user );
}
catch( BackendlessException exception )
{
// update failed, to get the error code, call exception.getFault
().getCode()
}
-
7/25/2019 Backendless API for Android
28/271
Backendless API for Android
2015 Backendless Corp.
28
1.11 Get Current User
An Android application can retrieve an instance of BackendlessUser representing the currently logged in
user using the following API call:
public BackendlessUser Backendless.UserService.CurrentUser();
If a user is not logged in, the method returns null.
1.12 Logout
The Logout operation terminates user session and disassociates the AuthenticatedUserrole from the
subsequent requests made by the client application.
Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.logout( AsyncCallback
callback )
where:
callback - an object which is notified when the server completes the logout operation or returns
an error. The class must implement the AsyncCallback interface.
Synchronous Call Method Signature:
public void Backendless.UserService.logout() throws
BackendlessException;
Error Codes:
The following errors may occur during the Logout API call. See the Error Handling sect ionfor details on
how to retrieve the error code when the server returns an error.
Error
Code
Description
2002 Version is disabled or provided wrong application info (application id or
secret key)
3007 Invalid application-id or version.
3023 General error while executing logout. Error details should be available in
the message property.
Asynchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.UserService.login( username, password, new
AsyncCallback()
{
public void handleResponse( BackendlessUser user )
{
// user has been logged in
// now, let's logout
Backendless.UserService.logout( new AsyncCallback()
-
7/25/2019 Backendless API for Android
29/271
User Service
2015 Backendless Corp.
29
{
public void handleResponse( Void response )
{
// user has been logged out.
}
public void handleFault( BackendlessFault fault )
{
// something went wrong and logout failed, to get the error
code call fault.getCode()
}
});
}
public void handleFault( BackendlessFault fault )
{
// login failed, to get the error code call fault.getCode()
}
});
Synchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
BackendlessUser user;
try
{
user = Backendless.UserService.login( username, password );
}
catch( BackendlessException exception )
{ // login failed, to get the error code, call exception.getFault
().getCode()
}
try
{
// now log out:
Backendless.UserService.logout();
}
catch( BackendlessException exception )
{
// logout failed, to get the error code, call exception.getFault
().getCode()}
1.13 Password Recovery
Password recovery sends an email to the user's email address with a link where the user can change
the password.
Asynchronous Call Method Signature:
-
7/25/2019 Backendless API for Android
30/271
Backendless API for Android
2015 Backendless Corp.
30
The method call does not block - it returns immediately. The AsyncCallback argument receives either
the response or the fault returned by the Backendless servers.
public void Backendless.UserService.restorePassword( String
identityValue, AsyncCallback callback )
where:identityValue - a value for the property marked as identitywhich uniquely identifies the user
within the application.
callback - an object which is notified when the server completes the logout operation or
returns an error. The class must implement the AsyncCallback
interface.
Synchronous Call Method Signature:
public void Backendless.UserService.restorePassword( String
identityValue) throws BackendlessException;
where:
identityValue - a value for the property marked as identitywhich uniquely identifies the user
within the application.
Error Codes:
The following errors may occur during the Password Recovery API call. See the Error Handling section
for details on how to retrieve the error code when the server returns an error.
Error
Code
Description
2002 Version is disabled or provided wrong application info (application id or
secret key)
3020 Unable to find user with the specified login (invalid user identity).
3025 General password recovery error. Additional details should be available
in the "message" property of the response.3038 One of the requirement arguments (application id, version or user
identity) is missing.
Asynchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
Backendless.UserService.restorePassword( "james.bond", new
AsyncCallback()
{
public void handleResponse( Void response )
{
// Backendless has completed the operation - an email has beensent to the user
}
public void handleFault( BackendlessFault fault )
{
// password revovery failed, to get the error code call fault.
getCode()
}
-
7/25/2019 Backendless API for Android
31/271
User Service
2015 Backendless Corp.
31
});
Synchronous Call Example:
Backendless.initApp( appId, secretKet, version ); // where to get
the argument values for this call
try
{
Backendless.UserService.restorePassword( "james.bond" );
}
catch( BackendlessException exception )
{
// password recovery failed, to get the error code, call
exception.getFault().getCode()
}
1.14 Security
All Backendless API operations can be restricted either for specific user accounts or for roles. A user
account may be associated with one or more roles. Backendless supports several built-in system roles
as well as developer-defined roles. The system roles include:
NotAuthenticatedUser- any user who has not authenticated to a Backendless application.
AuthenticatedUser- any user who has successfully logged in.
SocialUser- any user who has logged in through a social network.
FacebookUser- any user who has logged in with a Facebook account.
TwitterUser- any user who has logged in with a Twitter account.
Developer-defined roles can be added using the Backendless Console. Roles are defined at the
application version level, that is a particular version of an application may have its own set of developer-
defined roles.
Backendless manages permissions as tuples consisting of:
Operation - Users interact with Backendless either via console or the API. Any request to
Backendless is an operation which may have a permission associated with it.
Resource - Some operations target specific resources. These can be data tables, messaging
channels or media tubes.
Principal - Either a specific user identity or a role associated with the user initiating the operation.
There are two levels of permissions for the API operations - global and resource-specific. The resource-
specific permissions guard access to the specific resources (data tables, messaging channels, etc).
They have higher priority and are checked first. When Backendless receives an API call from a client, it
determines the user associated with the request and obtains a list of roles associated with the user
account (for the users who have not authenticated, the NotAuthenticatedUserrole is used). The
resource-specific permissions can be set to either inherit the permission from the global matrix or
explicitly grant or deny access to the resource for the given user or role. The diagram below illustrates
the process when the resource-specific permission is set to inherit:
-
7/25/2019 Backendless API for Android
32/271
Backendless API for Android
2015 Backendless Corp.
32
When the resource-specific permission is explicitly set to either grant or deny access, the global
permissions are bypassed:
Global PermissionsThe global service permissions apply to all resources managed by a particular service. For example,
global Data Service permissions for a particular role apply to all data tables. These permissions can be
viewed and modified by clicking a role on the Users > Security and Restrictions screen in Backendless
Console:
-
7/25/2019 Backendless API for Android
33/271
User Service
2015 Backendless Corp.
33
The table below shows a global permissions matrix for a role:
-
7/25/2019 Backendless API for Android
34/271
Backendless API for Android
2015 Backendless Corp.
34
Each global permission has two states:
Grant - represented by a green check mark - grants the rights to execute an operation
Deny - represented by a red X - denies the rights to execute an operation.
To change a permission click the icon of the current state. The change will be effective immediately.
To register a new role use the "Add Role" button on the "Security and Restrictions" screen. Once a role
is added, you can configure it's global permission matrix as well as resource-specific permissions.
Resource-Specific PermissionsTo view, assign or modify resource-specific permissions, use a corresponding screen in the
Backendless Console. For example, to restrict access to a data table, switch to the Data view, select a
table and click the "Schema and Permissions" button. The user interface has two views - one is for
managing permissions for user accounts and the other for roles. To modify permissions for a user
account:
1. Click the "User Permissions" list item.
2. Enter the user name in the search field.
3. Select the user and click the "Add" button.
4. The table displays the permissions for various operations for the selected user and the resource.
5. Click an icon representing the permission state to modify the permission.
-
7/25/2019 Backendless API for Android
35/271
User Service
2015 Backendless Corp.
35
Similarly permissions can be assigned or modified for specific roles - use the "Role Permissions" list
item.
To modify the permissions for Messaging channels, click the "Messaging" icon, select a channel and
switch to the "Permissions" view.
1.15 Role To User Mapping
User accounts can be mapped to roles using the API documented below. Once a role is assigned to a
user account, any permissions assigned to the role (both grant and deny) automatically apply to all API
operations executed by the application on behalf of the user. Roles can be assigned to users in CustomBusiness Logic. This can be accomplished using the custom events.
Retrieving Available User RolesBefore you assign a user to a role, you might need to figure out what roles are available in the system.
Please note that the system will return the list of the roles associated with your user account in
Backendless. If you send the request without logging in, the system will return only one role -
NotAuthenticatedUser.
To get the list of the available user roles:
Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallback argument receives
either the response or the fault returned by the Backendless servers.Backendless.UserService.getUserRoles(newAsyncCallback());
Synchronous Call Method Signature:
BackendlessUserBackendless.UserService.getUserRoles()throws
BackendlessException;
Asynchronous Call Example:
Before retrieving the user roles, log in as described in the Loginsection. Then, retrieve the user
roles as follows:
//login user
Backendless.UserService.login("[email protected]","secretpassword",new
AsyncCallback()
{
@Override
publicvoidhandleResponse(BackendlessUserbackendlessUser)
{
// user has been logged in. Get user roles.
Backendless.UserService.getUserRoles(newAsyncCallback()
{
@Override
publicvoidhandleResponse(ListuserRoles)
http://backendless.com/documentation/business-logic/java/bl_custom_events.htm -
7/25/2019 Backendless API for Android
36/271
Backendless API for Android
2015 Backendless Corp.
36
{
//here we get all user roles - "userRoles".
}
@Override
publicvoidhandleFault(BackendlessFaultbackendlessFault)
{
// get user roles, to get the error code call backendlessFault.
getCode()
}
});
}
@Override
publicvoidhandleFault(BackendlessFaultbackendlessFault)
{
// login failed, to get the error code call backendlessFault.getCode()
}
});
Assigning a Role to User:Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallbackargument receives
either the response or the fault returned by the Backendless servers.
publicvoidBackendless.UserService.assignRole(Stringidentity,
StringroleName,
AsyncCallbackcallback
);
where:
identity - user identification. A value for the user property marked as
identity.
roleName - the name of the role to assign to the user account.callback - an object which receives either a return value or an error from
the server. The class must implement the AsyncCallback
interface.
Synchronous Call Method Signature:
publicBackendlessUser Backendless.UserService.assignRole( String
identity, String roleName ) throwsBackendlessException;
where:
identity - user identification. A value for the property marked as identity.
roleName - name of the role to assign to the user account.
Unassigning a Role from User:Asynchronous Call Method Signature:
The method call does not block - it returns immediately. The AsyncCallback argument receives
either the response or the fault returned by the Backendless servers.
publicvoidBackendless.UserService.unassignRole( Stringidentity,
String roleName,
AsyncCallback
-
7/25/2019 Backendless API for Android
37/271
User Service
2015 Backendless Corp.
37
d> callback );
where:
identity - user identification. A value for the user property marked as
identity.
roleName - name of the role to remove from the user account.callback - an object which receives either a return value or an error from
the server. The class must implement the AsyncCallback
interface.
Synchronous Call Method Signature:
publicBackendlessUser Backendless.UserService.unassignRole( String
identity, String roleName ) throwsBackendlessException;
where:
identity - user identification. A value for the user property marked as
identity.
roleName - name of the role to remove from the user account.
Error Codes:
The following errors may occur during the Login API call. See the Error Handling sect ionfor
details on how to retrieve the error code when the server returns an error.
Error
Code
Description
2002 Version is disabled or provided wrong application info (application id or
secret key)
2005 Could not find role.
3038 One of the required parameters (user identity or roleName) is null.
3057 Could not find user by id or identity.
3058 Could not assign role to user.
3059 Could not unassign role to user.
2 Data Service
2.1 Overview
The Backendless Data Service is a highly scalable, object storage system. It is available via intuitive API
which supports all basic data persistence operations - Create, Retrieve, Update and Delete (CRUD). The
Data Service operates with persistent data at the object level, that means applications use the APIs to
save, update, delete or search for objects, rather than traditional database records. Developers using the
Data Service API do not need to know or understand the databases, schema creation rules, storedprocedures or SQL syntax.
The Data Service follows the following rules when working with user objects:
1. Objects persisted by the Data Service must specify the "type" or be an instance of a class (for
client applications written in strongly-typed languages).
2. Backendless automatically creates tables for each persisted type it has not seen before and
saves objects in the corresponding tables. Each table has columns corresponding to the
properties of the persisted objects.
3. Backendless creates three additional system-level columns for each new table:
-
7/25/2019 Backendless API for Android
38/271
Backendless API for Android
2015 Backendless Corp.
38
objectId- contains a unique object ID assigned by Backendless to each object.
created- contains a timestamp when the object was first saved by Data Service
updated- contains a timestamp when the object was most recently updated. The value is
null for newly created objects.
4. When an object of a known type/class introduces any new properties throughout the lifetime of
the application, the persistence structure will be modified accordingly. When such an object ispersisted, Backendless analyzes the object's properties and automatically alters the structure of
the corresponding table if any new properties are added.
5. When an object is saved or updated, it may reference another related object (a one-to-one
relationship) or objects (one-to-many). Backendless creates the underlying tables for the main
and the referenced types and persists the hierarchy accordingly.
2.2 Setup
Pure Java and Android clients can consume the Backendless services using the class library (JAR)
provided in the Backendless SDK for Java. Make sure to reference backendless.jar located in the /lib
folder of the SDK in the project dependencies and the runtime classpath to get access to the API.
Download SDKThe SDK can be downloaded from the Backendless website.
Maven integrationThe backendless client library for Android and Java is available through the Maven repository. To add a
dependency for the library, add the following to pom.xml:
com.backendless
android
1.0
Before the Java/Android client uses any of the APIs, the code must initialize the Backendless
Application using the following call:
Backendless.initApp( application-id, secret-key, version );
Proguard ConfigurationIf your Android application uses Proguard, it is necessary to add the following configuration parameters
to proguard.cfg:
-dontwarn
-keep class weborb.** {*;}
Apps with Google Maps and GeolocationAndroid applications using Google Maps, for instance, the Geo service sample app generated by
Backendless code generator, require additional configuration in order for Google maps to be displayed.
The process of configuring an app to support Google maps consists of the following tasks:
1. Display the debug certificate fingerprint
1. Locate your debug keystore file. The file name is debug.keystore, and is created the first time
you build your project. By default, it is stored in the same directory as your Android Virtual Device
http://developer.android.com/tools/help/proguard.htmlhttps://backendless.com/downloads -
7/25/2019 Backendless API for Android
39/271
Data Service
2015 Backendless Corp.
39
(AVD) files:
OS X and Linux: ~/.android/
Windows Vista and Windows 7: C:\Users\your_user_name\.android\
2. If you are using Eclipse with ADT, and you are not sure where your debug keystore is located, you
can select Windows> Prefs> Android>Buildto check the full path, which you can then pasteinto a file explorer to locate the directory containing the keystore.
3. List the SHA-1 fingerprint.
For Linux or OS X, open a terminal window and enter the following:
keytool -list -v -keystore ~/.android/debug.keystore -alias
androiddebugkey -storepass android -keypass android
For Windows Vista and Windows 7, run:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.
keystore" -alias androiddebugkey -storepass android -keypass
android
4. You should see output similar to this:
Alias name: androiddebugkey
Creation date: Jan 01, 2013
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 4aa9b300
Valid from: Mon Jan 01 08:04:04 UTC 2013 until: Mon Jan 01
18:04:04 PST 2033
Certificate fingerprints:
MD5: AE:9F:95:D0:A6:86:89:BC:A8:70:BA:34:FF:6A:AC:F9
SHA1: BB:0D:AC:74:D3:21:E1:43:07:71:9B:62:90:AF:
A1:66:6E:44:5D:75
Signature algorithm name: SHA1withRSA
Version: 3
5. The line that begins SHA1 contains the certificate's SHA-1 fingerprint. The fingerprint is the
sequence of 20 two-digit hexadecimal numbers separated by colons.2. Create an API project in the Google APIs Console
1. In a browser, navigate to the Google APIs Console.
If you haven't used the Google APIs Console before, you're prompted to create a project that
you use to track your usage of the Google Maps Android API. Click Create Project; the
Console creates a new project called API Project. On the next page, this name appears in
the upper left hand corner. To rename or otherwise manage the project, click on its name.
If you're already using the Google APIs Console, you will immediately see a list of your
existing projects and the available services. It's still a good idea to use a new project for
Google Maps Android API, so select the project name in the upper left hand corner and then
click Create.
2. You should see a list of APIs and services in the main window. If you don't, select Servicesfrom
the left navigation bar.
3. In the list of services displayed in the center of the page, scroll down until you see Google Maps
Android API v2. To the right of the entry, click the switch indicator so that it is on.
https://code.google.com/apis/console/?noredirect -
7/25/2019 Backendless API for Android
40/271
Backendless API for Android
2015 Backendless Corp.
40
4. This displays the Google Maps Android API Terms of Service. If you agree to the terms of service,
click the checkbox below the terms of service, then click Accept. This returns you to the list of
APIs and services.3. Obtain a Google Maps API key
If your application is registered with the Google Maps Android API v2 service, then you can request
an API key. It's possible to register more than one key per project.1. Navigate to your project in the Google APIs Console.
2. In the Servicespage, verify that the "Google Maps Android API v2" is enabled.
3. In the left navigation bar, click API Access.
4. In the resulting page, click Create New Android Key....
5. In the resulting dialog, enter the SHA-1 fingerprint, then a semicolon, then your application's
package name. For example:
BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75;com.
example.android.mapexample
6. The Google APIs Console responds by displaying Key for Android apps (with certificates) followed
by a forty-character API key, for example:
AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0
4. Add the API key to your application
Follow the steps below to include the API key in your application's manifest, contained in the file
AndroidManifest.xml. From there, the Maps API reads the key value and passes it to the Google
Maps server, which then confirms that you have access to Google Maps data.
1. In AndroidManifest.xml, add the following element as a child of the element, by
inserting it just before the closing tag :
2. Substitute your API key for API_KEYin the value attribute. This element sets the key com.google.
android.maps.v2.API_KEYto the value of your API key, and makes the API key visible to any
MapFragmentin your application.3. Save AndroidManifest.xml a