====== CEC Android SDK Integration ======
Android SDK is now available for Hyphenate Customer Engagement Cloud! When you already have an Android app, you can simply create an “IM account” on the Hyphenate Customer Engagement Cloud and integrate the Android SDK into your app. By doing so, you can provide customer service for users of your app.
The Android SDK has integrated dual-channel function to ensure no loss of messages. The SDK also provides a built-in conversation UI. It would take about 5 minutes to integrate the SDK together with customer service features.
The Android SDK supports the following functions:
* Send text messages, voice messages, picture messages, and file messages.
* Receive text messages, voice messages, picture messages, file messages, and robot menu messages.
* Show the customer avatar and nickname, and the "Chat with agent" button.
* Show customer information, specify agent, specify team (See [[#step_4integrate_more_service_functions|Step 4: Integrate More Service Functions]]).
* Support notes, including text, picture and voice notes (See [[#step_5integrate_more_extended_functions|Step 5: Integrate More Extended Functions]]).
===== Step 1: Create IM Account =====
The “IM account” on the Hyphenate Customer Engagement Cloud corresponds to the application in the instant messaging (IM) console. After creating an IM account on the Hyphenate Customer Engagement Cloud, you can log in to the IM console to manage the corresponding application.
* Quick create: If you do not have an IM console account, you can click **Quick create**. The system will automatically create an IM account for you.
Bind IM account: If you already have an IM console account and have created an application on the IM console, you can go to “Admin Mode > Channels > App”, click **Create IM Account**, click **Bind IM Account**, and then fill in the display name, AppKey, ClientId, ClientSecret, IM service ID (IM username), IM password (IM user's password) to manually bind your application to Hyphenate Customer Engagement Cloud.
For a step-by-step demonstration of creating an IM account, see [[cs-en:visitoraccess:createappchannel|Create IM Account]].
===== Step 2: Environment Preparation =====
Development Tool: Android Studio.
When you integrate the Android SDK, you can refer to the “Mall” demo source code and EaseUI source code.
Download them at: https://github.com/easemob/kefu-android-demo
KefuSDK contains IM SDK 3.x. If you need both customer service and instant messaging (IM) features (excluding real-time audio and video), use the initialization, login, logout methods described in this document. Then, you can use IM SDK APIs without adding IM SDK to your project.
For more information on how to integrate IM and customer service features at the same time, please refer to: [[http://www.imgeek.org/article/825308789|Co-development Guide of IM SDK and customer service SDK -- Android]]
===== Step 3: Integrate the Basic Functions =====
The Android SDK already contains EaseUI. Complete this step, and you can provide your app users with these functions: user registration, login, logout, text messages, voice messages, picture messages, and file messages.
**Precautions:**
- You need to create an Application file and have it registered in Androidmanifest.xml.
- Check the login status before entering the conversation screen. Use this method to check the login status: ChatClient.getInstance().isLoggedInBefore()
==== build.gradle Configuration ====
Add the Android SDK and other dependencies.
In the app build.gradle file, under defaultConfig and dependencies, add the following code (gradle needs to be synchronized after that).
android{
......
defaultConfig {
ndk {
// Add the .so library of the corresponding cpu type
abiFilters 'armeabi-v7a', 'arm64-v8a'
// You can also add 'armeabi', 'x86'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Add Android SDK
compile 'com.hyphenate:kefu-easeui-android:latest.release' // Or, compile 'com.hyphenate:kefu-easeui-android:1.1.0'
// Add a glide library, as glide is used in EaseUI
compile 'com.github.bumptech.glide:glide:3.7.0' // other versions are also okay
// In EaseUI, fragment uses an android-support-v4 package
compile 'com.android.support:support-v4:23.1.1' // other versions are also okay
}
**Note:** If your Android Studio prompts the following tip after you add the above abiFilter configuration:
NDK integration is deprecated in the current plugin. Consider trying the new experimental plugin.
You need to add the gradle.properties file in the Project root directory:
android.useDeprecatedNdk=true
==== Initialization ====
The Android SDK contains EaseUI. You need to call the initialization method in the Application file (MyApplication.java in this example).
* Use the ChatClient method to initialize the SDK
* Use the UIProvider method to initialize EaseUI
Other methods of ChatClient also need to be called behind it. Such as DebugMode (log) in this document, as well as the custom notification bar and message notifications in the Demo.
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ChatClient.Options options = new ChatClient.Options();
options.setAppkey("Your appkey"); // required. Get your appkey on the "Admin Mode > Channels > App" page
options.setTenantId("Your tenantId"); // required. Get your tenantId on the "Admin Mode > Settings > Company" page
// Initialize SDK
if (!ChatClient.getInstance().init(this, options)){
return;
}
// Initialize EaseUI
UIProvider.getInstance().init(this);
// Set other properties here
}
}
// A simple version of SDK initialization
ChatClient.getInstance().init(this, new ChatClient.Options().setAppkey("zdxd#ksf").setTenantId("35"));
Note: In private deployment scenarios, you need to configure the server IP address and port in the initialization method. For more information, see [[cs-en:visitoraccess:private-server|SDK Private Deployment]].
Register the Application file in Androidmanifest.xml.
==== Register ====
There are two registration modes: open registration and authorized registration. Users can register on the client side only in open registration mode.
* Open registration: This does not require administrator authentication information during the registration process.
* Authorized registration: This requires administrator authentication information during the registration process.
We recommend Authorized registration to prevent malicious attempts of registering fraudulent accounts.
ChatClient.getInstance().createAccount("username", "password", new Callback(){});
//ErrorCode:
Error.NETWORK_ERROR network is not available
Error.USER_ALREADY_EXIST user already exists
Error.USER_AUTHENTICATION_FAILED No open registration permission (Hyphenate console [open|authorized])
Error.USER_ILLEGAL_ARGUMENT username is illegal
==== Login ====
Users need to log in before they can enter the conversation screen and have a conversation with an agent.
ChatClient.getInstance().login("username", "password", new Callback(){});
==== Login Status ====
Check the login status before entering the conversation screen.
if(ChatClient.getInstance().isLoggedInBefore()){
// Logged in. Okay to enter the conversation screen
}else{
// Not logged in. Need to log in before entering the conversation screen
}
==== Logout ====
After logout, users cannot receive messages from agents.
// The first argument indicates whether to unbind the devicetoken for push messages
ChatClient.getInstance().logout(true, new Callback(){});
==== Log ====
Set the debug mode.
// If set to true, the log will be printed to logcat. Set to false when you publish your app
ChatClient.getInstance().setDebugMode(true|false);
==== Conversation ====
Create a "Chat" button and call the following method to open the conversation screen.
Note: The "IM service ID" set in this method needs to correspond to the appkey set at initialization.
Intent intent = new IntentBuilder({Activity}.this)
.setServiceIMNumber("IM service ID") // required. Get the IM service ID on the "Admin Mode > Channels > App" page
.build();
startActivity(intent);
The conversation screen uses IM EaseUI. For information about how to modify the screen, see [[im:200androidclientintegration:135easeuiuseguide|EaseUI User Guide]].
==== Network Listener ====
Add a network listener to show whether the server is currently connected.
ChatClient.getInstance().addConnectionListener(new ChatClient.ConnectionListener() {
@Override
public void onConnected() {
// connected to the server successfully
}
@Override
public void onDisconnected(int errorcode) {
//errorcode value
//Error.USER_REMOVED account removed
//Error.USER_LOGIN_ANOTHER_DEVICE account logged in elsewhere
//Error.USER_AUTHENTICATION_FAILED Account or password is incorrect
//Error.USER_NOT_FOUND account not found
}
});
==== Message Listener ====
Add message listeners.
ChatClient.getInstance().getChat().addMessageListener(new ChatManager.MessageListener() {
@Override
public void onMessage(List list) {
// receive a regular message
}
@Override
public void onCmdMessage(List list) {
// received a command message. Command messages are not saved in the database. They are used as system notifications, such as comment updates in notes,
// and conversations served, transferred, and closed
}
@Override
public void onMessageStatusUpdate() {
// message status updated. It is used to refresh the list and display the latest status
}
@Override
public void onMessageSent() {
// Message sent. It is used to refresh the list and display the latest message
}
});
==== Add Google Push ====
=== Prerequisites ===
* GCM is used outside China.
* The devices must be installed with the Google Play service and the Google Play store.
=== Set Hyphenate Android Push Certificate ===
Step 1: Sign in to [[https://console.developers.google.com/project|Google Cloud Platform]], create a project, and enter your app name and app ID (You can fill in the app ID, or the system will assign you an app ID).
{{:start:200androidcleintintegration:gcm1.jpg?nolink|Create a project}}
Step 2: Obtain your project number.
{{:start:200androidcleintintegration:gcm2.jpg?nolink|Obtain project number}}
Step 3: Click **Credentials**, and then click **Create service key** to obtain an API key.
{{:start:200androidcleintintegration:gcm3.jpg?nolink|Obtain API key}}
=== Configure your certificate on Hyphenate console ===
Log in to [[http://console.easemob.com|Hyphenate console]], select your application, select certificates, and add your certificate. The certificate name must be the project number and the key must be the API key from Google Development Platform.
{{:cs-en:start-app9.png?nolink|Configure certificate on Hyphenate console}}
=== Configure your Android app ===
In the AndroidManifest.xml file, perform the following configuration.
**Note:** Replace the Demo package name com.easemob.helpdeskdemo with your own project name.
...
...
...
=== Code settings ===
* The project number (generated on Google Cloud Platform) must be configured in ''options.setGCMNumber(projectNumber)'';
* When the user logs out, unbind the device token using the 'ChatClient.getInstance().logout(true)'' or ''ChatClient.getInstance().logout(true,callback)'' method. If the user is kicked out, set false.
==== Add Huawei Push ====
1. Apply for a Huawei push certificate and add it to Hyphenate console.
Go to [[http://developer.huawei.com/cn/consumer/devunion/openPlatform/html/memberCenter.html#appManage#|Huawei Developer Center]], create an application, and configure the push permissions. After the creation is complete, AppId and AppSecret are generated. Go to [[http://console.easemob.com/|Hyphenate console]], select your application, choose "Push Certificate > Huawei > Add Certificate". Fill AppId in the certificate name box, and AppSecret in the certificate key box, and click **Upload**.
2. Configure AndroidManifest.xml.
...
/>
...
3. Add [[http://kefu-prod-apk.oss-cn-hangzhou.aliyuncs.com/HwPush_SDK_V2705_nomap.jar|HwPush_SDK_V2705_nomap.jar]] to the libs folder of your project.
4. Configure options in the initialization method in the Application file.
ChatClient.Options options = new ChatClient.Options();
options.setAppkey("Your appkey");// obtain your appkey at kefu.easemob.com
options.setTenantId("Your tenantId");// obtain you tenantId at kefu.easemob.com
options.setHuaweiPushAppId("huawei appid");// obtain appid at Huawei Developer Center
// SDK initialization
if (!ChatClient.getInstance().init(this, options)){
return;
}
// Set other properties here
==== App Proguard ====
Add the following lines to the proguard-rules.pro file.
# for android SDK
-keep class com.hyphenate.** {*;}
-dontwarn com.hyphenate.**
# for huawei push
# Huawei push
-keep class com.huawei.android.pushagent.** {*;}
-keep class com.huawei.android.pushselfshow.** {*;}
-keep class com.huawei.android.microkernel.** {*;}
-keep class com.baidu.mapapi.** {*;}
-keep class com.hianalytics.android.** {*;}
-dontwarn com.huawei.android.pushagent.**
-dontwarn com.huawei.android.pushselfshow.**
-dontwarn com.huawei.android.microkernel.**
-dontwarn com.github.mikephil.charting.data.**
Congratulations! You've completed the integration of Android SDK and its basic functions. Now your app users can send text messages, voice messages, picture messages, and file messages to Hyphenate Customer Engagement Cloud.
===== Step 4: Integrate More Service Functions =====
You can pass customer profiles to Hyphenate Customer Engagement Cloud, and specify the agent or team that serves the conversations.
==== Pass Customer Profile ====
Pass user information as customer profiles to Hyphenate Customer Engagement Cloud. The information is displayed on the Profile tab on the Conversations page.
Intent intent = new IntentBuilder(this)
.setServiceIMNumber("ceshia")
.setVisitorInfo(ContentFactory.createVisitorInfo(null)
.companyName("huanxin")
.email("abc@123.com")
.qq("12345")
.name("visitor_" + userName)
.nickName("nick_" + userName))
.build();
startActivity(intent);
==== Specify Agent ====
When your app user taps the "Chat" button to start a conversation, the conversation is assigned to the specified agent.
Intent intent = new IntentBuilder(this)
.setServiceIMNumber("ceshia")
.setScheduleAgent(ContentFactory.createAgentIdentityInfo("zhangsan@qq.com")) // Agent's login email address
.build();
startActivity(intent)
==== Specify Team ====
When your app user taps the "Chat" button to start a conversation, the conversation is assigned to the specified team.
The name of the team must be exactly the same as the name of the team set on the Hyphenate Customer Engagement Cloud.
Intent intent = new IntentBuilder(this)
.setServiceIMNumber("ceshia")
.setScheduleQueue(ContentFactory.createQueueIdentityInfo("Pre-sales")) // Name of a team
.build();
startActivity(intent);
==== Real-time Calling ====
Real-time calling includes network-based video calling and audio calling.
* Listen to incoming calls
Register BroadcastReceiver of the corresponding action to listen to incoming calls. When receiving the broadcasts, you can call up the call Activity in the app.
IntentFilter callFilter = new IntentFilter(ChatClient.getInstance().callManager().getIncomingCallBroadcastAction());
registerReceiver(new CallReceiver(), callFilter);
private class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// caller username
String from = intent.getStringExtra("from");
// call type
String type = intent.getStringExtra("type");
// Jump to the call page
}
}
For more information about real-time call APIs, see [[cs-en:visitoraccess:androidsdkapi|Android SDK API]].
===== Step 5: Integrate More Extended Functions =====
For information about extended functions (sending track messages, sending order messages, and note functions), see [[cs-en:visitoraccess:androidsdkapi|Android SDK API]].
For information about how to display the satisfaction evaluation invitation, refer to [[https://github.com/easemob/kefu-android-demo|Android "mall" demo source code]].