当前位置:   article > 正文

java后台程序员转android 《二》之 集成腾讯云 im 及时通讯及采坑记录_com.tencent.imsdk.v2

com.tencent.imsdk.v2

目录

前言:

1.第一步创建一个工程

2.通过文档下载sdk 顺便做个集成

3.献上一个集成的demo

3.1ainActivity.xml 编写一些功能

4.java 代码

4.1介绍

5.java server 后台集成代码


前言:

最近公司打算做先关android 方面的技术,然后招andirod 还挺贵,老板打算让我来搞搞,那就搞一搞,顺便做些总结,从java后台转型快速入手 android 的小策略。

 

andoird 官网地址 https://developer.android.google.cn/

 

1.第一步创建一个工程

 

2.通过文档下载sdk 顺便做个集成

 

3.献上一个集成的demo

 

3.1ainActivity.xml 编写一些功能

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="#C4E0FC"
  8. tools:context=".im">
  9. <TextView
  10. android:id="@+id/abc"
  11. android:layout_width="0dp"
  12. android:layout_height="165dp"
  13. android:text="Hello World!"
  14. app:layout_constraintBottom_toBottomOf="parent"
  15. app:layout_constraintHorizontal_bias="0.0"
  16. app:layout_constraintLeft_toLeftOf="parent"
  17. app:layout_constraintRight_toRightOf="parent"
  18. app:layout_constraintTop_toTopOf="parent"
  19. app:layout_constraintVertical_bias="0.72" />
  20. <Button
  21. android:id="@+id/button"
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:layout_marginTop="10dp"
  25. android:layout_marginEnd="5dp"
  26. android:layout_marginRight="5dp"
  27. android:onClick="shutdownLogin"
  28. android:text="退出im"
  29. app:layout_constraintEnd_toStartOf="@+id/button3"
  30. app:layout_constraintTop_toTopOf="parent" />
  31. <Button
  32. android:id="@+id/button1"
  33. android:layout_width="wrap_content"
  34. android:layout_height="wrap_content"
  35. android:layout_marginTop="10dp"
  36. android:layout_marginEnd="5dp"
  37. android:layout_marginRight="5dp"
  38. android:onClick="startupLogin"
  39. android:text="登录im"
  40. app:layout_constraintEnd_toEndOf="parent"
  41. app:layout_constraintTop_toTopOf="parent" />
  42. <Button
  43. android:id="@+id/button2"
  44. android:layout_width="wrap_content"
  45. android:layout_height="wrap_content"
  46. android:layout_marginTop="10dp"
  47. android:layout_marginEnd="5dp"
  48. android:layout_marginRight="5dp"
  49. android:onClick="oneSession"
  50. android:text="单聊会话"
  51. app:layout_constraintEnd_toStartOf="@+id/button1"
  52. app:layout_constraintTop_toTopOf="parent" />
  53. <Button
  54. android:id="@+id/button3"
  55. android:layout_width="wrap_content"
  56. android:layout_height="wrap_content"
  57. android:layout_marginTop="10dp"
  58. android:layout_marginEnd="5dp"
  59. android:layout_marginRight="5dp"
  60. android:onClick="getGroupSession"
  61. android:text="群聊会话"
  62. app:layout_constraintEnd_toStartOf="@+id/button2"
  63. app:layout_constraintTop_toTopOf="parent" />
  64. <Button
  65. android:id="@+id/button4"
  66. android:layout_width="wrap_content"
  67. android:layout_height="wrap_content"
  68. android:layout_marginEnd="5dp"
  69. android:layout_marginRight="5dp"
  70. android:layout_marginBottom="10dp"
  71. android:onClick="sendInfo"
  72. android:text="发送消息"
  73. app:layout_constraintBottom_toBottomOf="parent"
  74. app:layout_constraintEnd_toEndOf="parent" />
  75. <Button
  76. android:id="@+id/button6"
  77. android:layout_width="wrap_content"
  78. android:layout_height="wrap_content"
  79. android:layout_marginEnd="5dp"
  80. android:layout_marginRight="5dp"
  81. android:layout_marginBottom="10dp"
  82. android:onClick="showListenerInfo"
  83. android:text="获取消息"
  84. app:layout_constraintBottom_toBottomOf="parent"
  85. app:layout_constraintEnd_toStartOf="@+id/button4" />
  86. <Button
  87. android:id="@+id/button7"
  88. android:layout_width="wrap_content"
  89. android:layout_height="wrap_content"
  90. android:layout_marginEnd="5dp"
  91. android:layout_marginRight="5dp"
  92. android:layout_marginBottom="10dp"
  93. android:onClick="createOpenGroup"
  94. android:text="创公开建群"
  95. app:layout_constraintBottom_toBottomOf="parent"
  96. app:layout_constraintEnd_toStartOf="@+id/button6" />
  97. <Button
  98. android:id="@+id/button8"
  99. android:layout_width="wrap_content"
  100. android:layout_height="wrap_content"
  101. android:layout_marginEnd="5dp"
  102. android:layout_marginRight="5dp"
  103. android:layout_marginBottom="10dp"
  104. android:onClick="createChatGroup"
  105. android:text="创建聊天室"
  106. app:layout_constraintBottom_toBottomOf="parent"
  107. app:layout_constraintEnd_toStartOf="@+id/button6" />
  108. <EditText
  109. android:id="@+id/t1"
  110. android:layout_width="270dp"
  111. android:layout_height="wrap_content"
  112. android:layout_marginStart="80dp"
  113. android:layout_marginLeft="80dp"
  114. android:layout_marginTop="44dp"
  115. android:hint="输入链接的账户"
  116. app:layout_constraintStart_toStartOf="parent"
  117. app:layout_constraintTop_toBottomOf="@+id/button" />
  118. <EditText
  119. android:id="@+id/t2"
  120. android:layout_width="270dp"
  121. android:layout_height="wrap_content"
  122. android:layout_marginStart="80dp"
  123. android:layout_marginLeft="80dp"
  124. android:layout_marginTop="15dp"
  125. android:hint="输入发送的内容"
  126. app:layout_constraintStart_toStartOf="parent"
  127. app:layout_constraintTop_toBottomOf="@+id/t1" />
  128. <EditText
  129. android:id="@+id/t3"
  130. android:layout_width="270dp"
  131. android:layout_height="wrap_content"
  132. android:layout_marginStart="80dp"
  133. android:layout_marginLeft="80dp"
  134. android:layout_marginTop="19dp"
  135. android:hint="输入个人账号"
  136. app:layout_constraintStart_toStartOf="parent"
  137. app:layout_constraintTop_toBottomOf="@+id/t2" />
  138. <EditText
  139. android:id="@+id/t5"
  140. android:layout_width="270dp"
  141. android:layout_height="wrap_content"
  142. android:layout_marginStart="80dp"
  143. android:layout_marginLeft="80dp"
  144. android:layout_marginTop="10dp"
  145. android:hint="输入群名称"
  146. app:layout_constraintStart_toStartOf="parent"
  147. app:layout_constraintTop_toBottomOf="@+id/t3" />
  148. <Button
  149. android:id="@+id/button9"
  150. android:layout_width="wrap_content"
  151. android:layout_height="wrap_content"
  152. android:layout_marginEnd="5dp"
  153. android:layout_marginRight="5dp"
  154. android:layout_marginBottom="10dp"
  155. android:onClick="createAVChatGroup"
  156. android:text="创建直播群"
  157. app:layout_constraintBottom_toBottomOf="parent"
  158. app:layout_constraintEnd_toStartOf="@+id/button7" />
  159. <Button
  160. android:id="@+id/button10"
  161. android:layout_width="wrap_content"
  162. android:layout_height="wrap_content"
  163. android:layout_marginEnd="5dp"
  164. android:layout_marginRight="5dp"
  165. android:layout_marginBottom="5dp"
  166. android:onClick="addGroup"
  167. android:text="添加到群中"
  168. app:layout_constraintBottom_toTopOf="@+id/button4"
  169. app:layout_constraintEnd_toEndOf="parent" />
  170. </android.support.constraint.ConstraintLayout>

 

