Don’t Do the Dishes studio @Author fhyPayaso

In the development process of some small projects, there may be requirements to realize the chat function in the requirements, and it may be tedious to realize it completely by the back-end. Here we choose to realize the simple chat function through the integration of loop SDK.

First, preliminary preparation

  • First of all, we need to register a developer account on the official website of Huanxin and create an application to obtain the AppKey. Please refer to registration and Create an Application for details

Second, integrate SDK

  • Add the following dependencies to biuld.gradle

    The compile 'com. Google. Android. GMS: play - services - GCM: 9.4.0' compile 'com. Hyphenate: hyphenate - SDK: 3.3.0'Copy the code
  • Add the required permissions in the Manifest, and remember to add the AppKey you registered in android: Value

    <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:name="Your Application"> <! <meta-data android:name="EASEMOB_APPKEY" Android :value="Your AppKey"/> <! - required SDK service SDK core functions - > < service android: name = "com. Hyphenate. Chat. EMChatService" android: exported = "true" / > <service android:name="com.hyphenate.chat.EMJobService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" /> <! - required SDK receiver - > < receiver android: name = "com. Hyphenate. Chat. EMMonitorReceiver" > < intent - filter > < action android:name="android.intent.action.PACKAGE_REMOVED"/> <data android:scheme="package"/> </intent-filter> <! - optional filter - > < intent - filter > < action android: name = "android. Intent. Action. BOOT_COMPLETED" / > < action android:name="android.intent.action.USER_PRESENT"/> </intent-filter> </receiver> </application>Copy the code

Initialize the SDK

  • Start by initializing the SDK Settings in the onCreate method of the Application

    EMOptions options = new EMOptions(); / / here you can make some initialization Settings, such as the default add buddy, don't need to verify, can change to need to verify the options. SetAcceptInvitationAlways (false); . // initialize emClient.getInstance ().init(this, options);Copy the code
  • If your application includes third-party login functionality, you need to add a judgement before initializing the sdkemClient.getInstance ().init(applicationContext, options) method to prevent SDK initialization:

    appContext = this; int pid = android.os.Process.myPid(); String processAppName = getAppName(pid); // The application:onCreate will be called twice if the APP has enabled a remote service. // To prevent the SDK from being initialized twice, this will ensure that the SDK is initialized once. // The default APP will run under the default process name of the package name. The process if the name is not APP process name immediately return the if (processAppName = = null | |! processAppName.equalsIgnoreCase(appContext.getPackageName())) { Log.e(TAG, "enter the service process!" ); // The application::onCreate is called by the service and returns a return; }Copy the code
  • GetAppName () is implemented as:

      private String getAppName(int pID) {
      
      	String processName = null;
      	ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
      	List l = am.getRunningAppProcesses();
      	Iterator i = l.iterator();
      	PackageManager pm = this.getPackageManager();
      	
      	while (i.hasNext()) {
      		ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
      		try {
      			if (info.pid == pID) {
      				processName = info.processName;
      				return processName;
              	}
          	} catch (Exception e) {
              // Log.d("Process", "Error>> :"+ e.toString());
          	}
      	}
      	return processName;
      }
    Copy the code

4. Login and registration

registered

There are two registration modes, open registration and authorized registration.

  • Open registration: Can be directly registered in the client, can be used in testing, not recommended in the official use environment.
  • Authorization registration: Authorization registration requires the backend to register through the REST API provided by Circ, and then the information is saved to the server and returned to the client.

Specific methods are as follows:

