Java tutorial
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.easemob.chatuidemo.ui; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.easemob.EMCallBack; import com.easemob.EMEventListener; import com.easemob.EMNotifierEvent; import com.easemob.chat.CmdMessageBody; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMConversation; import com.easemob.chat.EMConversation.EMConversationType; import com.easemob.chat.EMMessage.ChatType; import com.easemob.chat.EMMessage.Type; import com.easemob.chat.EMMessage; import com.easemob.chatuidemo.Constant; import com.easemob.chatuidemo.DemoHelper; import com.easemob.chatuidemo.R; import com.easemob.chatuidemo.db.InviteMessgeDao; import com.easemob.chatuidemo.db.UserDao; import com.easemob.chatuidemo.domain.InviteMessage; import com.easemob.easeui.EaseConstant; import com.easemob.easeui.utils.EaseCommonUtils; import com.easemob.exceptions.EaseMobException; import com.easemob.util.EMLog; import com.easemob.util.NetUtils; import com.umeng.analytics.MobclickAgent; import com.umeng.update.UmengUpdateAgent; import com.xiaomi.mipush.sdk.MiPushClient; public class MainActivity extends BaseActivity implements EMEventListener { protected static final String TAG = "MainActivity"; // ?textview private TextView unreadLabel; // textview private TextView unreadAddressLable; private Button[] mTabs; private ContactListFragment contactListFragment; // private conversationListFragment conversationListFragment; // private ChatAllHistoryFragment conversationListFragment; private SettingsFragment settingFragment; private Fragment[] fragments; private int index; // ?fragmentindex private int currentTabIndex; // ? public boolean isConflict = false; // ? private boolean isCurrentAccountRemoved = false; /** * ?? */ public boolean getCurrentAccountRemoved() { return isCurrentAccountRemoved; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MiPushClient.clearNotification(this); if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) { // ??home???appcrash // fragment?? DemoHelper.getInstance().logout(false, null); finish(); startActivity(new Intent(this, LoginActivity.class)); return; } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) { // T??home???appcrash // fragment?? finish(); startActivity(new Intent(this, LoginActivity.class)); return; } setContentView(R.layout.em_activity_main); initView(); //umeng api MobclickAgent.updateOnlineConfig(this); UmengUpdateAgent.setUpdateOnlyWifi(false); UmengUpdateAgent.update(this); if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) { showConflictDialog(); } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) { showAccountRemovedDialog(); } inviteMessgeDao = new InviteMessgeDao(this); userDao = new UserDao(this); conversationListFragment = new ConversationListFragment(); contactListFragment = new ContactListFragment(); settingFragment = new SettingsFragment(); fragments = new Fragment[] { conversationListFragment, contactListFragment, settingFragment }; // fragment getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, conversationListFragment) .add(R.id.fragment_container, contactListFragment).hide(contactListFragment) .show(conversationListFragment).commit(); // ?? DemoHelper.getInstance().registerGroupAndContactListener(); registerBroadcastReceiver(); // registerInternalDebugReceiver(); } /** * ? */ private void initView() { unreadLabel = (TextView) findViewById(R.id.unread_msg_number); unreadAddressLable = (TextView) findViewById(R.id.unread_address_number); mTabs = new Button[3]; mTabs[0] = (Button) findViewById(R.id.btn_conversation); mTabs[1] = (Button) findViewById(R.id.btn_address_list); mTabs[2] = (Button) findViewById(R.id.btn_setting); // tab? mTabs[0].setSelected(true); } /** * button * * @param view */ public void onTabClicked(View view) { switch (view.getId()) { case R.id.btn_conversation: index = 0; break; case R.id.btn_address_list: index = 1; break; case R.id.btn_setting: index = 2; break; } if (currentTabIndex != index) { FragmentTransaction trx = getSupportFragmentManager().beginTransaction(); trx.hide(fragments[currentTabIndex]); if (!fragments[index].isAdded()) { trx.add(R.id.fragment_container, fragments[index]); } trx.show(fragments[index]).commit(); } mTabs[currentTabIndex].setSelected(false); // ?tab? mTabs[index].setSelected(true); currentTabIndex = index; } /** * ? */ @Override public void onEvent(EMNotifierEvent event) { switch (event.getEvent()) { case EventNewMessage: // ? EMMessage message = (EMMessage) event.getData(); // ??? DemoHelper.getInstance().getNotifier().onNewMsg(message); refreshUIWithMessage(); break; case EventOfflineMessage: { refreshUIWithMessage(); break; } case EventConversationListChanged: { refreshUIWithMessage(); break; } case EventNewCMDMessage: EMMessage cmdMessage = (EMMessage) event.getData(); //??body CmdMessageBody cmdMsgBody = (CmdMessageBody) cmdMessage.getBody(); final String action = cmdMsgBody.action;//?action if (action.equals(EaseConstant.EASE_ATTR_REVOKE)) { EaseCommonUtils.receiveRevokeMessage(this, cmdMessage); } refreshUIWithMessage(); break; case EventReadAck: // TODO ?ackMessagenull? EMMessage ackMessage = (EMMessage) event.getData(); EMConversation conversation = EMChatManager.getInstance().getConversation(ackMessage.getTo()); // ack????????(?txt iamge file??? ) if (ackMessage.getBooleanAttribute(EaseConstant.EASE_ATTR_READFIRE, false) && (ackMessage.getType() == Type.TXT || ackMessage.getType() == Type.VOICE || ackMessage.getType() == Type.IMAGE)) { // ??????????????????? if (conversation.getAllMessages().size() == 1 && conversation.getLastMessage().getMsgId().equals(ackMessage.getMsgId())) { if (ackMessage.getChatType() == ChatType.Chat) { conversation.loadMoreMsgFromDB(ackMessage.getMsgId(), 1); } else { conversation.loadMoreGroupMsgFromDB(ackMessage.getMsgId(), 1); } } conversation.removeMessage(ackMessage.getMsgId()); } refreshUIWithMessage(); break; default: break; } } private void refreshUIWithMessage() { runOnUiThread(new Runnable() { public void run() { // bottom bar? updateUnreadLabel(); if (currentTabIndex == 0) { // ?????? if (conversationListFragment != null) { conversationListFragment.refresh(); } } } }); } @Override public void back(View view) { super.back(view); } private void registerBroadcastReceiver() { broadcastManager = LocalBroadcastManager.getInstance(this); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED); intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateUnreadLabel(); updateUnreadAddressLable(); if (currentTabIndex == 0) { // ?????? if (conversationListFragment != null) { conversationListFragment.refresh(); } } else if (currentTabIndex == 1) { if (contactListFragment != null) { contactListFragment.refresh(); } } String action = intent.getAction(); if (action.equals(Constant.ACTION_GROUP_CHANAGED)) { if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) { GroupsActivity.instance.onResume(); } } } }; broadcastManager.registerReceiver(broadcastReceiver, intentFilter); } private void unregisterBroadcastReceiver() { broadcastManager.unregisterReceiver(broadcastReceiver); } @Override protected void onDestroy() { super.onDestroy(); if (conflictBuilder != null) { conflictBuilder.create().dismiss(); conflictBuilder = null; } unregisterBroadcastReceiver(); try { unregisterReceiver(internalDebugReceiver); } catch (Exception e) { } } /** * ? */ public void updateUnreadLabel() { int count = getUnreadMsgCountTotal(); if (count > 0) { unreadLabel.setText(String.valueOf(count)); unreadLabel.setVisibility(View.VISIBLE); } else { unreadLabel.setVisibility(View.INVISIBLE); } } /** * ? */ public void updateUnreadAddressLable() { runOnUiThread(new Runnable() { public void run() { int count = getUnreadAddressCountTotal(); if (count > 0) { // unreadAddressLable.setText(String.valueOf(count)); unreadAddressLable.setVisibility(View.VISIBLE); } else { unreadAddressLable.setVisibility(View.INVISIBLE); } } }); } /** * ?? * * @return */ public int getUnreadAddressCountTotal() { int unreadAddressCountTotal = 0; unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount(); return unreadAddressCountTotal; } /** * ?? * * @return */ public int getUnreadMsgCountTotal() { int unreadMsgCountTotal = 0; int chatroomUnreadMsgCount = 0; unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount(); for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) { if (conversation.getType() == EMConversationType.ChatRoom) chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount(); } return unreadMsgCountTotal - chatroomUnreadMsgCount; } private InviteMessgeDao inviteMessgeDao; private UserDao userDao; /** * ???? * * @param msg */ private void notifyNewIviteMessage(InviteMessage msg) { saveInviteMsg(msg); // ??? DemoHelper.getInstance().getNotifier().viberateAndPlayTone(null); // bottom bar? updateUnreadAddressLable(); // ??ui if (currentTabIndex == 1) contactListFragment.refresh(); } /** * ?msg * * @param msg */ private void saveInviteMsg(InviteMessage msg) { // ?msg inviteMessgeDao.saveMessage(msg); //? inviteMessgeDao.saveUnreadMessageCount(1); } @Override protected void onResume() { super.onResume(); if (!isConflict && !isCurrentAccountRemoved) { updateUnreadLabel(); updateUnreadAddressLable(); } // unregister this event listener when this activity enters the // background DemoHelper sdkHelper = DemoHelper.getInstance(); sdkHelper.pushActivity(this); // register the event listener when enter the foreground EMChatManager.getInstance().registerEventListener(this, new EMNotifierEvent.Event[] { EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged, EMNotifierEvent.Event.EventNewCMDMessage, EMNotifierEvent.Event.EventReadAck }); // if push service available, connect will be disconnected after app in background // after activity restore to foreground, reconnect if (!EMChatManager.getInstance().isConnected() && NetUtils.hasNetwork(this)) { EMChatManager.getInstance().reconnect(); } } @Override protected void onStop() { EMChatManager.getInstance().unregisterEventListener(this); DemoHelper sdkHelper = DemoHelper.getInstance(); sdkHelper.popActivity(this); super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("isConflict", isConflict); outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved); super.onSaveInstanceState(outState); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(false); return true; } return super.onKeyDown(keyCode, event); } private android.app.AlertDialog.Builder conflictBuilder; private android.app.AlertDialog.Builder accountRemovedBuilder; private boolean isConflictDialogShow; private boolean isAccountRemovedDialogShow; private BroadcastReceiver internalDebugReceiver; private ConversationListFragment conversationListFragment; private BroadcastReceiver broadcastReceiver; private LocalBroadcastManager broadcastManager; /** * ??dialog */ private void showConflictDialog() { isConflictDialogShow = true; DemoHelper.getInstance().logout(false, null); String st = getResources().getString(R.string.Logoff_notification); if (!MainActivity.this.isFinishing()) { // clear up global variables try { if (conflictBuilder == null) conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this); conflictBuilder.setTitle(st); 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; DemoHelper.getInstance().logout(false, null); String st5 = getResources().getString(R.string.Remove_the_notification); if (!MainActivity.this.isFinishing()) { // clear up global variables try { if (accountRemovedBuilder == null) accountRemovedBuilder = new android.app.AlertDialog.Builder(MainActivity.this); accountRemovedBuilder.setTitle(st5); 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()); } } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) { showConflictDialog(); } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) { showAccountRemovedDialog(); } } /** * ?? */ private void registerInternalDebugReceiver() { internalDebugReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { DemoHelper.getInstance().logout(false, new EMCallBack() { @Override public void onSuccess() { runOnUiThread(new Runnable() { public void run() { // ?? finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); } @Override public void onProgress(int progress, String status) { } @Override public void onError(int code, String message) { } }); } }; IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug"); registerReceiver(internalDebugReceiver, filter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); //getMenuInflater().inflate(R.menu.context_tab_contact, menu); } }