假如我们想要快速实现一个即时通讯功能,最快捷的方法就是借助网络上的即时云服务。下面我们讲述一下如何利用环信实现一个IM功能。
首先下载环信的SDK,也就是几个库,把demo里面的HXSDKHelper.java,HXSDKModel.java,DefaultHXSDKModel.java,HXPreferenceUtils.java四个文件复制到新建的工程下。稍作修改。
首先在Application中实现初始化SDK
public static DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();
@Override
public void onCreate() {
super.onCreate();
applicationContext = this;
instance = this;
hxSDKHelper.onInit(applicationContext);
}
然后在Activity中登陆
EMChatManager.getInstance().login("123456", "123456", new EMCallBack() {
@Override
public void onSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "登陆成功!", Toast.LENGTH_LONG).show();
}
});
};
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(final int code, final String message) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "登陆失败" + message, Toast.LENGTH_SHORT).show();
}
});
}
});
调用函数进行信息的发送
String string = editText3.getText().toString();
EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
String toNum = editText.getText().toString();
if (toNum.equals("1425193776689")) {
message.setChatType(ChatType.GroupChat);
}
TextMessageBody txtBody = new TextMessageBody(string);
message.addBody(txtBody);
message.setReceipt(toNum);
try {
EMChatManager.getInstance().sendMessage(message);
} catch (EaseMobException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在接收信息时,只需要监听广播就可以
// 注册接收消息广播
receiver = new NewMessageBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
intentFilter.setPriority(5);
registerReceiver(receiver, intentFilter);
private class NewMessageBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 记得把广播给终结掉
abortBroadcast();
String username = intent.getStringExtra("from");
String msgId = intent.getStringExtra("msgid");
// 收到这个广播的时候,message已经在db和内存里了,可以通过id获取mesage对象
final EMMessage message = EMChatManager.getInstance().getMessage(msgId);
final TextMessageBody txtBody = (TextMessageBody)message.getBody();
Toast.makeText(getApplicationContext(), "text message from:" + message.getFrom() + " text:" + txtBody.getMessage() + " \n\r", Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
@Override
public void run() {
editText2.setText("from:" + message.getFrom() + "\ntext:" + txtBody.getMessage() + " \n");
}
});
}
}
这样就可以进行收发。
由于环信的库比较大,编译完之后可执行文件有5M那么大。
时间: 2024-10-25 21:23:31