Android high imitation WeChat real-time chat Based on Baidu cloud push

Source: Internet
Author: User
Tags tojson

Android high-imitation real-time chat Based on Baidu cloud push

 

I have been imitating the interface. Today I am lucky enough to use Baidu cloud to push the imitation chat ~~~

First of all, I would like to express my special thanks to weidi1989 for sharing Android, which is based on Baidu cloud push IM. You can download it directly, saving a lot of things. In this example, we also use some weidi code, all @ author way code is weidi1989 ~~

1,

The core functions are shown in the above two figures ~~~ I took my cell phone and chatted with the simulator, and thanked the siblings in the group for helping with the test (in the friend list ).

2. Principles

The following describes the implementation principles through several questions:

1. How can I send messages to a user?

In fact, the rest api provided by Baidu cloud is used to directly push a message to a user by sending an Http request;

URL: http://developer.baidu.com/wiki/index.php? Title = docs/cplat/push/api/list

Instance:

Push_msg
Function
Push messages. This API can be used to push messages to individual users, a group of people, all users, and fixed devices.
HTTP Request Method
POST
URL
Http [s]: // channel.api.duapp.com/rest/2.0/channel/channel

....

2. It is true that messages can be pushed to a user or a group of users. How can I obtain the nickname "Shenma" of a user? I cannot store such data in the cloud for hundreds of times?

Well, it actually uses a clever method. When the user installs the software for the first time, the user is required to fill in the registration information, that is, the nickname, and so on. When the user completes filling in the information, when you click log on:

1. Send a special message. For example, the message carries a hello field and broadcasts it to all users;

2. When receiving a message, other users first determine whether the hello field has a value. If yes, the new user is added, the new user is saved to the local database, and then the user list is updated;

3. Other users send a message to this new user with a special field, such as welcome. When a new user receives a message containing the welcome field, it indicates that this is a reply to the new user hello, add an existing user to the user list of the new user.

This is the basic principle. You can even use the above principles to add some functions to delete friends. For example, when a user clicks to delete a friend, a special message is sent to the deleted object, the other party receives the message and deletes the message.

I believe that after everyone understands the principle, this example instantly changes from high to low. This Nima, so easy, no one will ~~~

 

3. Core code analysis

Because the amount of code is quite large and you don't want to split it into several blogs, you are ready to explain the core code. Others can read the source code by themselves ~

For the main interface of this example, refer to: High imitation 5.2.1 Main Interface Architecture contains Message notification

For more information about Baidu cloud push, see: get started with Baidu cloud push for Android

Okay, the most important thing is to receive the Referer pushed by Baidu cloud.

1. onBind

First, the callback bound when the user logs on for the first time

 

