程序员人生 网站导航

Android 基于环信即时云的IM开发

栏目:综合技术时间:2015-04-10 07:43:40

假设我们想要快速实现1个即时通讯功能,最快捷的方法就是借助网络上的即时云服务。下面我们讲述1下如何利用环信实现1个IM功能。

首先下载环信的SDK,也就是几个库,把demo里面的HXSDKHelper.java,HXSDKModel.java,DefaultHXSDKModel.java,HXPreferenceUtils.java4个文件复制到新建的工程下。稍作修改。

首先在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() + " ", Toast.LENGTH_LONG).show(); runOnUiThread(new Runnable() { @Override public void run() { editText2.setText("from:" + message.getFrom() + " text:" + txtBody.getMessage() + " "); } }); } }

这样就能够进行收发。
由于环信的库比较大,编译完以后可履行文件有5M那末大。

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