创建一个内部类,实现EMConnectionListener接口,该接口实现了两个方法,一个是连接上的方法,在该方法中,去掉网络断开的可见,在连接不上的方法中,做出相应的处理。
/**
* 连接监听listener
*
*/
private class MyConnectionListener implements EMConnectionListener {
@Override
public void onConnected() {
runOnUiThread(new Runnable() {
@Override
public void run() {
chatHistoryFragment.errorItem.setVisibility(View.GONE);
}
});
}
@Override
public void onDisconnected(final int error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (error == EMError.USER_REMOVED) {
// 显示帐号已经被移除
showAccountRemovedDialog();
} else if (error == EMError.CONNECTION_CONFLICT) {
// 显示帐号在其他设备登陆dialog
showConflictDialog();
} else {
chatHistoryFragment.errorItem
.setVisibility(View.VISIBLE);
if (NetUtils.hasNetwork(MainActivity.this))
chatHistoryFragment.errorText.setText("连接不到聊天服务器");
else
chatHistoryFragment.errorText
.setText("当前网络不可用,请检查网络设置");
}
}
});
}
}
剩下的两个方法:
/**
* 显示帐号在别处登录dialog
*/
private void showConflictDialog() {
isConflictDialogShow = true;
IMApplication.getInstance().logout(null);
if (!MainActivity.this.isFinishing()) {
// clear up global variables
try {
if (conflictBuilder == null)
conflictBuilder = new android.app.AlertDialog.Builder(
MainActivity.this);
conflictBuilder.setTitle("下线通知");
conflictBuilder.setMessage(R.string.connect_conflict);
conflictBuilder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
conflictBuilder = null;
finish();
startActivity(new Intent(MainActivity.this,
LoginActivity.class));
}
});
conflictBuilder.setCancelable(false);
conflictBuilder.create().show();
isConflict = true;
} catch (Exception e) {
EMLog.e(TAG,
"---------color conflictBuilder error" + e.getMessage());
}
}
}
/**
* 帐号被移除的dialog
*/
private void showAccountRemovedDialog() {
isAccountRemovedDialogShow = true;
IMApplication.getInstance().logout(null);
if (!MainActivity.this.isFinishing()) {
// clear up global variables
try {
if (accountRemovedBuilder == null)
accountRemovedBuilder = new android.app.AlertDialog.Builder(
MainActivity.this);
accountRemovedBuilder.setTitle("移除通知");
accountRemovedBuilder.setMessage(R.string.em_user_remove);
accountRemovedBuilder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
accountRemovedBuilder = null;
finish();
startActivity(new Intent(MainActivity.this,
LoginActivity.class));
}
});
accountRemovedBuilder.setCancelable(false);
accountRemovedBuilder.create().show();
isCurrentAccountRemoved = true;
} catch (Exception e) {
EMLog.e(TAG,
"---------color userRemovedBuilder error"
+ e.getMessage());
}
}
}