com.lykj.weixun.ui.chat.ui.ContactListFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.lykj.weixun.ui.chat.ui.ContactListFragment.java

Source

/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * 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.lykj.weixun.ui.chat.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.util.EMLog;
import com.lykj.aextreme.afinal.libzxing.activity.CaptureActivity;
import com.lykj.aextreme.afinal.nammu.Nammu;
import com.lykj.aextreme.afinal.nammu.PermissionCallback;
import com.lykj.bosheng.R;
import com.lykj.weixun.common.ComantUtils;
import com.lykj.weixun.dialog.PCLoginDialog;
import com.lykj.weixun.ui.chat.DemoHelper;
import com.lykj.weixun.ui.chat.db.InviteMessgeDao;
import com.lykj.weixun.ui.chat.db.UserDao;
import com.lykj.weixun.ui.directorie.LabelActivity;
import com.lykj.weixun.ui.directorie.UserDetailsActivity;

import java.util.Hashtable;
import java.util.Map;

/**
 * contact list
 */
public class ContactListFragment extends EaseContactListFragment implements OnClickListener {
    private static final String TAG = ContactListFragment.class.getSimpleName();
    private ContactSyncListener contactSyncListener;
    private BlackListSyncListener blackListSyncListener;
    private ContactInfoSyncListener contactInfoSyncListener;
    private View loadingView;
    private TextView applicationItem;
    private InviteMessgeDao inviteMessgeDao;
    private TextView unreadMsgView;