new Thread(new Runnable() { @Override public void run() { try { EMClient.getInstance().createAccount(editUsername.getText().toString().trim(), editPassword.getText().toString().trim()); Log. I (TAG, "register: successful "); } catch (HyphenateException e) {// Failure to register will throw an exception e.printStackTrace(); Log. I (TAG, "register: failed to register "+ LLDB TerrorCode () +", "+ LLDB etMessage()); } } }).start();Copy the code

Emclient.getinstance ().createAccount(String username,password) is a synchronous method, so you need to create your own thread when using it.

The login

The login method is an asynchronous method that can be called directly and prints information in the callback function:

EMClient.getInstance().login(editUsername.getText().toString().trim(), editPassword.getText().toString().trim(), New EMCallBack() {@override public void onSuccess() {// Ensure that local sessions and groups are loaded after entering the main page EMClient.getInstance().groupManager().loadAllGroups(); EMClient.getInstance().chatManager().loadAllConversations(); startActivity(new Intent(LoginActivity.this, FriendListActivity.class)); Log. I (TAG, "onSuccess: login succeeded "); } @override public void onError(int code, String error) {log. I (TAG, "onError: login failed, "+ error); } @Override public void onProgress(int progress, String status) { } });Copy the code

Automatic login

If you want to disable automatic login, you can set options.setautologin (false) during SDK initialization.

Log out

EMClient.getInstance().logout(true, new EMCallBack() { @Override public void onSuccess() { Log.i(TAG, "onSuccess: Exit successful "); } @Override public void onProgress(int progress, String status) { } @Override public void onError(int code, String message) {log. I (TAG, "onError: exit failed, "+ message); }});Copy the code

If the third-party push function is integrated, the first parameter in the method must be set to true to unbind the device token. Otherwise, the device may still receive push after exiting.

Five, friend management

Add buddy

Emclient.getinstance ().contactManager().addContact(toAddUsername, reason);Copy the code

Remove buddy

EMClient.getInstance().contactManager().deleteContact(username);
Copy the code

Get a list of friends

List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
Copy the code

Ring mail is just an instant messaging channel. Huanxin itself does not provide user system. Huanxin does not store any APP business data, nor does it store any APP user information. Therefore, we need to query the details of the user through the obtained username to the app server.

Search for friends

Huanxin SDK does not provide an interface for searching friends, but we can import the username of all users into Huanxin through the SDK interface of the server to ensure that the friends found can be added, and then obtain the username of specific users through the search of the server to realize the function of adding friends through search.

Instant messaging

Text message sending

Specific methods are as follows:

/ / create a text message, the content of news text, the username username EMMessage for each other message = EMMessage. CreateTxtSendMessage (the content, the username); If (chatType == CHATTYPE_GROUP) message.setchatType (chattype.groupchat); if (chatType == CHATTYPE_GROUP) message.setchatType (chattype.groupchat); Emclient.getinstance ().chatManager().sendMessage(message);Copy the code

Message receive monitor

Message listening can be set by implementing the EMMessageListener interface

public class ChatActivity extends AppCompatActivity implements EMMessageListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); Emclient.getinstance ().chatManager().addMessagelistener (this); } @override public void onMessageReceived(List<EMMessage> messages) { } @override public void onCmdMessageReceived(List<EMMessage> messages) { } @override public void onMessageRead(List<EMMessage> messages) {// Receiving read messages} @override public void onMessageRead(List<EMMessage> messages) OnMessageDelivered (List<EMMessage> messages) {Override public void hanged(EMMessage message, Object change) {// Message status change}}Copy the code

Remove the Listener when it is not needed, as in the activity onDestroy()

EMClient.getInstance().chatManager().removeMessageListener(this);
Copy the code

Get message record

Specific methods are as follows:

EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username); / / get all the messages of this session List < EMMessage > messages = conversation. GetAllMessages ();Copy the code

Display messages to UI in RecyclerView adapter

EMTextMessageBody textMessageBody = (EMTextMessageBody) emMessage.getBody();
txtMessage.setText(textMessageBody.getMessage());
Copy the code

SDK loading by default chat record up to 20 pieces, can be set when initializing the SDK options. SetNumberOfMessagesLoaded (number)

This article only briefly introduces the realization of text instant chat method, SDK more functions please see the circular letter development document