54.用环信实现聊天功能
1.配置EM
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.chatdemo">
<!--环信需要权限-->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".common.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".activity.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.A1_RegisterActivity" />
<activity android:name=".activity.A2_LoginActivity" />
<activity
android:name=".activity.A3_SendTextActivity"
android:launchMode="singleInstance" />
<!--环信:START-->
<meta-data
android:name="EASEMOB_APPKEY"
android:value="fishgas#chatdemo" />
<service android:name="com.easemob.chat.EMChatService" />
<!--环信:END-->
</application>
</manifest>
public class MyApplication extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
initEaseMob();
initImageLoader();
}
/**
* 配置ImageLoader
*/
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions
.Builder()
.showImageForEmptyUri(R.drawable.empty_photo)
.showImageOnFail(R.drawable.empty_photo)
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration
.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.discCacheSize(50 * 1024 * 1024)//
.discCacheFileCount(100)//缓存一百张图片
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
/**
* 配置环信IM
*/
private void initEaseMob() {
EMChat.getInstance().init(getApplicationContext());
}
}
/*环信工具类*/
public class EMUtil {
/**
* EM注册账号
*/
public static void register(final Activity context, final String username, final String password) {
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
// 调用sdk注册方法
try {
EMChatManager.getInstance().createAccountOnServer(username, password);
//注册成功
AbSharedUtil.putString(context, "username", username);
AbSharedUtil.putString(context, "password", password);
context.finish();
showToastOnUI(context, "环信注册成功");
} catch (EaseMobException e) {
switch (e.getErrorCode()) {
case EMError.NONETWORK_ERROR:
showToastOnUI(context, "网络异常,请检查网络!");
break;
case EMError.USER_ALREADY_EXISTS:
showToastOnUI(context, "用户已存在!");
break;
case EMError.UNAUTHORIZED:
showToastOnUI(context, "注册失败,无权限!");
break;
default:
showToastOnUI(context, "注册失败: " + e.getMessage());
break;
}
}
return null;
}
}.execute();
}
/**
* EM登录账号
*/
public static void login(final Activity context, final String username, final String password) {
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
EMChatManager.getInstance().login(username, password, new EMCallBack() {//回调
@Override
public void onSuccess() {
context.runOnUiThread(new Runnable() {
public void run() {
EMGroupManager.getInstance().loadAllGroups();
EMChatManager.getInstance().loadAllConversations();
context.finish();
showToastOnUI(context, "环信登录成功");
}
});
}
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(int code, String message) {
}
});
return null;
}
}.execute();
}
/**
* EM动态注册广播,接受广播
*/
public static void registerEMReceiver(Activity context) {
EMReceiver msgReceiver = new EMReceiver();
IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
intentFilter.setPriority(3);
context.registerReceiver(msgReceiver, intentFilter);
}
/**
* EM发送文本消息
*/
public static void sendText(Activity context, String friendStr, String inputStr, final MyEMCallBack myEMCallBack) {
LogUtil.e("friendStr=" + friendStr + "\tinputStr=" + inputStr);
String username = AbSharedUtil.getString(context, "username", "");
String password = AbSharedUtil.getString(context, "password", "");
//获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid,后文中的username皆是如此
EMConversation conversation = EMChatManager.getInstance().getConversation(username);
//创建一条文本消息
final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
//如果是群聊,设置chattype,默认是单聊
message.setChatType(EMMessage.ChatType.Chat);
//设置消息body
TextMessageBody txtBody = new TextMessageBody(inputStr);
message.addBody(txtBody);
//设置接收人
message.setReceipt(friendStr);
//把消息加入到此会话对象中
conversation.addMessage(message);
//发送消息,并传入回调监听
EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
@Override
public void onSuccess() {
LogUtil.e("");
myEMCallBack.onSuccess(message);
}
@Override
public void onError(int i, String s) {
myEMCallBack.onError(i, s);
}
@Override
public void onProgress(int i, String s) {
}
});
}
/**
* 对EM回调进行改造,成功的方法中多传一个EMMessage对象
*/
public interface MyEMCallBack {
void onSuccess(EMMessage message);
void onError(int var1, String var2);
}
/**
* 在分线程中显示Toast
*/
public static void showToastOnUI(final Activity context, final CharSequence message) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
Looper.getMainLooper();
LogUtil.s(message);
}
});
}
}
public class EMReceiver extends BroadcastReceiver {4.聊天界面
@Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();// 注销广播,避免重复接收
String msgId = intent.getStringExtra("msgid");// 消息id(每条消息都会生成唯一的一个id,目前是SDK生成)
String username = intent.getStringExtra("from");//发送方
EMMessage message = EMChatManager.getInstance().getMessage(msgId); // 收到这个广播的时候,message已经在db和内存里了,可以通过id获取mesage对象
EMConversation conversation = EMChatManager.getInstance().getConversation(username);
LogUtil.e("接受到环信的消息:message=" + JSON.toJSONString(message));
Intent it = new Intent(context, A3_SendTextActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("message", message);
it.putExtras(bundle);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(it);
}
}
//发送消息
public class A3_SendTextActivity extends Activity {
Context context = A3_SendTextActivity.this;
@InjectView(R.id.et_friend)
EditText friend;
@InjectView(R.id.et_input)
EditText input;
@InjectView(R.id.listview)
ListView listView;
ChatAdapter adapter;
List<EMMessage> data = new ArrayList<EMMessage>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendtext);
ButterKnife.inject(this);
initListView();
EMUtil.registerEMReceiver(A3_SendTextActivity.this);
}
@OnClick(R.id.send)
public void doSend(View v) {
String friendStr = friend.getText().toString().trim();
String inputStr = input.getText().toString().trim();
if (TextUtils.isEmpty(friendStr) || TextUtils.isEmpty(inputStr)) {
LogUtil.s("请输入完整信息!");
return;
}
EMUtil.sendText(A3_SendTextActivity.this, friendStr, inputStr, new EMUtil.MyEMCallBack() {
@Override
public void onSuccess(EMMessage message) {
LogUtil.e("");
addEMMessageToListView(message);
}
@Override
public void onError(int var1, String var2) {
}
});
}
@OnClick(R.id.getmsg)
public void doGetMSg(View v) {
String friendStr = friend.getText().toString().trim();
if (TextUtils.isEmpty(friendStr)) {
LogUtil.s("请输入完整信息!");
return;
}
getMsgList(friendStr);
}
/**
* 初始化聊天消息列表
*/
private void initListView() {
adapter = new ChatAdapter(context);
listView.setAdapter(adapter);
}
/**
* 从广播进入聊天界面
*/
@Override
protected void onNewIntent(Intent intent) {
Bundle bun = intent.getExtras();
EMMessage message = bun.getParcelable("message");
addEMMessageToListView(message);
}
/**
* 获取与好友的聊天记录
*/
private void getMsgList(String friendStr) {
EMConversation conversation = EMChatManager.getInstance().getConversation(friendStr);
//获取此会话的所有消息
List<EMMessage> messages = conversation.getAllMessages();
data = messages;
adapter.setData(data);
adapter.notifyDataSetChanged();
listView.setSelection(data.size());
}
/**
* 将接受的消息添加进listview
*/
private void addEMMessageToListView(EMMessage msg) {
data.add(msg);
adapter.setData(data);
adapter.notifyDataSetChanged();
listView.setSelection(data.size());
}
}
源码:
EMSDK官网:
附件列表