4.java 代码

  1. package com.example.im;
  2. import android.os.Environment;
  3. import android.os.Handler;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.EditText;
  9. import android.widget.TextView;
  10. import com.tencent.imsdk.TIMCallBack;
  11. import com.tencent.imsdk.TIMConversation;
  12. import com.tencent.imsdk.TIMConversationType;
  13. import com.tencent.imsdk.TIMElem;
  14. import com.tencent.imsdk.TIMElemType;
  15. import com.tencent.imsdk.TIMGroupManager;
  16. import com.tencent.imsdk.TIMGroupMemberInfo;
  17. import com.tencent.imsdk.TIMGroupMemberRoleType;
  18. import com.tencent.imsdk.TIMLogLevel;
  19. import com.tencent.imsdk.TIMManager;
  20. import com.tencent.imsdk.TIMMessage;
  21. import com.tencent.imsdk.TIMMessageListener;
  22. import com.tencent.imsdk.TIMSdkConfig;
  23. import com.tencent.imsdk.TIMTextElem;
  24. import com.tencent.imsdk.TIMValueCallBack;
  25. import java.net.URLConnection;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import android.os.Bundle;
  29. import android.support.v7.app.AppCompatActivity;
  30. import android.util.Log;
  31. import android.view.View;
  32. import android.widget.Button;
  33. import java.io.BufferedReader;
  34. import java.io.IOException;
  35. import java.io.InputStream;
  36. import java.io.InputStreamReader;
  37. import java.net.HttpURLConnection;
  38. import java.net.MalformedURLException;
  39. import java.net.URL;
  40. import java.util.concurrent.Callable;
  41. import java.util.concurrent.FutureTask;
  42. public class im extends AppCompatActivity {
  43. private int sdkAppId = 1400187322;
  44. private String accountType = "0";
  45. private TextView mtextView;
  46. private EditText meditView1;
  47. private EditText meditView2;
  48. private EditText meditView3;
  49. private EditText meditView5;
  50. private Handler mHandler;
  51. @Override
  52. protected void onCreate(Bundle savedInstanceState) {
  53. super.onCreate(savedInstanceState);
  54. setContentView(R.layout.activity_im);
  55. mHandler = new Handler();
  56. mtextView = findViewById(R.id.abc);
  57. meditView1 = findViewById(R.id.t1);
  58. meditView2 = findViewById(R.id.t2);
  59. meditView3 = findViewById(R.id.t3);
  60. meditView5 = findViewById(R.id.t5);
  61. initIm();
  62. }
  63. //初始化 SDK 基本配置
  64. public void initIm(){
  65. TIMSdkConfig config = new TIMSdkConfig(sdkAppId)
  66. // .setAccoutType(accountType)
  67. .enableLogPrint(true) // 是否在控制台打印Log?
  68. .setLogLevel(TIMLogLevel.DEBUG) // Log输出级别(debug级别会很多)
  69. .setLogPath(Environment.getExternalStorageDirectory().getPath() + "/justfortest/");// Log文件存放在哪里?
  70. //初始化 SDK
  71. TIMManager.getInstance().init(getApplicationContext(), config);
  72. }
  73. //服务器获取 sgin地址 这个方法用来通过后台获取用户的usersgin
  74. private String loginSginUrl = "http://XX:8080/im/getUserSign?username=";
  75. //im登陆
  76. public void startupLogin(View v){
  77. String userId = meditView3.getText().toString();//账户
  78. String userSign = getUrlClient(loginSginUrl+userId);
  79. TIMManager.getInstance().login(userId, userSign, new TIMCallBack() {
  80. @Override
  81. public void onError(int code, String desc) {Log.d("loginUser","---------------------------login failed. code: " + code + " errmsg: " + desc);
  82. exitText("login failed. code: " + code + " errmsg: " + desc);
  83. }
  84. @Override
  85. public void onSuccess() {
  86. exitText("登录seccess");
  87. }
  88. });
  89. }
  90. //登出
  91. public void shutdownLogin(View v){
  92. TIMManager.getInstance().logout(new TIMCallBack() {
  93. @Override
  94. public void onError(int code, String desc) {
  95. exitText("登出error");
  96. }
  97. @Override
  98. public void onSuccess() {
  99. removeText("登出seccess");
  100. }
  101. });
  102. }
  103. private TIMConversation conversation; //获取imsession
  104. // //获取单聊会话
  105. public void oneSession(View v){
  106. String peer = meditView1.getText().toString(); //获取与用户 "test_user" 的会话
  107. conversation = TIMManager.getInstance().getConversation(
  108. TIMConversationType.C2C, //会话类型:单聊
  109. peer);
  110. exitText("单聊回话seccess");
  111. getInfoIM();
  112. }
  113. //获取群聊会话
  114. public void getGroupSession(View v){
  115. String groupId = ""+meditView5.getText().toString();//获取与群组 "test_group" 的会话
  116. conversation = TIMManager.getInstance().getConversation(
  117. TIMConversationType.Group, //会话类型:群组
  118. groupId); //群组 ID
  119. exitText("群回话seccess");
  120. getInfoIM();
  121. }
  122. //添加到群中
  123. public void addGroup(View v){
  124. String groupId = ""+meditView5.getText().toString();//获取与群组 "test_group" 的会话
  125. TIMGroupManager.getInstance().applyJoinGroup(groupId, "some reason", new TIMCallBack() {
  126. @java.lang.Override
  127. public void onError(int code, String desc) {
  128. exitText("disconnected"+code+desc);
  129. }
  130. @java.lang.Override
  131. public void onSuccess() {
  132. exitText("join group");
  133. }
  134. });
  135. }
  136. //发送消息 //构造一条消息并添加一个文本内容
  137. public void sendInfo(View v){
  138. TIMMessage msg = new TIMMessage();
  139. TIMTextElem elem = new TIMTextElem();
  140. String params = meditView2.getText().toString();
  141. elem.setText(params);
  142. msg.addElement(elem);
  143. //发送消息
  144. conversation.sendMessage(msg, new TIMValueCallBack<TIMMessage>() {
  145. @Override
  146. public void onError(int code, String desc) {//发送消息失败
  147. exitText("发送消息失败 " + code + " errmsg: " + desc);
  148. }
  149. @Override
  150. public void onSuccess(TIMMessage msg) {//发送消息成功
  151. exitText("发送消息seccess");
  152. }
  153. });
  154. }
  155. //获取消息
  156. public void getInfoIM(){
  157. TIMManager.getInstance().addMessageListener(new TIMMessageListener() {//消息监听器
  158. @Override
  159. public boolean onNewMessages(List<TIMMessage> msgs) {//收到新消息
  160. for (int z= 0; z < msgs.size(); z++){
  161. TIMMessage msg = msgs.get(z);
  162. for(int i = 0; i < msg.getElementCount(); ++i) {
  163. TIMElem elem = msg.getElement(i);
  164. TIMElemType elemType = elem.getType();//获取当前元素的类型
  165. Log.d("", "elem type: " + elemType.name());
  166. if (elemType == TIMElemType.Text) {//处理文本消息
  167. TIMTextElem elemnew = (TIMTextElem) elem;
  168. exitText(msg.getSender()+":"+elemnew.getText());
  169. } else if (elemType == TIMElemType.Image) { //处理图片消息
  170. }//...处理更多消息
  171. }
  172. }
  173. //消息的内容解析请参考消息收发文档中的消息解析说明
  174. return true; //返回true将终止回调链,不再调用下一个新消息监听器
  175. }
  176. });
  177. }
  178. 创建公开群
  179. public void createOpenGroup(View v){
  180. TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("Public", "test_group1");
  181. //创建群组
  182. TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
  183. @Override
  184. public void onError(int code, String desc) {
  185. Log.d("createGroup", "create group failed. code: " + code + " errmsg: " + desc);
  186. exitText("创建群error");
  187. }
  188. @Override
  189. public void onSuccess(String s) {
  190. Log.d("createGroup", "create group succ, groupId:" + s);
  191. exitText("创建群seccess");
  192. }
  193. });
  194. }
  195. //创建聊天室
  196. public void createChatGroup(View v){
  197. TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("Public", "test_group1");
  198. TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
  199. @Override
  200. public void onError(int code, String desc) {
  201. Log.d("createGroup", "create group failed. code: " + code + " errmsg: " + desc);
  202. exitText("创建群error");
  203. }
  204. @Override
  205. public void onSuccess(String s) {
  206. Log.d("createGroup", "create group succ, groupId:" + s);
  207. exitText("创建群seccess");
  208. }
  209. });
  210. }
  211. //创建直播大群
  212. public void createAVChatGroup(View v){
  213. TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("AVChatRoom", meditView5.getText().toString());
  214. TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
  215. @Override
  216. public void onError(int code, String desc) {
  217. Log.d("createGroup", "create group failed. code: " + code + " errmsg: " + desc);
  218. exitText("创建群error");
  219. }
  220. @Override
  221. public void onSuccess(String s) {
  222. Log.d("createGroup", "create group succ, groupId:" + s);
  223. exitText("创建群seccess");
  224. }
  225. });
  226. }
  227. //想文本中添加内容
  228. public void exitText(final String val){
  229. mHandler.post(new Runnable() {
  230. @Override
  231. public void run() {
  232. mtextView.append(";"+val);
  233. }
  234. });
  235. }
  236. //删除内容
  237. public void removeText(final String val){
  238. mHandler.post(new Runnable() {
  239. @Override
  240. public void run() {
  241. mtextView.setText(val);
  242. }
  243. });
  244. }
  245. //执行网络请求
  246. public static String getUrlClient(final String url) {
  247. final StringBuilder sb = new StringBuilder();
  248. FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
  249. @Override
  250. public String call() throws Exception {
  251. BufferedReader br = null;
  252. InputStreamReader isr = null;
  253. URLConnection conn;
  254. try {
  255. URL geturl = new URL(url);
  256. conn = geturl.openConnection();//创建连接
  257. conn.connect();//get连接
  258. isr = new InputStreamReader(conn.getInputStream());//输入流
  259. br = new BufferedReader(isr);
  260. String line = null;
  261. while ((line = br.readLine()) != null) {
  262. sb.append(line);//获取输入流数据
  263. }
  264. System.out.println(sb.toString());
  265. } catch (Exception e) {
  266. e.printStackTrace();
  267. } finally {//执行流的关闭
  268. if (br != null) {
  269. try {
  270. if (br != null) {
  271. br.close();
  272. }
  273. if (isr != null) {
  274. isr.close();
  275. }
  276. } catch (IOException e) {
  277. e.printStackTrace();
  278. } }}
  279. return sb.toString();
  280. }
  281. });
  282. new Thread(task).start();
  283. String s = null;
  284. try {
  285. s = task.get();//异步获取返回值
  286. } catch (Exception e) {
  287. e.printStackTrace();
  288. }
  289. return s;
  290. }
  291. }