@ Overridepublic void onBind (final Context context, int errorCode, String appid, String userId, String channelId, String requestId) {String responseString = onBind errorCode = + errorCode + appid = + appid + userId = + userId + channelId = + channelId + requestId = + requestId; Log. e (TAG, responseString); if (errorCode = 0) {SharePreferenceUtil util = PushApplication. getInstance (). getSpUtil (); util. setAppId (appid); util. setChannelId (channelId); util. setUserId (userId);} else // if the network is normal, retry {if (NetUtil. isNetConnected (context) {T. showLong (context, startup failed, retry ...); new Handler (). postDelayed (new Runnable () {@ Overridepublic void run () {PushManager. startWork (context, PushConstants. LOGIN_TYPE_API_KEY, PushApplication. API_KEY) ;}}, 2000); // verify the else {T. showLong (context, R.string.net _ error_tip) ;}// callback function for (int I = 0; I <bindListeners. size (); I ++) bindListeners. get (I ). onBind (userId, errorCode );}
If the initial binding is successful, use SharedPreferences to store userId, channelId, and other data.

 

Then callback: bindListeners. get (I). onBind (userId, errorCode); send notifications to all registered events

See listener. onBind.

 

/*** Receive notification */@ Overridepublic void onBind (String userId, int errorCode) {Log. e (TAG, Login Activity onBind); if (errorCode = 0) {Log. e (TAG, Login Activity onBind success); // If the account is successfully bound, a new User message "User u = new User (mSpUtil)" is pushed to the person with the same tag for the first time. getUserId (), mSpUtil. getChannelId (), mSpUtil. getNick (), mSpUtil. getHeadIcon (), 0); mUserDB. addUser (u); // Add yourself to the database Message firstSendMsg = new Message (System. currentTimeMilli S (),); firstSendMsg. setHello (hello); task = new SendMsgAsyncTask (mGson. toJson (firstSendMsg),); task. setOnSendScuessListener (new OnSendScuessListener () {@ Overridepublic void sendScuess () {if (mLoadingDialog! = Null & mLoadingDialog. isVisible () mLoadingDialog. dismiss (); mHandler. removeCallbacks (mConnTimeoutCallback); finish (); Intent intent = new Intent (LoginActivity. this, MainActivity. class); startActivity (intent) ;}}); task. send ();}}
First, save yourself to the local database, then send a Message to all users, and set a special field hello, which is part of the above principle analysis ~

 

 

2. onMessage

Receive onMessage from the worker pushed by Baidu cloud

 

@ Overridepublic void onMessage (Context context, String message, String customContentString) {String messageString = received message = + message + customContentString = + customContentString; Log. e (TAG, messageString); Message receivedMsg = PushApplication. getInstance (). getGson (). fromJson (message, Message. class); // processes parseMessage (receivedMsg) for the received message;}/*** message: 1. Carries hello, indicating that a new user joins the message and should automatically reply to a world message; 2. Common message ;**@ Param msg */private void parseMessage (Message msg) {String userId = msg. getUserId (); // if (userId. equals (PushApplication. getInstance (). getSpUtil (). getUserId () return; if (checkHasNewFriend (msg) | checkAutoResponse (msg) return; // common message UserDB userDB = PushApplication. getInstance (). getUserDB (); User user = userDB. selectInfo (userId); // if (user = null) {user = new User (userId, msg. getChannelId (), Msg. getNickname (), 0, 0); userDB. addUser (user); // The Panel for notification listening (onNewFriendListener listener: friendListeners) listener. onNewFriend (user);} if (msgListeners. size ()> 0) {// when there is a listener, pass it down for (int I = 0; I <msgListeners. size (); I ++) msgListeners. get (I ). onNewMessage (msg);} else // No listener currently, that is, processing background status {// store the new message ChatMessage chatMessage = new ChatMessage (msg. getMessage (), true, userId, msg. getHeadIcon (), msg. GetNickname (), false, TimeUtil. getTime (msg. getTimeSamp (); PushApplication. getInstance (). getMessageDB (). add (userId, chatMessage); showNotify (msg) ;}/ *** check whether automatic reply ** @ param msg */private boolean checkAutoResponse (Message msg) {String world = msg. getWorld (); String userId = msg. getUserId (); if (! TextUtils. isEmpty (world) {User u = new User (userId, msg. getChannelId (), msg. getNickname (), msg. getHeadIcon (), 0); PushApplication. getInstance (). getUserDB (). addUser (u); // save or update a friend // The Panel of the notification listener for (onNewFriendListener listener: friendListeners) listener. onNewFriend (u); return true;} return false;}/*** check whether a new user is added ** @ param msg */private boolean checkHasNewFriend (Message msg) {String userId = msg. getUserId (); S Tring hello = msg. getHello (); // if (! TextUtils. isEmpty (hello) {Log. e (checkHasNewFriend, msg. getUserId (); // new User u = new User (userId, msg. getChannelId (), msg. getNickname (), msg. getHeadIcon (), 0); PushApplication. getInstance (). getUserDB (). addUser (u); // save or update friend T. showShort (PushApplication. getInstance (), u. getNick () + Add); // returns a Response Message = new message (System. currentTimeMillis (),); message. setWorld (world); new SendMsgAsyncTask (PushApplication. getInstance (). getGson (). toJson (message), userId); // Panel of the notification listener for (onNewFriendListener listener: friendListeners) listener. onNewFriend (u); return true;} return false ;}

When a new message is received:

 

1. First, determine whether it is sent by yourself. Yes, ignore it;

2. Determine whether the hello field is included. If the hello field is included, the hello field is saved to the friends list and a message with the welcome field is returned;

3. Check whether the welcome field is included and saved to the friends list.

4. If it is not 1, 2, or 3, it must be a common message. Save the message to the local database and set the send callback for all the message listeners ~

 

Callback for receiving new messages in the MainTabFriends. java User List:

 

/*** When a new Message is received * // @ Overridepublic void onNewMessage (message) {// if it is sent by yourself, if (Message. getUserId () = mSpUtils. getUserId () return; // if the user already has unread messages, update the number of unread messages and notify the interface for updating unread messages. Finally, notifyDataSetChangedString userId = message. getUserId (); if (mUserMessages. containsKey (userId) {mUserMessages. put (userId, mUserMessages. get (userId) + 1);} else {mUserMessages. put (userId, 1) ;}munreadedmsgs ++; yyunreadedmsg (); // store the new message ChatMessage chatMessage = new ChatMessage (message. getMessage (), true, userId, message. getHeadIcon (), message. getNickname (), false, TimeUtil. getTime (message. getTimeSamp (); mApplication. getMessageDB (). add (userId, chatMessage); // notifies the listview to change the mAdapter data. notifyDataSetChanged ();}

1. if it is sent by yourself, it will not be processed.

 

2. If the current message is sent to an unread message, the number of unread messages of the user is updated (the number of unread messages is displayed on the user Item ), update the total number of unread messages (the sum of unread messages is displayed on the friend Tab), and store the message.

3. Refresh the interface

 

New message callback in ChattingActivity. java chat interface

 

@ Overridepublic void onNewMessage (Message message) {// obtain the reply Message if (mFromUser. getUserId (). equals (message. getUserId () {ChatMessage chatMessage = new ChatMessage (); chatMessage. setComing (true); chatMessage. setDate (new Date (message. getTimeSamp (); chatMessage. setMessage (message. getMessage (); chatMessage. setUserId (message. getUserId (); chatMessage. setNickname (message. getNickname (); chatMessage. setReaded (true); mDatas. add (chatMessage); mAdapter. notifyDataSetChanged (); mChatMessagesListView. setSelection (mDatas. size ()-1); // save it to the database. The current chat record is mApplication. getMessageDB (). add (mFromUser. getUserId (), chatMessage );}}

First, determine whether the message is sent by the user chatting. If yes, directly store the message to the database and refresh the chat interface;

 

 

 

Well, the details are not described. You can check the source code and check the bug. If you find the bug, you can leave a message to help you learn other kids shoes, thank you ~~~~~~~~~~~~~~

Ps: The status is not good recently. I want to drink pulsating ~~~~

 

Click to download the source code. You can first install the apk In the compressed file for testing, so that you can find other partners ~~~

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.