目录
前言:
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/
package com.example.im;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMValueCallBack;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class im extends AppCompatActivity {
private int sdkAppId = 1400187322;
private String accountType = "0";
private TextView mtextView;
private EditText meditView1;
private EditText meditView2;
private EditText meditView3;
private EditText meditView5;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_im);
mHandler = new Handler();
mtextView = findViewById(R.id.abc);
meditView1 = findViewById(R.id.t1);
meditView2 = findViewById(R.id.t2);
meditView3 = findViewById(R.id.t3);
meditView5 = findViewById(R.id.t5);
initIm();
}
//初始化 SDK 基本配置
public void initIm(){
TIMSdkConfig config = new TIMSdkConfig(sdkAppId)
// .setAccoutType(accountType)
.enableLogPrint(true) // 是否在控制台打印Log?
.setLogLevel(TIMLogLevel.DEBUG) // Log输出级别(debug级别会很多)
.setLogPath(Environment.getExternalStorageDirectory().getPath() + "/justfortest/");// Log文件存放在哪里?
//初始化 SDK
TIMManager.getInstance().init(getApplicationContext(), config);
}
//服务器获取 sgin地址 这个方法用来通过后台获取用户的usersgin
private String loginSginUrl = "http://XX:8080/im/getUserSign?username=";
//im登陆
public void startupLogin(View v){
String userId = meditView3.getText().toString();//账户
String userSign = getUrlClient(loginSginUrl+userId);
TIMManager.getInstance().login(userId, userSign, new TIMCallBack() {
@Override
public void onError(int code, String desc) {Log.d("loginUser","---------------------------login failed. code: " + code + " errmsg: " + desc);
exitText("login failed. code: " + code + " errmsg: " + desc);
}
@Override
public void onSuccess() {
exitText("登录seccess");
}
});
}
//登出
public void shutdownLogin(View v){
TIMManager.getInstance().logout(new TIMCallBack() {
@Override
public void onError(int code, String desc) {
exitText("登出error");
}
@Override
public void onSuccess() {
removeText("登出seccess");
}
});
}
private TIMConversation conversation; //获取imsession
// //获取单聊会话
public void oneSession(View v){
String peer = meditView1.getText().toString(); //获取与用户 "test_user" 的会话
conversation = TIMManager.getInstance().getConversation(
TIMConversationType.C2C, //会话类型:单聊
peer);
exitText("单聊回话seccess");
getInfoIM();
}
//获取群聊会话
public void getGroupSession(View v){
String groupId = ""+meditView5.getText().toString();//获取与群组 "test_group" 的会话
conversation = TIMManager.getInstance().getConversation(
TIMConversationType.Group, //会话类型:群组
groupId); //群组 ID
exitText("群回话seccess");
getInfoIM();
}
//添加到群中
public void addGroup(View v){
String groupId = ""+meditView5.getText().toString();//获取与群组 "test_group" 的会话
TIMGroupManager.getInstance().applyJoinGroup(groupId, "some reason", new TIMCallBack() {
@java.lang.Override
public void onError(int code, String desc) {
exitText("disconnected"+code+desc);
}
@java.lang.Override
public void onSuccess() {
exitText("join group");
}
});
}
//发送消息 //构造一条消息并添加一个文本内容
public void sendInfo(View v){
TIMMessage msg = new TIMMessage();
TIMTextElem elem = new TIMTextElem();
String params = meditView2.getText().toString();
elem.setText(params);
msg.addElement(elem);
//发送消息
conversation.sendMessage(msg, new TIMValueCallBack() {
@Override
public void onError(int code, String desc) {//发送消息失败
exitText("发送消息失败 " + code + " errmsg: " + desc);
}
@Override
public void onSuccess(TIMMessage msg) {//发送消息成功
exitText("发送消息seccess");
}
});
}
//获取消息
public void getInfoIM(){
TIMManager.getInstance().addMessageListener(new TIMMessageListener() {//消息监听器
@Override
public boolean onNewMessages(List msgs) {//收到新消息
for (int z= 0; z < msgs.size(); z++){
TIMMessage msg = msgs.get(z);
for(int i = 0; i < msg.getElementCount(); ++i) {
TIMElem elem = msg.getElement(i);
TIMElemType elemType = elem.getType();//获取当前元素的类型
Log.d("", "elem type: " + elemType.name());
if (elemType == TIMElemType.Text) {//处理文本消息
TIMTextElem elemnew = (TIMTextElem) elem;
exitText(msg.getSender()+":"+elemnew.getText());
} else if (elemType == TIMElemType.Image) { //处理图片消息
}//...处理更多消息
}
}
//消息的内容解析请参考消息收发文档中的消息解析说明
return true; //返回true将终止回调链,不再调用下一个新消息监听器
}
});
}
创建公开群
public void createOpenGroup(View v){
TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("Public", "test_group1");
//创建群组
TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack() {
@Override
public void onError(int code, String desc) {
Log.d("createGroup", "create group failed. code: " + code + " errmsg: " + desc);
exitText("创建群error");
}
@Override
public void onSuccess(String s) {
Log.d("createGroup", "create group succ, groupId:" + s);
exitText("创建群seccess");
}
});
}
//创建聊天室
public void createChatGroup(View v){
TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("Public", "test_group1");
TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack() {
@Override
public void onError(int code, String desc) {
Log.d("createGroup", "create group failed. code: " + code + " errmsg: " + desc);
exitText("创建群error");
}
@Override
public void onSuccess(String s) {
Log.d("createGroup", "create group succ, groupId:" + s);
exitText("创建群seccess");
}
});
}
//创建直播大群
public void createAVChatGroup(View v){
TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("AVChatRoom", meditView5.getText().toString());
TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack() {
@Override
public void onError(int code, String desc) {
Log.d("createGroup", "create group failed. code: " + code + " errmsg: " + desc);
exitText("创建群error");
}
@Override
public void onSuccess(String s) {
Log.d("createGroup", "create group succ, groupId:" + s);
exitText("创建群seccess");
}
});
}
//想文本中添加内容
public void exitText(final String val){
mHandler.post(new Runnable() {
@Override
public void run() {
mtextView.append(";"+val);
}
});
}
//删除内容
public void removeText(final String val){
mHandler.post(new Runnable() {
@Override
public void run() {
mtextView.setText(val);
}
});
}
//执行网络请求
public static String getUrlClient(final String url) {
final StringBuilder sb = new StringBuilder();
FutureTask task = new FutureTask(new Callable() {
@Override
public String call() throws Exception {
BufferedReader br = null;
InputStreamReader isr = null;
URLConnection conn;
try {
URL geturl = new URL(url);
conn = geturl.openConnection();//创建连接
conn.connect();//get连接
isr = new InputStreamReader(conn.getInputStream());//输入流
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);//获取输入流数据
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {//执行流的关闭
if (br != null) {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
} }}
return sb.toString();
}
});
new Thread(task).start();
String s = null;
try {
s = task.get();//异步获取返回值
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
}
package com.supermap.im;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tls.tls_sigature.tls_sigature;
import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;
/**
* 云通信IM
*
* @author yushen
*
*/
@Controller
public class IMCtr {
//必须是五行内容经过测试发现似乎 sdk 需要 带上换行才好使
private static String IMpriKeyContent = "-----BEGIN PRIVATE KEY-----\r\n" +
"MIGxxxxxxxxxxxxxxxxxxxxxxxxxOC14uZfbJlKuW\r\n" +
"JZ3xYoBzjRJS4sJxxxxxxxxxxxxxxxxxxxxxxxUdFH31NOb\r\n" +
"8CNJNb3io530JxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxZe\r\n" +
"-----END PRIVATE KEY-----\r\n" +
"";
/**
* 获取用户腾讯云IM sgin
*
* @param req 获取用户名
* @return 返回sgin
*/
@RequestMapping("/im/getUserSign")
@ResponseBody
public String getUserSign(HttpServletRequest req) {
String username = req.getParameter("username") == null ? "" : req.getParameter("username");
if(username.equals(""))return "nul";
//生成Sgin 14xxxxx 是腾讯云注册的时候会带一个sdkappid
GenTLSSignatureResult result = tls_sigature.genSig( 14xxxxx, username, IMpriKeyContent);
return result.urlSig;
}
// 测试时候使用
// public static void main(String[] args) {
// IMCtr t = new IMCtr();
// System.out.println(t.getsgin());
// }
//
// public String getsgin() {
// GenTLSSignatureResult result = tls_sigature.genSig( 1400187322, "西施", IMpriKeyContent);
// return result.urlSig;
// }
//
}
到这里就ok楼,文章持续更新,有转发的带上地址,方便更新的时候大家都都方便找到
ok