app.view.main.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for app.view.main.MainActivity.java

Source

/**
 * 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 app.view.main;

import android.content.*;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import app.DemoApplication;
import app.view.chat.ChatActivity;
import app.view.chat.ChatAllHistoryFragment;
import app.view.chat.ContactListFragment;
import app.view.chat.GroupsActivity;
import app.view.circle.CircleFragment;
import app.view.login.LoginActivity;
import app.view.login.R;
import app.view.play_list.PlayListFragment;
import com.easemob.chat.*;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;
import com.easemob.util.HanziToPinyin;
import com.easemob.util.NetUtils;
import easemob.Constant;
import easemob.db.InviteMessageDao;
import easemob.db.UserDao;
import easemob.domain.InviteMessage;
import easemob.domain.User;
import utils.CommonUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends FragmentActivity {

    protected static final String TAG = "MainActivity";
    // ?textview
    private TextView unreadMessageLabel;
    // textview
    private TextView unreadContactLabel;

    private Button[] mTabs;

    /**
     * Fragments
     */
    private PlayListFragment playListFragment = null;
    private CircleFragment circleFragment = null;
    private ChatAllHistoryFragment chatHistoryFragment;
    private ContactListFragment contactListFragment;
    private Fragment[] fragments;

    private int index;
    private RelativeLayout[] tab_containers;
    // ?fragmentindex
    private int currentTabIndex;
    private NewMessageBroadcastReceiver msgReceiver;
    // ?
    private boolean isConflict = false;
    /**
     * ?BroadcastReceiver
     */
    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");
            EMConversation conversation = EMChatManager.getInstance().getConversation(from);
            if (conversation != null) {
                // message
                EMMessage msg = conversation.getMessage(msgid);
                if (msg != null) {
                    msg.isAcked = true;
                }
            }
            abortBroadcast();
        }
    };

    /**
     * ?BroadcastReceiver
     * sdk ????clientreceiverUI ???
     * UI ????
     */
    private BroadcastReceiver offlineMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String[] users = intent.getStringArrayExtra("fromuser");
            String[] groups = intent.getStringArrayExtra("fromgroup");
            if (users != null) {
                for (String user : users) {
                    System.out.println("user?" + user);
                }
            }
            if (groups != null) {
                for (String group : groups) {
                    System.out.println("group?" + group);
                }
            }
            abortBroadcast();
        }
    };
    private InviteMessageDao inviteMessageDao;
    private UserDao userDao;
    private android.app.AlertDialog.Builder conflictBuilder;
    private boolean isConflictDialogShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity_layout);
        initView();
        inviteMessageDao = new InviteMessageDao(this);
        userDao = new UserDao(this);

        //fragments
        playListFragment = new PlayListFragment();
        circleFragment = new CircleFragment();
        chatHistoryFragment = new ChatAllHistoryFragment();//?
        contactListFragment = new ContactListFragment();//
        fragments = new Fragment[] { playListFragment, circleFragment, chatHistoryFragment, contactListFragment };

        // fragment
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, playListFragment)
                .add(R.id.fragment_container, circleFragment).hide(circleFragment).show(playListFragment).commit();

        // ?BroadcastReceiver
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        // ack?BroadcastReceiver
        IntentFilter ackMessageIntentFilter = new IntentFilter(
                EMChatManager.getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(3);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        // ?BroadcastReceiver
        IntentFilter offlineMessageIntentFilter = new IntentFilter(
                EMChatManager.getInstance().getOfflineMessageBroadcastAction());
        registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);

        // setContactListener???
        EMContactManager.getInstance().setContactListener(new MyContactListener());
        // ??listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
        // ?listener
        EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());
        // sdkUI ??receiverlistener, ??broadcast
        EMChat.getInstance().setAppInited();
    }

    /**
     * ?
     */
    private void initView() {
        unreadMessageLabel = (TextView) findViewById(R.id.unread_message_number);
        unreadContactLabel = (TextView) findViewById(R.id.unread_friend_number);
        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.tabbar_playlist);
        mTabs[1] = (Button) findViewById(R.id.tabbar_circles);
        mTabs[2] = (Button) findViewById(R.id.tabbar_message);
        mTabs[3] = (Button) findViewById(R.id.tabbar_friends);
        // tab?
        mTabs[0].setSelected(true);
    }

    /**
     * button
     *
     * @param view
     */
    public void onTabClicked(View view) {
        switch (view.getId()) {
        case R.id.tabbar_playlist:
            index = 0;
            break;
        case R.id.tabbar_circles:
            index = 1;
            break;
        case R.id.tabbar_message:
            index = 2;
            break;
        case R.id.tabbar_friends:
            index = 3;
            break;
        }
        if (currentTabIndex != index) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                transaction.add(R.id.fragment_container, fragments[index]);
            }
            transaction.show(fragments[index]).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        // ?tab?
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 
        try {
            unregisterReceiver(msgReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(offlineMessageReceiver);
        } catch (Exception e) {
        }

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }

    }

    /**
     * ?
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            unreadMessageLabel.setText(String.valueOf(count));
            unreadMessageLabel.setVisibility(View.VISIBLE);
        } else {
            unreadMessageLabel.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * ?
     */
    public void updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
                    unreadContactLabel.setText(String.valueOf(count));
                    unreadContactLabel.setVisibility(View.VISIBLE);
                } else {
                    unreadContactLabel.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    /**
     * ??
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        if (DemoApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = DemoApplication.getInstance().getContactList()
                    .get(Constant.NEW_FRIENDS_USERNAME).getUnreadMsgCount();
        return unreadAddressCountTotal;
    }

    /**
     * ??
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        return unreadMsgCountTotal;
    }

    /**
     * ????
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // ???
        EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

        // bottom bar?
        updateUnreadAddressLable();
        // ??ui
        if (currentTabIndex == 1)
            contactListFragment.refresh();
    }

    /**
     * ?msg
     *
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // ?msg
        inviteMessageDao.saveMessage(msg);
        // 1
        User user = DemoApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
        user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }

    /**
     * set head
     *
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1)
                    .toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isConflict) {
            updateUnreadLabel();
            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * ??dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        DemoApplication.getInstance().logout();

        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) {
                Log.e("###", "---------color conflictBuilder error" + e.getMessage());
            }

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow)
            showConflictDialog();
    }

    /**
     * ?
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //????????chat?

            // ?id
            String msgId = intent.getStringExtra("msgid");
            // message?db?id?mesage
            // EMMessage message =
            // EMChatManager.getInstance().getMessage(msgId);

            // bottom bar?
            updateUnreadLabel();
            if (currentTabIndex == 0) {
                // ??????
                if (chatHistoryFragment != null) {
                    chatHistoryFragment.refresh();
                }
            }
            // ?ChatActivity
            abortBroadcast();
        }
    }

    /**
     * ??listener
     */
    private class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // ??
            Map<String, User> localUsers = DemoApplication.getInstance().getContactList();
            Map<String, User> toAddUsers = new HashMap<String, User>();
            for (String username : usernameList) {
                User user = setUserHead(username);
                // bug??added
                if (!localUsers.containsKey(username)) {
                    userDao.saveContact(user);
                }
                toAddUsers.put(username, user);
            }
            localUsers.putAll(toAddUsers);
            // ui
            if (currentTabIndex == 1)
                contactListFragment.refresh();

        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            // 
            Map<String, User> localUsers = DemoApplication.getInstance().getContactList();
            for (String username : usernameList) {
                localUsers.remove(username);
                userDao.deleteContact(username);
                inviteMessageDao.deleteMessage(username);
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    //??
                    if (ChatActivity.activityInstance != null
                            && usernameList.contains(ChatActivity.activityInstance.getToChatUsername())) {
                        Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername()
                                + "?", Toast.LENGTH_LONG).show();
                        ChatActivity.activityInstance.finish();
                    }
                    updateUnreadLabel();
                }
            });
            // ui
            if (currentTabIndex == 1)
                contactListFragment.refresh();

        }

        @Override
        public void onContactInvited(String username, String reason) {
            // ???(???)???????????
            List<InviteMessage> msgs = inviteMessageDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // ?javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            Log.d(TAG, username + "?,reason: " + reason);
            // status
            msg.setStatus(InviteMessage.InviteMesageStatus.BEINVITEED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactAgreed(String username) {
            List<InviteMessage> msgs = inviteMessageDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // ?javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "???");
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAGREED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactRefused(String username) {
            //TODO ???,demo

        }

    }

    /**
     * ?listener
     */
    private class MyConnectionListener implements ConnectionListener {

        @Override
        public void onConnected() {
            if (chatHistoryFragment.isAdded())
                chatHistoryFragment.errorItem.setVisibility(View.GONE);
        }

        @Override
        public void onDisConnected(String errorString) {
            if (errorString != null && errorString.contains("conflict")) {
                // ??dialog
                showConflictDialog();
            } else {
                if (chatHistoryFragment.isAdded()) {
                    chatHistoryFragment.errorItem.setVisibility(View.VISIBLE);

                    if (NetUtils.hasNetwork(MainActivity.this))
                        chatHistoryFragment.errorText.setText("???");
                    else
                        chatHistoryFragment.errorText.setText("???");
                }
            }
        }

        @Override
        public void onReConnected() {
            if (chatHistoryFragment.isAdded())
                chatHistoryFragment.errorItem.setVisibility(View.GONE);
        }

        @Override
        public void onReConnecting() {
        }

        @Override
        public void onConnecting(String progress) {
        }

    }

    /**
     * MyGroupChangeListener
     */
    private class MyGroupChangeListener implements GroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
            boolean hasGroup = false;
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 
            EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
            msg.setChatType(ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(inviter + "?"));
            // ??
            EMChatManager.getInstance().saveMessage(msg);
            // ???
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    if (currentTabIndex == 2)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onInvitationAccpted(String groupId, String inviter, String reason) {

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee, String reason) {

        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            // ??Tdemo?
            // ui
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        updateUnreadLabel();
                        if (currentTabIndex == 0)
                            chatHistoryFragment.refresh();
                        if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        Log.e("###", "refresh exception " + e.getMessage());
                    }

                }
            });
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            // 
            // ??,demo?
            // ui
            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    if (currentTabIndex == 0)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
            // ?
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " ?" + groupName);
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
        }

        @Override
        public void onApplicationAccept(String groupId, String groupName, String accepter) {
            //??
            EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
            msg.setChatType(ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(accepter + "???"));
            // ????
            EMChatManager.getInstance().saveMessage(msg);
            // ???
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
                    updateUnreadLabel();
                    // ui
                    if (currentTabIndex == 0)
                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            //?demo
        }

    }
}