本文主要是介绍LeanCloud Android 实时通信服务 搭建聊天,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Reference
https://leancloud.cn/docs/android_realtime_v2.html
https://github.com/leancloud/leanchat-android
一对一的文本聊天
。。。。。。。官网写得太详细了,还是看官网吧。。。。。。。
初始化
public class MyApplication extends Application{public void onCreate(){...AVOSCloud.initialize(this,"","");...}
}
<manifest>...<applicationandroid:name=".MyApplication"....>...<service android:name="com.avos.avoscloud.PushService" /><receiver android:name="com.avos.avoscloud.AVBroadcastReceiver"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /><action android:name="android.intent.action.USER_PRESENT" /></intent-filter></receiver>...</application></manifest>
登陆
AVIMClient imClient = AVIMClient.getInstance("Tom");
imClient.open(new IMClientCallback(){@Overridepublic void done(AVIMClient client, AVException e) {if (null != e) {// 出错了,可能是网络问题无法连接 LeanCloud 云端,请检查网络之后重试。// 此时聊天服务不可用。e.printStackTrace();} else {// 成功登录,可以开始进行聊天了(假设为 MainActivity)。Intent intent = new Intent(currentActivity, MainActivity.class);currentActivity.startActivity(intent);};}
});
建立对话
List<String> clientIds = new ArrayList<String>();
clientIds.add("Tom");
clientIds.add("Bob");// 我们给对话增加一个自定义属性 type,表示单聊还是群聊
// 常量定义:
// int ConversationType_OneOne = 0; // 两个人之间的单聊
// int ConversationType_Group = 1; // 多人之间的群聊
Map<String, Object> attr = new HashMap<String, Object>();
attr.put("type", ConversationType_OneOne);imClient.createConversation(clientIds, attr, new AVIMConversationCreatedCallback() {@Overridepublic void done(AVIMConversation conversation, AVException e) {if (null != conversation) {// 成功了,这时候可以显示对话的 Activity 页面(假定为 ChatActivity)了。Intent intent = new Intent(this, ChatActivity.class);Intent.putExtra(“conversation”, conversation);startActivity(intent);}}
});
发送消息&接受消息
AVIMMessage message = new AVIMMessage();
message.setContent("hello");
conversation.sendMessage(message, new AVIMConversationCallback() {@Overridepublic void done(AVException e) {if (null != e) {// 出错了。。。e.printStackTrace();} else {Logger.d("发送成功,msgId=" + message.getMessageId());}}
});
// 自定义消息响应类
class CustomMessageHandler extends AVIMMessageHandler {@Overridepublic void onMessage(AVIMMessage message, AVIMConversation conversation, AVIMClient client) {// 新消息到来了。在这里增加你自己的处理代码。String msgContent = message.getContent();Logger.d(conversation.getConversationid() + " 收到一条新消息:" + msgContent);}
}// application 的初始化部分
public void onCreate(){...AVOSCloud.initialize(this,"","");AVIMMessageManager.registerDefaultMessageHandler(new CustomMessageHandler());...
}// 用户登录部分
AVIMClient imClient = AVIMClient.getInstance("Bob");
imClient.open(new IMClientCallback(){@Overridepublic void done(AVIMClient client, AVException e) {if (null != e) {// 出错了,可能是网络问题无法连接 LeanCloud 云端,请检查网络之后重试。// 此时聊天服务不可用。e.printStackTrace();} else {// 成功登录,可以开始进行聊天了。};}
});
退出登录
AVIMClient.close(final AVIMClientCallback callback)
这篇关于LeanCloud Android 实时通信服务 搭建聊天的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!