4.1介绍

  • 功能包括 登录,退出 ,创建群 创建单人回话,创建群回话 ,发送消息,接受解析消息 ,网络发送信息
  • 实现方式 通过集成sdk
  • 然后调用方法
  • 在当中出现过获取群回话不成功情况,通过重新用新的sdkappid 生成 usersgin 实现 就ok了
  • ok

 

5.java server 后台集成代码

  1. package com.supermap.im;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import com.tls.tls_sigature.tls_sigature;
  8. import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;
  9. /**
  10. * 云通信IM
  11. *
  12. * @author yushen
  13. *
  14. */
  15. @Controller
  16. public class IMCtr {
  17. //必须是五行内容经过测试发现似乎 sdk 需要 带上换行才好使
  18. private static String IMpriKeyContent = "-----BEGIN PRIVATE KEY-----\r\n" +
  19. "MIGxxxxxxxxxxxxxxxxxxxxxxxxxOC14uZfbJlKuW\r\n" +
  20. "JZ3xYoBzjRJS4sJxxxxxxxxxxxxxxxxxxxxxxxUdFH31NOb\r\n" +
  21. "8CNJNb3io530JxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxZe\r\n" +
  22. "-----END PRIVATE KEY-----\r\n" +
  23. "";
  24. /**
  25. * 获取用户腾讯云IM sgin
  26. *
  27. * @param req 获取用户名
  28. * @return 返回sgin
  29. */
  30. @RequestMapping("/im/getUserSign")
  31. @ResponseBody
  32. public String getUserSign(HttpServletRequest req) {
  33. String username = req.getParameter("username") == null ? "" : req.getParameter("username");
  34. if(username.equals(""))return "nul";
  35. //生成Sgin 14xxxxx 是腾讯云注册的时候会带一个sdkappid
  36. GenTLSSignatureResult result = tls_sigature.genSig( 14xxxxx, username, IMpriKeyContent);
  37. return result.urlSig;
  38. }
  39. // 测试时候使用
  40. // public static void main(String[] args) {
  41. // IMCtr t = new IMCtr();
  42. // System.out.println(t.getsgin());
  43. // }
  44. //
  45. // public String getsgin() {
  46. // GenTLSSignatureResult result = tls_sigature.genSig( 1400187322, "西施", IMpriKeyContent);
  47. // return result.urlSig;
  48. // }
  49. //
  50. }

到这里就ok楼,文章持续更新,有转发的带上地址,方便更新的时候大家都都方便找到

 

ok

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/178599
推荐阅读
相关标签
  

闽ICP备14008679号