腾讯云通信独立模式
腾讯云通信10万日活免费,甩同行几十条街,不过看了独立模式的接入迟迟不敢下手,经过仔细的读官方文档,最终还是完美解决了。
验证服务器
这一块乍一看花里胡哨,细看还是很容易读懂的。
首先需要在控制台填写管理员账号
下载公钥私钥
获取SdkAppId,accountType
获取管理员账号的usersig(有效期180天)
我服务器用的php,
下载 PHP Server SDK
官方SDK
配置文件
独立模式需要在自己的服务器获取usersig
所以我们需要一个获取usersig的api
private.pem是在控制台下载的私钥。
Config.php是配置文件
<?php
header('Content-type: application/json; charset=UTF-8');
// 设置REST API调用基本参数
$sdkappid = 0;
$identifier = "admin";
$private_key_path = dirname(__FILE__)."/private.pem";
$signature = dirname(__FILE__)."/signature/linux-signature64";
$usersig = '';//设置管理员usersig 180天失效
其中usersig设置为固定的,过期之前再来重新生成。
账号导入
apiimport.php
<?php
require_once("TimRestApi.php");
require_once("Config.php");
$api = createRestAPI();
$api->init($sdkappid, $identifier);
$api->set_user_sig($usersig);
$userid=$_GET['userid'];//用户id
$nickname=$_GET['userid'];//用户昵称
$avatarurl=$_GET['userid'];//用户头像
$ret = $api->account_import($userid, $nickname, $avatarurl);
必须先先导入账号到腾讯云
获取usersig
apigetsig.php
<?php
require_once("TimRestApi.php");
require_once("Config.php");
$api = createRestAPI();
$api->init($sdkappid, $identifier);
$userid=$_GET['userid'];//自己系统用户id
$ret = $api->generate_user_sig($userid, '86400',$private_key_path, $signature);
if ($ret == null)
{
// 签名生成失败
return -10;
}
echo $ret[0];
获取到usersig就可以登录了。
android客户端接入
使用官方的demo,不过我们不需要tlslibrary这个module,其他module都依赖给自己的项目即可。
初始化
首先在自己的CommonApplication中初始化腾讯云通信
package com.lx.pet;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.lx.pet.Config.Config;
import com.lx.pet.util.Foreground;
import com.mob.MobSDK;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMGroupEventListener;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupReceiveMessageOpt;
import com.tencent.imsdk.TIMGroupTipsElem;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushListener;
import com.tencent.imsdk.TIMOfflinePushNotification;
import com.tencent.imsdk.TIMRefreshListener;
import com.tencent.imsdk.TIMSNSChangeInfo;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.ext.group.TIMGroupAssistantListener;
import com.tencent.imsdk.ext.group.TIMGroupCacheInfo;
import com.tencent.imsdk.ext.group.TIMUserConfigGroupExt;
import com.tencent.imsdk.ext.message.TIMUserConfigMsgExt;
import com.tencent.imsdk.ext.sns.TIMFriendGroup;
import com.tencent.imsdk.ext.sns.TIMFriendshipProxyListener;
import com.tencent.imsdk.ext.sns.TIMUserConfigSnsExt;
import com.tencent.qalsdk.sdk.MsfSdkUtils;
import java.io.File;
import java.util.List;
import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.util.DeviceUtils;
/**
* Created by xubowen on 2018/2/25.
*/
public class CommonApplication extends Application {
private static Context context;
private String tag="xbw12138";
@Override
public void onCreate() {
super.onCreate();
Foreground.init(this);
context = getApplicationContext();
initTim();//初始化腾讯云通信
initTimUser();
if(MsfSdkUtils.isMainProcess(this)) {
TIMManager.getInstance().setOfflinePushListener(new TIMOfflinePushListener() {
@Override
public void handleNotification(TIMOfflinePushNotification notification) {
if (notification.getGroupReceiveMsgOpt() == TIMGroupReceiveMessageOpt.ReceiveAndNotify){
//消息被设置为需要提醒
notification.doNotify(getApplicationContext(), R.mipmap.ic_launcher);
}
}
});
}
}
public static Context getContext() {
return context;
}
public void initTim() {
//初始化SDK基本配置
TIMSdkConfig config = new TIMSdkConfig(Config.SdkAppId)
.setAccoutType(Config.accountType)
.enableCrashReport(false)
.enableLogPrint(true)
.setLogLevel(TIMLogLevel.DEBUG)
.setLogPath(Environment.getExternalStorageDirectory().getPath() + "/petpet/");
//初始化SDK
boolean init= TIMManager.getInstance().init(getApplicationContext(), config);
if(init){
Log.i("xbw12138", "init success");
}else{
Log.i("xbw12138", "init fail");
}
}
public void initTimUser(){
//基本用户配置
TIMUserConfig userConfig = new TIMUserConfig()
//设置群组资料拉取字段
//.setGroupSettings(initGroupSettings())
//设置资料关系链拉取字段
//.setFriendshipSettings(initFriendshipSettings())
//设置用户状态变更事件监听器
.setUserStatusListener(new TIMUserStatusListener() {
@Override
public void onForceOffline() {
//被其他终端踢下线
Log.i(tag, "onForceOffline");
}
@Override
public void onUserSigExpired() {
//用户签名过期了,需要刷新userSig重新登录SDK
Log.i(tag, "onUserSigExpired");
}
})
//设置连接状态事件监听器
.setConnectionListener(new TIMConnListener() {
@Override
public void onConnected() {
Log.i(tag, "onConnected");
}
@Override
public void onDisconnected(int code, String desc) {
Log.i(tag, "onDisconnected");
}
@Override
public void onWifiNeedAuth(String name) {
Log.i(tag, "onWifiNeedAuth");
}
})
//设置群组事件监听器
.setGroupEventListener(new TIMGroupEventListener() {
@Override
public void onGroupTipsEvent(TIMGroupTipsElem elem) {
Log.i(tag, "onGroupTipsEvent, type: " + elem.getTipsType());
}
})
//设置会话刷新监听器
.setRefreshListener(new TIMRefreshListener() {
@Override
public void onRefresh() {
Log.i(tag, "onRefresh");
}
@Override
public void onRefreshConversation(List<TIMConversation> conversations) {
Log.i(tag, "onRefreshConversation, conversation size: " + conversations.size());
}
});
userConfig = new TIMUserConfigMsgExt(userConfig)
.enableStorage(false)
.enableReadReceipt(true);
userConfig = new TIMUserConfigSnsExt(userConfig)
.enableFriendshipStorage(true)
.setFriendshipProxyListener(new TIMFriendshipProxyListener() {
@Override
public void OnAddFriends(List<TIMUserProfile> users) {
Log.i(tag, "OnAddFriends");
}
@Override
public void OnDelFriends(List<String> identifiers) {
Log.i(tag, "OnDelFriends");
}
@Override
public void OnFriendProfileUpdate(List<TIMUserProfile> profiles) {
Log.i(tag, "OnFriendProfileUpdate");
}
@Override
public void OnAddFriendReqs(List<TIMSNSChangeInfo> reqs) {
Log.i(tag, "OnAddFriendReqs");
}
});
userConfig = new TIMUserConfigGroupExt(userConfig)
.enableGroupStorage(true)
.setGroupAssistantListener(new TIMGroupAssistantListener() {
@Override
public void onMemberJoin(String groupId, List<TIMGroupMemberInfo> memberInfos) {
Log.i(tag, "onMemberJoin");
}
@Override
public void onMemberQuit(String groupId, List<String> members) {
Log.i(tag, "onMemberQuit");
}
@Override
public void onMemberUpdate(String groupId, List<TIMGroupMemberInfo> memberInfos) {
Log.i(tag, "onMemberUpdate");
}
@Override
public void onGroupAdd(TIMGroupCacheInfo groupCacheInfo) {
Log.i(tag, "onGroupAdd");
}
@Override
public void onGroupDelete(String groupId) {
Log.i(tag, "onGroupDelete");
}
@Override
public void onGroupUpdate(TIMGroupCacheInfo groupCacheInfo) {
Log.i(tag, "onGroupUpdate");
}
});
TIMManager.getInstance().setUserConfig(userConfig);
}
}
导入账号
在我们自己的登录界面登录成功后,紧接着导入账号到腾讯云
//导入账号到腾讯云通信 独立模式
public void importUserid(String userid,String nickname,String avatarurl){
//Log.i("xbw12138",Config.API_IMPORT_USERID+"?userid="+userid+"&nickname="+nickname+"&avatarurl="+avatarurl);
OkHttpClient okHttpClient = new OkHttpClient();
final okhttp3.Request request = new okhttp3.Request.Builder()
.url(Config.API_IMPORT_USERID+"?userid="+userid+"&nickname="+nickname+"&avatarurl="+avatarurl)
.build();
okhttp3.Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
SplashActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
T.showShort(mContext,getString(R.string.importfail));
Log.d(tag,"import userid fail");
}
});
}
@Override
public void onResponse(okhttp3.Call call, final Response response) throws IOException {
SplashActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
T.showShort(mContext,getString(R.string.importsucc));
Log.d(tag,"import userid success");
}
});
}
});
}
登录
在主界面登录即可
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getUserSig(userid);//登录腾讯云通信
}
//获取腾讯云通信usersig
public void getUserSig(final String userid){
OkHttpClient okHttpClient = new OkHttpClient();
final okhttp3.Request request = new okhttp3.Request.Builder()
.url(Config.API_GET_USERSIG+"?userid="+userid)
.build();
okhttp3.Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
@Override
public void onResponse(okhttp3.Call call, final Response response) throws IOException {
TimLogin(userid,response.body().string());
}
});
}
//登录腾讯云通信
public void TimLogin(String userid,String usersig){
TIMManager.getInstance().login(userid, usersig, new TIMCallBack() {
@Override
public void onError(int code, String desc) {
T.showShort(mContext,getString(R.string.loginfail)+code+desc);
Log.d("xbw12138", "login failed. code: " + code + " errmsg: " + desc);
}
@Override
public void onSuccess() {
T.showShort(mContext,getString(R.string.loginsucc));
Log.d("xbw12138", "login succ");
}
});
}
这样就完成了,由于云通信使用了单利模式,所以到此就结束了,已经可以成功过获取消息了。
细节
我发现demo里的getAvatar方法都是给的死的头像资源,并没有获取我们导入账号上传的头像url,这样很难受。
其实传过来的消息是带有用户头像的,我们需要重新定义一个抽象方法。
找到demo中 model目录下的 Conversation.java
添加
/**
* 获取头像URL
*/
abstract public String getAvatarUrl();
在FriendshipConversation.java,GroupManageConversation.java
实现该抽象方法为
@Override
public String getAvatarUrl() {
return "";
}
在NomalConversation.java实现该方法抽象为
@Override
public String getAvatarUrl() {
FriendProfile profile = FriendshipInfo.getInstance().getProfile(identify);
String avatar="";
avatar=profile == null?a:profile.getAvatarUrl();
return avatar;
}
在adapter目录下修改ConversationAdapter.java
//viewHolder.avatar.setImageResource(data.getAvatar());替换这一行为下边的
if(data.getAvatarUrl()!=null){
if(data.getAvatarUrl().equals("")){
viewHolder.avatar.setImageResource(data.getAvatar());
}else{
Picasso.with(getContext()).load(data.getAvatarUrl()).into(viewHolder.avatar);
}
}else {
viewHolder.avatar.setImageResource(data.getAvatar());
}
Screenshot_20180304-165717.png
效果还不错,这样既保留系统的头像,又获取到用户的头像了。
写了一个独立模式的小demo
Github 腾讯云通信独立模式android端 TIMChat
网友评论