    @SuppressLint("InflateParams")
    @Override
    protected void initView() {
        super.initView();
        @SuppressLint("InflateParams")
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.em_contacts_header, null);
        HeaderItemClickListener clickListener = new HeaderItemClickListener();
        applicationItem = (TextView) headerView.findViewById(R.id.application_item);
        applicationItem.setOnClickListener(clickListener);
        unreadMsgView = (TextView) headerView.findViewById(R.id.unread_msg_number);
        headerView.findViewById(R.id.directorie_label).setOnClickListener(clickListener);
        headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
        headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
        headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
        listView.addHeaderView(headerView);
        loadingView = LayoutInflater.from(getActivity()).inflate(R.layout.em_layout_loading_data, null);
        contentContainer.addView(loadingView);
        registerForContextMenu(listView);
        titleBar.setRightImageResource(R.drawable.em_add);
        // ?
        titleBar.getRightLayout().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPopuWindow(v);//??
            }
        });
    }

    @Override
    public void refresh() {
        Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
        if (m instanceof Hashtable<?, ?>) {
            //noinspection unchecked
            m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>) m).clone();
        }
        setContactsMap(m);
        super.refresh();
        if (inviteMessgeDao == null) {
            inviteMessgeDao = new InviteMessgeDao(getActivity());
        }
        if (inviteMessgeDao.getUnreadMessagesCount() > 0) {
            showUnreadMsgView();
        } else {
            hideUnreadMsgView();
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    protected void setUpView() {
        //??
        Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
        if (m instanceof Hashtable<?, ?>) {
            m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>) m).clone();
        }
        setContactsMap(m);
        super.setUpView();
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EaseUser user = (EaseUser) listView.getItemAtPosition(position);
                if (user != null) {
                    String username = user.getUsername();
                    ComantUtils.ACTION_CONTACT_INDEXT = 1;
                    // demo??
                    Intent intent = new Intent();
                    intent.putExtra("userId", username);
                    intent.putExtra("title", "newPager");
                    intent.setClass(getActivity(), UserDetailsActivity.class);
                    startActivity(intent);
                    //                    startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", username));
                }
            }
        });

        contactSyncListener = new ContactSyncListener();
        DemoHelper.getInstance().addSyncContactListener(contactSyncListener);

        blackListSyncListener = new BlackListSyncListener();
        DemoHelper.getInstance().addSyncBlackListListener(blackListSyncListener);

        contactInfoSyncListener = new ContactInfoSyncListener();
        DemoHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);

        if (DemoHelper.getInstance().isContactsSyncedWithServer()) {
            loadingView.setVisibility(View.GONE);
        } else if (DemoHelper.getInstance().isSyncingContactsWithServer()) {
            loadingView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (contactSyncListener != null) {
            DemoHelper.getInstance().removeSyncContactListener(contactSyncListener);
            contactSyncListener = null;
        }

        if (blackListSyncListener != null) {
            DemoHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
        }

        if (contactInfoSyncListener != null) {
            DemoHelper.getInstance().getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.popuMeu_group://??
            startActivity(new Intent(getContext(), GroupPickContactsActivity.class));
            window.dismiss();
            break;
        case R.id.popuMeu_friend://?
            startActivity(new Intent(getActivity(), AddContactActivity.class));//?
            window.dismiss();
            break;
        case R.id.popuMeu_sweep://
            int permissionCheck1 = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA);
            if (permissionCheck1 == PackageManager.PERMISSION_GRANTED) {
                startActivityForResult(new Intent(getContext(), CaptureActivity.class),
                        ConversationListFragment.REQUEST_CODE);
                window.dismiss();
            } else {
                Nammu.askForPermission(this, Manifest.permission.CAMERA, new PermissionCallback() {
                    @Override
                    public void permissionGranted() {
                        startActivityForResult(new Intent(getContext(), CaptureActivity.class),
                                ConversationListFragment.REQUEST_CODE);
                        window.dismiss();
                    }

                    @Override
                    public void permissionRefused() {

                    }
                });
            }
            break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * ????
         */
        if (requestCode == ConversationListFragment.REQUEST_CODE) {
            //????
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    String result = bundle.getString("result");
                    if (result.contains("sid")) {
                        PCLoginDialog login = new PCLoginDialog(getContext(), result.replace("sid=", ""));
                        login.show();
                    } else {
                        if (isInteger(result)) {
                            Intent intent = new Intent();
                            intent.putExtra("userId", result);
                            intent.putExtra("title", "Conversation");
                            intent.setClass(getActivity(), UserDetailsActivity.class);
                            startActivity(intent);
                        }
                    }
                }
            }

        }
    }

    protected class HeaderItemClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.application_item:
                // ?
                startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
                break;
            case R.id.group_item:
                // ??
                startActivity(new Intent(getActivity(), GroupsActivity.class));
                break;
            case R.id.chat_room_item:
                //??
                startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class));
                break;
            case R.id.robot_item:
                //Robot?
                startActivity(new Intent(getActivity(), RobotsActivity.class));
                break;
            case R.id.directorie_label:
                //
                startActivity(new Intent(getActivity(), LabelActivity.class));
                break;
            default:
                break;
            }
        }

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        toBeProcessUser = (EaseUser) listView.getItemAtPosition(((AdapterContextMenuInfo) menuInfo).position);
        toBeProcessUsername = toBeProcessUser.getUsername();
        getActivity().getMenuInflater().inflate(R.menu.em_context_contact_list, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.delete_contact) {
            try {
                // delete contact
                deleteContact(toBeProcessUser);
                // remove invitation message
                InviteMessgeDao dao = new InviteMessgeDao(getActivity());
                dao.deleteMessage(toBeProcessUser.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
        //        else if (item.getItemId() == R.id.add_to_blacklist) {
        //            moveToBlacklist(toBeProcessUsername);
        //            return true;
        //        }
        return super.onContextItemSelected(item);
    }

    /**
     * delete contact
     *
     * @param
     */
    public void deleteContact(final EaseUser tobeDeleteUser) {
        String st1 = getResources().getString(R.string.deleting);
        final String st2 = getResources().getString(R.string.Delete_failed);
        final ProgressDialog pd = new ProgressDialog(getActivity());
        pd.setMessage(st1);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().contactManager().deleteContact(tobeDeleteUser.getUsername());
                    // remove user from memory and database
                    UserDao dao = new UserDao(getActivity());
                    dao.deleteContact(tobeDeleteUser.getUsername());
                    DemoHelper.getInstance().getContactList().remove(tobeDeleteUser.getUsername());
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            contactList.remove(tobeDeleteUser);
                            contactListLayout.refresh();

                        }
                    });
                } catch (final Exception e) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getActivity(), st2 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });

                }

            }
        }).start();

    }

    class ContactSyncListener implements DemoHelper.DataSyncListener {
        @Override
        public void onSyncComplete(final boolean success) {
            EMLog.d("aa", "on contact list sync success:" + success);
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (success) {
                                loadingView.setVisibility(View.GONE);
                                refresh();
                            } else {
                                String s1 = getResources().getString(R.string.get_failed_please_check);
                                Toast.makeText(getActivity(), s1, Toast.LENGTH_LONG).show();
                                loadingView.setVisibility(View.GONE);
                            }
                        }

                    });
                }
            });
        }
    }

    class BlackListSyncListener implements DemoHelper.DataSyncListener {

        @Override
        public void onSyncComplete(boolean success) {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    refresh();
                }
            });
        }

    }

    class ContactInfoSyncListener implements DemoHelper.DataSyncListener {

        @Override
        public void onSyncComplete(final boolean success) {
            EMLog.d(TAG, "on contactinfo list sync success:" + success);
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    loadingView.setVisibility(View.GONE);
                    if (success) {
                        refresh();
                    }
                }
            });
        }

    }

    public void setUnreadCount(int unreadCount) {
        unreadMsgView.setText(String.valueOf(unreadCount));
    }

    public void showUnreadMsgView() {
        unreadMsgView.setVisibility(View.VISIBLE);
    }

    public void hideUnreadMsgView() {
        unreadMsgView.setVisibility(View.INVISIBLE);
    }

    /**
     * popuwindow??
     *
     * @param view
     */
    private PopupWindow window;

    public void setPopuWindow(View view) {
        // 
        View inflateView = LayoutInflater.from(getContext()).inflate(R.layout.popu_meu, null);
        //
        window = new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());//??
        //
        window.setContentView(inflateView);
        // popWindow???true
        int[] location = new int[2];
        inflateView.getLocationOnScreen(location);
        window.setOutsideTouchable(true);
        window.showAsDropDown(view);//v?
        window.showAtLocation(inflateView, Gravity.NO_GRAVITY, location[0] + inflateView.getWidth() - 20,
                location[1]);
        inflateView.findViewById(R.id.popuMeu_group).setOnClickListener(this);
        inflateView.findViewById(R.id.popuMeu_friend).setOnClickListener(this);
        inflateView.findViewById(R.id.popuMeu_sweep).setOnClickListener(this);
        window.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // popupwindowpopupwindow
                // true?touch
                // ? PopupWindowonTouchEvent?dismiss
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    window.dismiss();
                    return true;
                }
                return false;
            }
        });

    }

    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}