org.xingjitong.LinphoneActivity.java Source code

Java tutorial

Introduction

Here is the source code for org.xingjitong.LinphoneActivity.java

Source

package org.xingjitong;

/*
 LinphoneActivity.java
 Copyright (C) 2012  Belledonne Communications, Grenoble, France
    
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.
    
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
import static android.content.Intent.ACTION_MAIN;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCall.State;
import org.linphone.core.LinphoneChatMessage;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneCore.EcCalibratorStatus;
import org.linphone.core.LinphoneCore.RegistrationState;
import org.linphone.core.LinphoneCoreException;
import org.linphone.core.LinphoneCoreFactory;
import org.linphone.core.LinphoneFriend;
import org.linphone.core.OnlineStatus;
import org.wecarephone.R;
import org.xingjitong.DialerFragment.OnItemClickedListener;
import org.xingjitong.LinphoneManager.AddressType;
import org.xingjitong.LinphoneManager.EcCalibrationListener;
import org.xingjitong.LinphoneManager.LinphoneConfigException;
import org.xingjitong.LinphoneSimpleListener.LinphoneOnCallStateChangedListener;
import org.xingjitong.LinphoneSimpleListener.LinphoneOnMessageReceivedListener;
import org.xingjitong.LinphoneSimpleListener.LinphoneOnRegistrationStateChangedListener;
import org.xingjitong.compatibility.ApiFivePlus;
import org.xingjitong.compatibility.Compatibility;
import org.xingjitong.money.Money_App_Activity;
import org.xingjitong.money.Money_Arriver_Activity;
import org.xingjitong.money.Money_Purse_Activiey;
import org.xingjitong.setup.SetupActivity;
import org.xingjitong.tang.db.CallsLogDB;
import org.xingjitong.tang.db.CallsLogUtils;
import org.xingjitong.tang.db.Common;
import org.xingjitong.tang.db.ContactDB;
import org.xingjitong.tang.db.MSG;
import org.xingjitong.tang.db.MyCallsLog;
import org.xingjitong.tang.set.HttpClientHelper;
import org.xingjitong.tang.set.UserConfig;
import org.xingjitong.tang.set.source.ActMonthlyRecharge;
import org.xingjitong.tang.set.source.SettingMes;
import org.xingjitong.tang.set.source.SettingQuery;
import org.xingjitong.tang.set.source.SettingSupp;
import org.xingjitong.ui.AddressText;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.CallLog;
import android.provider.ContactsContract.Data;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.Fragment.SavedState;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * ??
 * @author Sylvain Berfini
 */
public class LinphoneActivity extends FragmentActivity implements OnClickListener, ContactPicked,
        LinphoneOnCallStateChangedListener, LinphoneOnMessageReceivedListener,
        LinphoneOnRegistrationStateChangedListener, EcCalibrationListener, OnItemClickedListener {
    public static final String PREF_FIRST_LAUNCH = "pref_first_launch";
    private static final int SETTINGS_ACTIVITY = 123;
    private static final int FIRST_LOGIN_ACTIVITY = 101;
    private static final int callActivity = 19;
    public static int tableindex = 0;
    private SoChangeReceiver receiver;
    private CallsLogDB db;
    private static LinphoneActivity instance;
    private CallLogObServer callLog;
    private StatusFragment statusFragment;
    private TextView missedCalls, missedChats;
    //private ImageView dialer;  //yypplayout del
    public RelativeLayout dialer; //yypplayout del
    private LinearLayout menu, mark;
    public RelativeLayout contacts, history, settings, chat;

    private FragmentsAvailable currentFragment, nextFragment;
    private Fragment dialerFragment, messageListenerFragment, messageListFragment, friendStatusListenerFragment;
    private SavedState dialerSavedState;
    private ChatStorage chatStorage;
    private boolean preferLinphoneContacts = false, isAnimationDisabled = false, isContactPresenceDisabled = true;
    private Handler mHandler = new Handler();
    private List<Contact> contactList, sipContactList;
    private Cursor contactCursor, sipContactCursor;
    private OrientationEventListener mOrientationHelper;
    private App app;
    public String addnum;
    private ContactsObServer obser;
    private MSG msg;
    private boolean start, start2 = true;
    private SharedPreferences pref;
    private String reg = "^[\\+]?[0-9\\-\\ ]{6,32}$";
    private HistoryFragment chistory;
    private ContactsFragment ccontacts;
    private static long exitTime = 0; //yyppexit
    //yyppoption  add
    private View view;
    private PopupWindow pop;
    public static boolean isPopShowing = false;
    /**  */
    private LinearLayout mlayout_setting;
    /**  */
    private LinearLayout mlayout_about;
    /**  */
    private LinearLayout mlayout_exit;
    //yyppoption end   

    //      private String url="http://pay.wecare100.com/recharge/service/goodsList.php?agent_id=170";
    //      private String urlChargeMethod="http://pay.wecare100.com/recharge/service/payChannel.php?agent_id=170";

    private String adJson1;
    private String adJson2;

    public static final boolean isInstanciated() {
        return instance != null;
    }

    public static final LinphoneActivity instance() {
        if (instance != null)
            return instance;
        throw new RuntimeException("LinphoneActivity not instantiated yet");
    }

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        db = new CallsLogDB(this);
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                UserConfig.getInstance().getUserType(UserConfig.getInstance().phone, LinphoneActivity.this);

            }
        });
        mHandler.post(new Runnable() {

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

        Log.v("yyppdebug", "yyppexception linponeactivity 000");
        //yyppexception del
        /*
        if (isTablet()
        && getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
           Log.v("yyppdebug","yyppexception linponeactivity 111"); 
           setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        */

        if (!LinphoneManager.isInstanciated()) {
            Log.v("yyppdebug", "yyppexception linponeactivity 333");
            // super.onCreate called earlier
            finish();
            startActivity(getIntent().setClass(this, LinphoneLauncherActivity.class));
            return;
        }

        boolean useFirstLoginActivity = getResources().getBoolean(R.bool.use_first_login_activity);
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        if (useFirstLoginActivity && !pref.getBoolean(getString(R.string.first_launch_suceeded_once_key), false)) {
            if (pref.getInt(getString(R.string.pref_extra_accounts), -1) > -1) {
                pref.edit().putBoolean(getString(R.string.first_launch_suceeded_once_key), true);
            } else {
                startActivityForResult(new Intent().setClass(this, SetupActivity.class), FIRST_LOGIN_ACTIVITY);
            }
        }

        setContentView(R.layout.main);

        //?
        //            new Thread(new Runnable() {
        //
        //               @Override
        //               public void run() {
        //                  byte[] data=HttpClientHelper.loadByteFromURL(url);
        //                  if (data != null && data.length > 0) {
        //                     adJson1 = new String(data, 0, data.length);
        //                     Log.i("xushuang", "====1"+adJson1);
        //                     SharedPreferences prefs =getSharedPreferences("products", Context.MODE_PRIVATE);
        //                     Editor editor = prefs.edit();
        //                     editor.putString("products", adJson1);
        //                     editor.commit();
        //                  }
        //
        //               }
        //            }).start();

        //             new Thread(new Runnable() {
        //
        //                  @Override
        //                  public void run() {
        //                     byte[] data=HttpClientHelper.loadByteFromURL(urlChargeMethod);
        //                     if (data != null && data.length > 0) {
        //                        adJson2 = new String(data, 0, data.length);
        //                        SharedPreferences prefs =getSharedPreferences("methods", Context.MODE_PRIVATE);
        //                        Editor editor = prefs.edit();
        //                        editor.putString("methods", adJson2);
        //                        editor.commit();
        //                        
        //                     }
        //
        //                  }
        //               }).start();

        Log.v("yyppdebug", "yyppexception linponeactivity 555");
        initButtons();
        start = pref.getBoolean(getString(R.string.pref_call_phone_type), false);
        currentFragment = nextFragment = FragmentsAvailable.DIALER;
        if (savedInstanceState == null) {
            if (findViewById(R.id.fragmentContainer) != null) {
                dialerFragment = new DialerFragment();
                start2 = false;
                dialerFragment.setArguments(getIntent().getExtras());
                getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, dialerFragment).commit();
                selectMenu(FragmentsAvailable.DIALER);
            }
        }
        Log.v("yyppdebug", "yyppexception linponeactivity 666");
        msg = MSG.getInstance();
        int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
        displayMissedCalls(missedCalls);

        int rotation = Compatibility.getRotation(getWindowManager().getDefaultDisplay());
        // Inverse landscape rotation to initiate linphoneCore correctly
        if (rotation == 270)
            rotation = 90;
        else if (rotation == 90)
            rotation = 270;

        LinphoneManager.getLc().setDeviceRotation(rotation);
        mAlwaysChangingPhoneAngle = rotation;

        updateAnimationsState();
        receiver = new SoChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Common.SOCHANGE_ACTION);
        registerReceiver(receiver, filter);
        app = (App) getApplication();
        onClick(contacts);
        onClick(dialer);
        obser = new ContactsObServer(mHandler);
        getContentResolver().registerContentObserver(Data.CONTENT_URI, false, //
                obser);
        callLog = new CallLogObServer(mHandler);
        getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, false, callLog);
        start = pref.getBoolean(getString(R.string.pref_call_phone_type), false);
        //yyppoption add
        initPopupWindow();
        //yyppoption end

    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

    private void initButtons() {
        menu = (LinearLayout) findViewById(R.id.menu);
        mark = (LinearLayout) findViewById(R.id.mark);

        history = (RelativeLayout) findViewById(R.id.history);
        history.setOnClickListener(this);
        contacts = (RelativeLayout) findViewById(R.id.contacts);
        contacts.setOnClickListener(this);
        //yypplayout
        //dialer = (ImageView) findViewById(R.id.dialer);
        dialer = (RelativeLayout) findViewById(R.id.dialer);
        dialer.setOnClickListener(this);

        //yyppsetting del
        settings = (RelativeLayout) findViewById(R.id.settings);
        settings.setOnClickListener(this);

        //yyppsetting end

        chat = (RelativeLayout) findViewById(R.id.chat);
        chat.setOnClickListener(this);
        /*
         * aboutChat = (RelativeLayout) findViewById(R.id.about_chat);
         * aboutSettings = (RelativeLayout) findViewById(R.id.about_settings);
         * 
         * if (getResources().getBoolean(R.bool.replace_chat_by_about)) {
         * chat.setVisibility(View.GONE); chat.setOnClickListener(null);
         * findViewById(R.id.completeChat).setVisibility(View.GONE);
         * aboutChat.setVisibility(View.VISIBLE);
         * aboutChat.setOnClickListener(this); } if
         * (getResources().getBoolean(R.bool.replace_settings_by_about)) {
         * settings.setVisibility(View.GONE); settings.setOnClickListener(null);
         * aboutSettings.setVisibility(View.VISIBLE);
         * aboutSettings.setOnClickListener(this); }
         */
        missedCalls = (TextView) findViewById(R.id.missedCalls);
        missedChats = (TextView) findViewById(R.id.missedChats);
    }

    private boolean isTablet() {
        return getResources().getBoolean(R.bool.isTablet);
    }

    private void hideStatusBar() {
        if (isTablet()) {
            return;
        }

        findViewById(R.id.status).setVisibility(View.GONE);
        findViewById(R.id.fragmentContainer).setPadding(0, 0, 0, 0);
    }

    private void showStatusBar() {
        Log.e("-----------------", isTablet() + "");
        if (isTablet()) {
            return;
        }

        // findViewById(R.id.status).setVisibility(View.VISIBLE);
        // if (statusFragment != null && !statusFragment.isVisible()) {
        // // Hack to ensure statusFragment is visible after coming back to
        // // dialer from chat
        // // statusFragment.getView().setVisibility(View.VISIBLE);
        // }
        // // findViewById(R.id.fragmentContainer).setPadding(0,
        // // LinphoneUtils.pixelsToDpi(getResources(), 40), 0, 0);
        // findViewById(R.id.status).setVisibility(View.GONE);
        // statusFragment.getView().setVisibility(View.GONE);
    }

    public void changeCurrentFragment(FragmentsAvailable newFragmentType, Bundle extras) {
        changeCurrentFragment(newFragmentType, extras, false);
    }

    @SuppressWarnings("incomplete-switch")
    private void changeCurrentFragment(FragmentsAvailable newFragmentType, // -----
            Bundle extras, boolean withoutAnimation) {
        if (newFragmentType == currentFragment && newFragmentType != FragmentsAvailable.CHAT) {
            return;
        }
        nextFragment = newFragmentType;

        if (currentFragment == FragmentsAvailable.DIALER) {
            try {
                dialerSavedState = getSupportFragmentManager().saveFragmentInstanceState(dialerFragment);
            } catch (Exception e) {
            }
        }

        Fragment newFragment = null;

        switch (newFragmentType) {
        case HISTORY:
            // if (getResources().getBoolean(R.bool.use_simple_history)) {
            // newFragment = new HistorySimpleFragment();
            // } else {
            //?
            newFragment = new HistoryFragment();
            // }
            break;
        case HISTORY_DETAIL:
            //?
            newFragment = new HistoryDetailFragment();
            break;
        case CONTACTS:
            //?
            newFragment = new ContactsFragment();
            friendStatusListenerFragment = newFragment;
            break;
        case CONTACT:
            //?
            newFragment = new ContactFragment();
            break;
        case EDIT_CONTACT:
            //?
            newFragment = new EditContactFragment();
            break;
        case DIALER:
            //??
            newFragment = new DialerFragment();
            if (extras == null) {
                newFragment.setInitialSavedState(dialerSavedState);
            }
            dialerFragment = newFragment;
            break;
        case SETTINGS:
            //???
            // newFragment = new PreferencesFragment();//
            //newFragment = new Setting_layoutFragment();
            //yyppset add
            newFragment = new SettingSupp();
            tableindex = 1;
            break;
        case TITTLE_SETTINGS:
            //TITTLE?
            // newFragment = new PreferencesFragment();//
            //newFragment = new Setting_layoutFragment();
            newFragment = new Setting_popup();

            break;
        case ACCOUNT_SETTINGS:
            newFragment = new AccountPreferencesFragment();
            break;
        // case ABOUT:
        // case ABOUT_INSTEAD_OF_CHAT:
        // case ABOUT_INSTEAD_OF_SETTINGS:
        // newFragment = new AboutFragment();
        // break;
        case CHAT:
            //??
            newFragment = new ChatFragment();
            messageListenerFragment = newFragment;
            break;
        case CHATLIST:
            //??
            newFragment = new MoneyListFragment();
            messageListFragment = new Fragment();
            tableindex = 2;
            break;
        case SET_CHONGZHI:
            //? ? 
            newFragment = new SettingSupp();
            //yyppset.del------------------------
            //messageListFragment = new Fragment();
            break;
        case MONEY_ADD:
            //
            //newFragment = new Money_Add_Activiey();
            newFragment = new SettingSupp(); //yyppchong//yyppset
            //messageListFragment = new Fragment();
            break;
        case MONEY_APP:
            newFragment = new Money_App_Activity();
            //messageListFragment = new Fragment();
            //app
            break;
        case MONEY_ARRIVES:
            newFragment = new Money_Arriver_Activity();
            //messageListFragment = new Fragment();
            //?
            break;
        case MONEY_PURSE:
            newFragment = new Money_Purse_Activiey();
            //messageListFragment = new Fragment();
            //
            break;
        case SET_CHONGZHIKA:
            //
            newFragment = new ActMonthlyRecharge();
            //yyppset.del-------------
            //messageListFragment = new Fragment();
            break;
        case SET_MES:
            //   
            newFragment = new SettingMes();
            messageListFragment = new Fragment();
            break;
        case SET_QUERY:
            //???
            newFragment = new SettingQuery();
            //yyppset.del-----------------
            //messageListFragment = new Fragment();
            break;
        case SET_ALIPAY:
            //         newFragment = new AlixDemo();
            //         messageListFragment = new Fragment();
            break;
        }
        if (newFragment != null) {
            newFragment.setArguments(extras);
            if (isTablet()) {
                changeFragmentForTablets(newFragment, newFragmentType, withoutAnimation);
            } else {
                changeFragment(newFragment, newFragmentType, withoutAnimation);
            }
        }
    }

    private void updateAnimationsState() {
        // SharedPreferences prefs =
        // PreferenceManager.getDefaultSharedPreferences(this);
        // isAnimationDisabled =
        // getResources().getBoolean(R.bool.disable_animations) ||
        // !prefs.getBoolean(getString(R.string.pref_animation_enable_key),
        // false);
        isAnimationDisabled = getApplicationContext().getResources()
                .getBoolean(R.bool.pref_animation_enable_default);
        isContactPresenceDisabled = !getResources().getBoolean(R.bool.enable_linphone_friends);
    }

    public boolean isAnimationDisabled() {
        return isAnimationDisabled;
    }

    public boolean isContactPresenceDisabled() {
        return isContactPresenceDisabled;
    }

    private void changeFragment(Fragment newFragment, FragmentsAvailable newFragmentType,
            boolean withoutAnimation) {
        if (getResources().getBoolean(R.bool.show_statusbar_only_on_dialer)) {
            if (newFragmentType == FragmentsAvailable.DIALER) {
                showStatusBar();
            } else {
                hideStatusBar();
            }
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (!withoutAnimation && !isAnimationDisabled && currentFragment.shouldAnimate()) {
            if (newFragmentType.isRightOf(currentFragment)) {
                transaction.setCustomAnimations(R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left,
                        R.anim.slide_in_left_to_right, R.anim.slide_out_left_to_right);
            } else {
                transaction.setCustomAnimations(R.anim.slide_in_left_to_right, R.anim.slide_out_left_to_right,
                        R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
            }
        }
        //      try {
        //         getSupportFragmentManager().popBackStackImmediate(
        //               newFragmentType.toString(),
        //               FragmentManager.POP_BACK_STACK_INCLUSIVE);
        //      } catch (java.lang.IllegalStateException e) {//?? 
        //
        //      }

        transaction.addToBackStack(newFragmentType.toString());
        transaction.replace(R.id.fragmentContainer, newFragment);
        if (isInstanciated()) {
            try {
                transaction.commitAllowingStateLoss();
            } catch (Exception e) {
            }
        }
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                getSupportFragmentManager().executePendingTransactions();
            }
        });

        currentFragment = newFragmentType;
    }

    private void changeFragmentForTablets(Fragment newFragment, FragmentsAvailable newFragmentType,
            boolean withoutAnimation) {
        if (getResources().getBoolean(R.bool.show_statusbar_only_on_dialer)) {
            if (newFragmentType == FragmentsAvailable.DIALER) {
                showStatusBar();
            } else {
                hideStatusBar();
            }
        }

        LinearLayout ll = (LinearLayout) findViewById(R.id.fragmentContainer); //yyppsize R.id.fragmentContainer2);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (newFragmentType.shouldAddItselfToTheRightOf(currentFragment)) {
            ll.setVisibility(View.VISIBLE);

            transaction.addToBackStack(newFragmentType.toString());
            transaction.replace(R.id.fragmentContainer, newFragment); //yyppsize R.id.fragmentContainer2);
        } else {
            if (newFragmentType == FragmentsAvailable.DIALER
                    // || newFragmentType == FragmentsAvailable.ABOUT
                    // || newFragmentType ==
                    // FragmentsAvailable.ABOUT_INSTEAD_OF_CHAT
                    // || newFragmentType ==
                    // FragmentsAvailable.ABOUT_INSTEAD_OF_SETTINGS
                    || newFragmentType == FragmentsAvailable.SETTINGS
                    || newFragmentType == FragmentsAvailable.ACCOUNT_SETTINGS) {
                ll.setVisibility(View.GONE);
            } else {
                ll.setVisibility(View.INVISIBLE);
            }

            if (!withoutAnimation && !isAnimationDisabled && currentFragment.shouldAnimate()) {
                if (newFragmentType.isRightOf(currentFragment)) {
                    transaction.setCustomAnimations(R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left,
                            R.anim.slide_in_left_to_right, R.anim.slide_out_left_to_right);
                } else {
                    transaction.setCustomAnimations(R.anim.slide_in_left_to_right, R.anim.slide_out_left_to_right,
                            R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
                }
            }

            try {
                getSupportFragmentManager().popBackStackImmediate(newFragmentType.toString(),
                        FragmentManager.POP_BACK_STACK_INCLUSIVE);
            } catch (java.lang.IllegalStateException e) {

            }

            transaction.addToBackStack(newFragmentType.toString());
            transaction.replace(R.id.fragmentContainer, newFragment);
        }
        transaction.commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();

        currentFragment = newFragmentType;
    }

    public void displayHistoryDetail(String num, MyCallsLog callsLog) {
        String sipUri = "sip:" + num + "@" + getResources().getString(R.string.pref_domain_default);
        LinphoneAddress lAddress = LinphoneCoreFactory.instance().createLinphoneAddress(sipUri);
        Uri uri = LinphoneUtils.findUriPictureOfContactAndSetDisplayName(lAddress, getContentResolver());
        String pictureUri = uri == null ? null : uri.toString();
        String displayName = callsLog.name;
        String status = null;
        switch (callsLog.type) {
        case 1:
            status = "";
            break;
        case 2:
            status = "";
            break;
        case 3:
            status = "";
            break;
        }
        Fragment fragment2 = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer); //yyppsize R.id.fragmentContainer2);
        if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.HISTORY_DETAIL) {
            HistoryDetailFragment historyDetailFragment = (HistoryDetailFragment) fragment2;
            historyDetailFragment.changeDisplayedHistory(sipUri, callsLog.name, uri.toString(), status,
                    callsLog.duraction, callsLog.date);
        } else {
            Bundle extras = new Bundle();
            extras.putString("SipUri", pictureUri);
            if (displayName != null) {
                extras.putString("DisplayName", displayName);
                extras.putString("PictureUri", pictureUri);
            }
            extras.putString("CallStatus", status);
            extras.putString("CallTime", callsLog.duraction);
            extras.putString("CallDate", callsLog.date);
            extras.putString("number", callsLog.number);
            changeCurrentFragment(FragmentsAvailable.HISTORY_DETAIL, extras);// ------
        }
    }

    @SuppressWarnings("unused")
    private String secondsToDisplayableString(int secs) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.set(0, 0, 0, 0, 0, secs);
        return dateFormat.format(cal.getTime());
    }

    public void displayContact(Contact contact, boolean chatOnly) {
        Fragment fragment2 = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer); //yyppsize R.id.fragmentContainer2);
        if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.CONTACT) {
            ContactFragment contactFragment = (ContactFragment) fragment2;
            contactFragment.changeDisplayedContact(contact);
        } else {
            Bundle extras = new Bundle();
            extras.putSerializable("Contact", contact);
            extras.putBoolean("ChatAddressOnly", chatOnly);
            changeCurrentFragment(FragmentsAvailable.CONTACT, extras);
        }
    }

    public void displayContacts(boolean chatOnly) {
        if (chatOnly) {
            preferLinphoneContacts = true;
        }

        Bundle extras = new Bundle();
        extras.putBoolean("ChatAddressOnly", chatOnly);
        changeCurrentFragment(FragmentsAvailable.CONTACTS, extras);
        preferLinphoneContacts = false;
    }

    public void displayContactsForEdition(String sipAddress) {
        Bundle extras = new Bundle();
        extras.putBoolean("EditOnClick", true);
        extras.putString("SipAddress", sipAddress);
        extras.putString("addnum", addnum);
        changeCurrentFragment(FragmentsAvailable.EDIT_CONTACT, extras);//intent to editor contacts fragment
    }

    public void displayAbout() {
        // changeCurrentFragment(FragmentsAvailable.ABOUT, null);
    }

    @SuppressWarnings("unchecked")
    public void displayChat(String sipUri) {
        if (getResources().getBoolean(R.bool.disable_chat)) {
            return;
        }

        LinphoneAddress lAddress = LinphoneCoreFactory.instance().createLinphoneAddress(sipUri);
        Uri uri = LinphoneUtils.findUriPictureOfContactAndSetDisplayName(lAddress, getContentResolver());
        String displayName = lAddress.getDisplayName();
        if (displayName == null) {
            String phone = sipUri.substring(sipUri.indexOf(":") + 1, sipUri.indexOf("@"));
            List<Contact> list = (List<Contact>) ContactDB.Instance().getAllOb()[2];
            for (Contact c : list) {
                if (phone.equals(c.num)) {
                    displayName = c.name;
                    break;
                }
            }
        }
        String pictureUri = uri == null ? null : uri.toString();
        if (currentFragment == FragmentsAvailable.CHATLIST || currentFragment == FragmentsAvailable.MONEY_APP
                || currentFragment == FragmentsAvailable.CHAT || currentFragment == FragmentsAvailable.MONEY_ADD
                || currentFragment == FragmentsAvailable.MONEY_ARRIVES
                || currentFragment == FragmentsAvailable.MONEY_PURSE) {
            Fragment fragment2 = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer); //yyppsize R.id.fragmentContainer2);
            if (fragment2 != null && fragment2.isVisible() && currentFragment == FragmentsAvailable.CHAT) {
                ChatFragment chatFragment = (ChatFragment) fragment2;
                chatFragment.changeDisplayedChat(sipUri, displayName, pictureUri);
            } else {
                Bundle extras = new Bundle();
                extras.putString("SipUri", sipUri);
                extras.putString("DisplayName", displayName);
                extras.putString("PictureUri", pictureUri);
                changeCurrentFragment(FragmentsAvailable.CHAT, extras);
            }
        } else {
            changeCurrentFragment(FragmentsAvailable.CHATLIST, null);
            displayChat(sipUri);
        }
        LinphoneService.instance().resetMessageNotifCount();
        LinphoneService.instance().removeMessageNotification();
        displayMissedChats(getChatStorage().getUnreadMessageCount());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        resetSelection();
        switch (id) {
        case R.id.history:
            changeCurrentFragment(FragmentsAvailable.HISTORY, null);
            history.setSelected(true);
            LinphoneManager.getLc().resetMissedCallsCount();// -------
            displayMissedCalls(0);
            break;
        case R.id.contacts:
            changeCurrentFragment(FragmentsAvailable.CONTACTS, null);
            contacts.setSelected(true);
            break;
        case R.id.dialer:
            changeCurrentFragment(FragmentsAvailable.DIALER, null);
            dialer.setSelected(true);
            break;
        //yyppsetting del
        /*
        case R.id.settings:
        changeCurrentFragment(FragmentsAvailable.SETTINGS, null);
        settings.setSelected(true);
        break;
        */
        case R.id.chat:
            changeCurrentFragment(FragmentsAvailable.CHATLIST, null);
            chat.setSelected(true);
            break;
        }

        /*
         * } else if (id == R.id.about_chat) { Bundle b = new Bundle();
         * b.putSerializable("About", FragmentsAvailable.ABOUT_INSTEAD_OF_CHAT);
         * changeCurrentFragment(FragmentsAvailable.ABOUT_INSTEAD_OF_CHAT, b);
         * aboutChat.setSelected(true); } else if (id == R.id.about_settings) {
         * Bundle b = new Bundle(); b.putSerializable("About",
         * FragmentsAvailable.ABOUT_INSTEAD_OF_SETTINGS); changeCurrentFragment
         * (FragmentsAvailable.ABOUT_INSTEAD_OF_SETTINGS, b);
         * aboutSettings.setSelected(true);
         */
    }

    private void resetSelection() {
        history.setSelected(false);
        contacts.setSelected(false);
        dialer.setSelected(false);
        settings.setSelected(false);
        chat.setSelected(false);
        // aboutChat.setSelected(false);
        // aboutSettings.setSelected(false);
    }

    @SuppressWarnings("incomplete-switch")
    public void selectMenu(FragmentsAvailable menuToSelect) {
        currentFragment = menuToSelect;
        resetSelection();

        switch (menuToSelect) {
        case HISTORY:
        case HISTORY_DETAIL:
            history.setSelected(true);
            break;
        case CONTACTS:
        case CONTACT:
        case EDIT_CONTACT:
            contacts.setSelected(true);
            break;
        case DIALER:
            dialer.setSelected(true);
            break;
        case SETTINGS:
        case SET_CHONGZHI:
        case SET_CHONGZHIKA:
        case SET_MES:
        case SET_QUERY:
        case SET_ALIPAY:
        case ACCOUNT_SETTINGS:
            settings.setSelected(true);
            break;
        /*
         * case ABOUT_INSTEAD_OF_CHAT: aboutChat.setSelected(true); break; case
         * ABOUT_INSTEAD_OF_SETTINGS: aboutSettings.setSelected(true); break;
         */
        case CHAT:
        case CHATLIST:
        case MONEY_ADD:
        case MONEY_ARRIVES:
        case MONEY_APP:
        case MONEY_PURSE:
            chat.setSelected(true);
            break;
        }

    }

    public void updateDialerFragment(DialerFragment fragment) {
        dialerFragment = fragment;
        // Hack to maintain soft input flags
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
                | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    public void updateChatFragment(ChatFragment fragment) {
        messageListenerFragment = fragment;
        // Hack to maintain soft input flags
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    public void updateChatListFragment(MoneyListFragment fragment) {
        messageListFragment = fragment;
    }

    public void hideMenu(boolean hide) {
        menu.setVisibility(hide ? View.GONE : View.VISIBLE);
        mark.setVisibility(hide ? View.GONE : View.VISIBLE);
    }

    public void updateStatusFragment(StatusFragment fragment) {
        statusFragment = fragment;

        LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
        if (lc != null && lc.getDefaultProxyConfig() != null) {
            statusFragment.registrationStateChanged(LinphoneManager.getLc().getDefaultProxyConfig().getState());
        }
    }

    public void displaySettings() {
        changeCurrentFragment(FragmentsAvailable.SETTINGS, null);
        settings.setSelected(true);
    }

    public void applyConfigChangesIfNeeded() {
        if (nextFragment != FragmentsAvailable.SETTINGS && nextFragment != FragmentsAvailable.ACCOUNT_SETTINGS) {
            reloadConfig();
            updateAnimationsState();
        }
    }

    private void reloadConfig() {
        LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();

        if (lc != null && (lc.isInComingInvitePending() || lc.isIncall())) {
            return;
        }

        try {
            LinphoneManager.getInstance().initFromConf();
            lc.setVideoPolicy(LinphoneManager.getInstance().isAutoInitiateVideoCalls(),
                    LinphoneManager.getInstance().isAutoAcceptCamera());
        } catch (LinphoneException e) {
            if (!(e instanceof LinphoneConfigException)) {
                return;
            }

            LinphoneActivity.instance().showPreferenceErrorDialog(e.getMessage());
        }
    }

    public void displayAccountSettings(int accountNumber) {
        Bundle bundle = new Bundle();
        bundle.putInt("Account", accountNumber);
        changeCurrentFragment(FragmentsAvailable.ACCOUNT_SETTINGS, bundle);
        settings.setSelected(true);
    }

    public StatusFragment getStatusFragment() {
        return statusFragment;
    }

    public List<String> getChatList() {
        return getChatStorage().getChatList();
    }

    public List<String> getDraftChatList() {
        return getChatStorage().getDrafts();
    }

    public List<ChatMessage> getChatMessages(String correspondent) {
        return getChatStorage().getMessages(correspondent);
    }

    public void removeFromChatList(String sipUri) {
        getChatStorage().removeDiscussion(sipUri);
    }

    public void removeFromDrafts(String sipUri) {
        getChatStorage().deleteDraft(sipUri);
    }

    @Override
    public void onMessageReceived(LinphoneAddress from, LinphoneChatMessage message) {
        if (getResources().getBoolean(R.bool.disable_chat)) {
            return;
        }

        String textMessage = message.getMessage();
        String url = message.getExternalBodyUrl();
        String notificationText = null;
        int id = -1;
        if (textMessage != null && textMessage.length() > 0) {
            id = getChatStorage().saveMessage(from.asStringUriOnly(), "", textMessage);
            notificationText = textMessage;
        } else if (url != null && url.length() > 0) {
            Bitmap bm = ChatFragment.downloadImage(url);
            id = getChatStorage().saveMessage(from.asStringUriOnly(), "", bm);
            notificationText = url;
        }

        ChatFragment chatFragment = ((ChatFragment) messageListenerFragment);
        if (messageListenerFragment != null && messageListenerFragment.isVisible()
                && chatFragment.getSipUri().equals(from.asStringUriOnly())) {
            chatFragment.onMessageReceived(id, from, message);
            getChatStorage().markMessageAsRead(id);
        } else if (LinphoneService.isReady()) {
            displayMissedChats(getChatStorage().getUnreadMessageCount());
            if (messageListFragment != null && messageListFragment.isVisible()) {
                ((MoneyListFragment) messageListFragment).refresh();
            }
        }
        LinphoneUtils.findUriPictureOfContactAndSetDisplayName(from, getContentResolver());
        LinphoneService.instance().displayMessageNotification(from.asStringUriOnly(), from.getDisplayName(),
                notificationText);
    }

    public void updateMissedChatCount() {
        displayMissedChats(getChatStorage().getUnreadMessageCount());
    }

    public int onMessageSent(String to, String message) {
        getChatStorage().deleteDraft(to);
        return getChatStorage().saveMessage("", to, message);
    }

    public int onMessageSent(String to, Bitmap image, String imageURL) {
        getChatStorage().deleteDraft(to);
        return getChatStorage().saveMessage("", to, image);
    }

    public void onMessageStateChanged(String to, String message, int newState) {
        getChatStorage().updateMessageStatus(to, message, newState);
    }

    public void onImageMessageStateChanged(String to, int id, int newState) {
        getChatStorage().updateMessageStatus(to, id, newState);
    }

    @Override
    public void onRegistrationStateChanged(RegistrationState state) {
        if (statusFragment != null) {
            LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
            if (lc != null && lc.getDefaultProxyConfig() != null)
                statusFragment.registrationStateChanged(lc.getDefaultProxyConfig().getState());
        }
    }

    private void displayMissedCalls(final int missedCallsCount) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (missedCallsCount > 0) {
                    missedCalls.setText(missedCallsCount + "");
                    missedCalls.setVisibility(View.VISIBLE);
                    if (!isAnimationDisabled) {
                        missedCalls
                                .startAnimation(AnimationUtils.loadAnimation(LinphoneActivity.this, R.anim.bounce));
                    }
                } else {
                    missedCalls.clearAnimation();
                    missedCalls.setVisibility(View.GONE);
                }
            }
        });
    }

    private void displayMissedChats(final int missedChatCount) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (missedChatCount > 0) {
                    missedChats.setText(missedChatCount + "");
                    if (missedChatCount > 99) {
                        missedChats.setTextSize(12);
                    } else {
                        missedChats.setTextSize(20);
                    }
                    missedChats.setVisibility(View.VISIBLE);
                    if (!isAnimationDisabled) {
                        missedChats
                                .startAnimation(AnimationUtils.loadAnimation(LinphoneActivity.this, R.anim.bounce));
                    }
                } else {
                    missedChats.clearAnimation();
                    missedChats.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onCallStateChanged(LinphoneCall call, State state, String message) {
        if (state == State.IncomingReceived) {
            startActivity(new Intent(this, IncomingCallActivity.class));
        } else if (state == State.OutgoingInit) {
            if (call.getCurrentParamsCopy().getVideoEnabled()) {
                startVideoActivity(call);
            } else {
                startIncallActivity(call);
            }
            // ???????????
        } else if (state == State.CallEnd || state == State.Error || state == State.CallReleased) {
            Intent intent = new Intent(Common.SOCHANGE_ACTION);
            sendBroadcast(intent);
            // Convert LinphoneCore message for internalization
            if (message != null && message.equals("Call declined.")) {
                displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_LONG);
            } else if (message != null && message.equals("User not found.")) {
                displayCustomToast(getString(R.string.error_user_not_found), Toast.LENGTH_LONG);
            } else if (message != null && message.equals("Incompatible media parameters.")) {
                displayCustomToast(getString(R.string.error_incompatible_media), Toast.LENGTH_LONG);
            }
            resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
        }

        int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
        displayMissedCalls(missedCalls);
    }

    public void displayCustomToast(final String message, final int duration) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));

                TextView toastText = (TextView) layout.findViewById(R.id.toastMessage);
                toastText.setText(message);
                final Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.setDuration(duration);
                toast.setView(layout);
                toast.show();
            }
        });
    }

    //yyppdial
    @Override
    public void setAddresGoToDialerAndCall(String number, String name, Uri photo) {
        if (!number.matches(reg)) {
            Toast.makeText(this, "??!", Toast.LENGTH_SHORT).show();
            return;
        }
        //yyppnotice add
        if (UserConfig.getInstance().loginstatus != 0) {
            Toast.makeText(this, "!", Toast.LENGTH_SHORT).show();
        }
        Bundle extras = new Bundle();
        extras.putString("SipUri", number);
        extras.putString("DisplayName", name);
        extras.putString("Photo", photo == null ? null : photo.toString());
        changeCurrentFragment(FragmentsAvailable.DIALER, extras);

        AddressType address = new AddressText(this, null);
        address.setDisplayedName(name);
        address.setText(number);
        if (LinphoneManager.getLc().getCallsNb() == 0) {
            LinphoneManager.getInstance().newOutgoingCall(address);
            app.setCallNum(number);
        }
    }

    public void setAddressAndGoToDialer(String number) {
        Bundle extras = new Bundle();
        extras.putString("SipUri", number);
        changeCurrentFragment(FragmentsAvailable.DIALER, extras);
    }

    @Override
    public void goToDialer() {
        changeCurrentFragment(FragmentsAvailable.DIALER, null);
    }

    public void startVideoActivity(LinphoneCall currentCall) {// uuuuuuuuuuu
        Intent intent = new Intent(this, InCallActivity.class);
        intent.putExtra("VideoEnabled", true);
        startOrientationSensor();
        startActivityForResult(intent, callActivity);// /---------------
    }

    public void startIncallActivity(LinphoneCall currentCall) {
        Intent intent = new Intent(this, InCallActivity.class);
        intent.putExtra("VideoEnabled", false);
        startOrientationSensor();
        startActivityForResult(intent, callActivity);
    }

    public void startActivityForResult(String phone) {
        Intent intent = new Intent(this, InCallActivity2.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.putExtra("phone", phone);
        startActivity(intent);
    }

    /**
     * Register a sensor to track phoneOrientation changes
     */
    private synchronized void startOrientationSensor() {
        if (mOrientationHelper == null) {
            mOrientationHelper = new LocalOrientationEventListener(this);
        }
        mOrientationHelper.enable();
    }

    private int mAlwaysChangingPhoneAngle = -1;
    private AcceptNewFriendDialog acceptNewFriendDialog;

    private class LocalOrientationEventListener extends OrientationEventListener {
        public LocalOrientationEventListener(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(final int o) {
            if (o == OrientationEventListener.ORIENTATION_UNKNOWN) {
                return;
            }

            int degrees = 270;
            if (o < 45 || o > 315)
                degrees = 0;
            else if (o < 135)
                degrees = 90;
            else if (o < 225)
                degrees = 180;

            if (mAlwaysChangingPhoneAngle == degrees) {
                return;
            }
            mAlwaysChangingPhoneAngle = degrees;

            int rotation = (360 - degrees) % 360;
            LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
            if (lc != null) {
                lc.setDeviceRotation(rotation);
                LinphoneCall currentCall = lc.getCurrentCall();
                if (currentCall != null && currentCall.cameraEnabled()
                        && currentCall.getCurrentParamsCopy().getVideoEnabled()) {
                    lc.updateCall(currentCall, null);
                }
            }
        }
    }

    public void showPreferenceErrorDialog(String message) {

    }

    public List<Contact> getAllContacts() {
        return contactList;
    }

    public List<Contact> getSIPContacts() {
        return sipContactList;
    }

    public Cursor getAllContactsCursor() {
        return contactCursor;
    }

    public Cursor getSIPContactsCursor() {
        return sipContactCursor;
    }

    public void setLinphoneContactsPrefered(boolean isPrefered) {
        preferLinphoneContacts = isPrefered;
    }

    public boolean isLinphoneContactsPrefered() {
        return preferLinphoneContacts;
    }

    private void refreshStatus(OnlineStatus status) {
        if (LinphoneManager.isInstanciated()) {
            LinphoneManager.getLcIfManagerNotDestroyedOrNull().setPresenceInfo(0, "", status);
        }
    }

    public void onNewSubscriptionRequestReceived(LinphoneFriend friend, String sipUri) {
        boolean isAutoAcceptFriends;

        if (isContactPresenceDisabled) {
            return;
        }

        sipUri = sipUri.replace("<", "").replace(">", "");
        // SharedPreferences prefs =
        // PreferenceManager.getDefaultSharedPreferences(this);
        // isAutoAcceptFriends =
        // prefs.getBoolean(getString(R.string.pref_auto_accept_friends_key),
        // false);
        isAutoAcceptFriends = getApplicationContext().getResources()
                .getBoolean(R.bool.pref_auto_accept_friends_default);
        if (isAutoAcceptFriends) {
            Contact contact = findContactWithSipAddress(sipUri);
            if (contact != null) {
                friend.enableSubscribes(true);
                try {
                    LinphoneManager.getLc().addFriend(friend);
                    contact.setFriend(friend);
                } catch (LinphoneCoreException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Contact contact = findContactWithSipAddress(sipUri);
            if (contact != null) {
                FragmentManager fm = getSupportFragmentManager();
                acceptNewFriendDialog = new AcceptNewFriendDialog(contact, sipUri);
                acceptNewFriendDialog.show(fm, "New Friend Request Dialog");
            }
        }
    }

    private Contact findContactWithSipAddress(String sipUri) {
        if (!sipUri.startsWith("sip:")) {
            sipUri = "sip:" + sipUri;
        }

        for (Contact contact : sipContactList) {
            for (String addr : contact.getNumerosOrAddresses()) {
                if (addr.equals(sipUri)) {
                    return contact;
                }
            }
        }
        return null;
    }

    public void onNotifyPresenceReceived(LinphoneFriend friend) {
        if (!isContactPresenceDisabled && currentFragment == FragmentsAvailable.CONTACTS
                && friendStatusListenerFragment != null) {
            ((ContactsFragment) friendStatusListenerFragment).invalidate();
        }
    }

    public boolean newFriend(Contact contact, String sipUri) {
        LinphoneFriend friend = LinphoneCoreFactory.instance().createLinphoneFriend(sipUri);
        friend.enableSubscribes(true);
        friend.setIncSubscribePolicy(LinphoneFriend.SubscribePolicy.SPAccept);
        try {
            LinphoneManager.getLc().addFriend(friend);
            contact.setFriend(friend);
            return true;
        } catch (LinphoneCoreException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void acceptNewFriend(Contact contact, String sipUri, boolean accepted) {
        acceptNewFriendDialog.dismissAllowingStateLoss();
        if (accepted) {
            newFriend(contact, sipUri);
        }
    }

    public boolean removeFriend(Contact contact, String sipUri) {
        LinphoneFriend friend = LinphoneManager.getLc().findFriendByAddress(sipUri);
        if (friend != null) {
            friend.enableSubscribes(false);
            LinphoneManager.getLc().removeFriend(friend);
            contact.setFriend(null);
            return true;
        }
        return false;
    }

    private void searchFriendAndAddToContact(Contact contact) {
        if (contact == null || contact.getNumerosOrAddresses() == null) {
            return;
        }

        for (String sipUri : contact.getNumerosOrAddresses()) {
            if (LinphoneUtils.isSipAddress(sipUri)) {
                LinphoneFriend friend = LinphoneManager.getLc().findFriendByAddress(sipUri);
                if (friend != null) {
                    friend.enableSubscribes(true);
                    friend.setIncSubscribePolicy(LinphoneFriend.SubscribePolicy.SPAccept);
                    contact.setFriend(friend);
                    break;
                }
            }
        }
    }

    public void removeContactFromLists(Contact contact) {
        if (contactList.contains(contact)) {
            contactList.remove(contact);
            contactCursor = Compatibility// ----------
                    .getContactsCursor(getContentResolver(), 0, 0, ApiFivePlus.LIMIT_TYPE_N);
        }
        if (sipContactList.contains(contact)) {
            sipContactList.remove(contact);
            sipContactCursor = Compatibility.getSIPContactsCursor(getContentResolver());
        }
        if (currentFragment == FragmentsAvailable.CONTACTS) {
            new Thread() {
                public void run() {
                    ContactDB.Instance().setAllDB();
                    ccontacts.changeData();
                }
            }.start();
        }
    }

    public synchronized void prepareContactsInBackground() {// 1
        if (contactCursor != null) {
            contactCursor.close();
        }
        if (sipContactCursor != null) {
            sipContactCursor.close();
        }

        contactCursor = Compatibility.getContactsCursor(getContentResolver(), 0, 0, ApiFivePlus.LIMIT_TYPE_N);
        sipContactCursor = Compatibility.getSIPContactsCursor(getContentResolver());

        Thread sipContactsHandler = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < sipContactCursor.getCount(); i++) {
                    Contact contact = Compatibility.getContact(getContentResolver(), sipContactCursor, i);
                    contact.refresh(getContentResolver());
                    if (!isContactPresenceDisabled) {
                        searchFriendAndAddToContact(contact);
                    }
                    sipContactList.add(contact);
                }
                for (int i = 0; i < contactCursor.getCount(); i++) {// ------------
                    Contact contact = Compatibility.getContact(getContentResolver(), contactCursor, i);
                    for (Contact c : sipContactList) {
                        if (c.getID().equals(contact.getID())) {
                            contact = c;
                            break;
                        }
                    }
                    contactList.add(contact);
                }
            }
        });

        contactList = new ArrayList<Contact>();
        sipContactList = new ArrayList<Contact>();

        sipContactsHandler.start();
    }

    private void initInCallMenuLayout(boolean callTransfer) {
        selectMenu(FragmentsAvailable.DIALER);
        if (dialerFragment != null) {
            ((DialerFragment) dialerFragment).resetLayout(callTransfer);
        }
    }

    public void resetClassicMenuLayoutAndGoBackToCallIfStillRunning() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (dialerFragment != null) {
                    ((DialerFragment) dialerFragment).resetLayout(false);
                }

                if (LinphoneManager.isInstanciated() && LinphoneManager.getLc().getCallsNb() > 0) {
                    LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
                    if (call.getCurrentParamsCopy().getVideoEnabled()) {
                        startVideoActivity(call);
                    } else {
                        startIncallActivity(call);
                    }
                }
            }
        });
    }

    public FragmentsAvailable getCurrentFragment() {
        return currentFragment;
    }

    public ChatStorage getChatStorage() {
        if (chatStorage == null) {
            chatStorage = new ChatStorage(this);
        }
        return chatStorage;
    }

    public void addContact(String displayName, String sipUri) {
        if (getResources().getBoolean(R.bool.use_android_native_contact_edit_interface)) {
            Intent intent = Compatibility.prepareAddContactIntent(displayName, sipUri);
            startActivity(intent);
        } else {
            Bundle extras = new Bundle();
            extras.putSerializable("NewSipAdress", sipUri);
            extras.putSerializable("addnum", sipUri);
            changeCurrentFragment(FragmentsAvailable.EDIT_CONTACT, extras);
        }
    }

    public void editContact(Contact contact) {
        if (getResources().getBoolean(R.bool.use_android_native_contact_edit_interface)) {
            Intent intent = Compatibility.prepareEditContactIntent(Integer.parseInt(contact.getID()));
            startActivity(intent);
        } else {
            Bundle extras = new Bundle();
            extras.putSerializable("Contact", contact);
            changeCurrentFragment(FragmentsAvailable.EDIT_CONTACT, extras);
        }
    }

    public void editContact(Contact contact, String sipAddress) {
        if (getResources().getBoolean(R.bool.use_android_native_contact_edit_interface)) {
            Intent intent = Compatibility.prepareEditContactIntentWithSipAddress(Integer.parseInt(contact.getID()),
                    sipAddress);
            startActivity(intent);
        } else {
            Bundle extras = new Bundle();
            extras.putSerializable("Contact", contact);
            extras.putSerializable("NewSipAdress", sipAddress);
            changeCurrentFragment(FragmentsAvailable.EDIT_CONTACT, extras);
        }
    }

    public void exit() {
        refreshStatus(OnlineStatus.Offline);
        finish();
        stopService(new Intent(ACTION_MAIN).setClass(this, LinphoneService.class));
        if (InCallActivity2.isInstanciated()) {
            InCallActivity2.instance().finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_FIRST_USER && requestCode == SETTINGS_ACTIVITY) {
            if (data.getExtras().getBoolean("Exit", false)) {
                exit();
            } else {
                FragmentsAvailable newFragment = (FragmentsAvailable) data.getExtras()
                        .getSerializable("FragmentToDisplay");
                changeCurrentFragment(newFragment, null, true);
                selectMenu(newFragment);
            }
        } else if (requestCode == callActivity) {
            boolean callTransfer = data == null ? false : data.getBooleanExtra("Transfer", false);
            if (LinphoneManager.getLc().getCallsNb() > 0) {
                initInCallMenuLayout(callTransfer);
            } else {
                resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        // Remove to avoid duplication of the listeners
        LinphoneManager.removeListener(this);
        LinphoneManager.addListener(this);
        if (chatStorage != null) {
            chatStorage.close();
        }
        chatStorage = new ChatStorage(this);

        updateMissedChatCount();
        displayMissedCalls(LinphoneManager.getLc().getMissedCallsCount());

        if (LinphoneManager.getLc().getCalls().length > 0) {
            LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
            LinphoneCall.State callState = call.getState();
            if (callState == State.IncomingReceived) {
                startActivity(new Intent(this, IncomingCallActivity.class));
            }
        }

        refreshStatus(OnlineStatus.Online);
        findViewById(R.id.status).setVisibility(View.GONE);
        if (start2) {
            start = pref.getBoolean(getString(R.string.pref_call_phone_type), false);
            if (start) {
                resetSelection();
                dialer.setSelected(true);
                changeCurrentFragment(FragmentsAvailable.DIALER, null);
            }
        }
        start2 = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        refreshStatus(OnlineStatus.Away);
    }

    public void changeHistory(HistoryFragment chistory) {
        this.chistory = chistory;
    }

    public void changeContacts(ContactsFragment ccontacts) {
        this.ccontacts = ccontacts;
    }

    @Override
    protected void onDestroy() {
        LinphoneManager.removeListener(this);

        if (chatStorage != null) {
            chatStorage.close();
            chatStorage = null;
        }

        if (mOrientationHelper != null) {
            mOrientationHelper.disable();
            mOrientationHelper = null;
        }

        instance = null;
        if (receiver != null)
            unregisterReceiver(receiver);
        if (msg != null)
            msg.setMSG();
        if (app != null)
            app.setCallNum(null);
        super.onDestroy();
        unbindDrawables(findViewById(R.id.topLayout));
        System.gc();
    }

    @SuppressLint("NewApi")
    private void unbindDrawables(View view) {
        if (view != null && view.getBackground() != null) {
            view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle extras = intent.getExtras();
        if (extras != null && extras.getBoolean("GoToChat", false)) {
            LinphoneService.instance().removeMessageNotification();
            String sipUri = extras.getString("ChatContactSipUri");
            displayChat(sipUri);
        } else if (extras != null && extras.getBoolean("Notification", false)) {
            if (LinphoneManager.getLc().getCallsNb() > 0) {
                LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
                if (call.getCurrentParamsCopy().getVideoEnabled()) {
                    startVideoActivity(call);
                } else {
                    startIncallActivity(call);
                }
            }
        } else {
            if (dialerFragment != null) {
                // ((DialerFragment) dialerFragment).newOutgoingCall(intent);
            }
            if (LinphoneManager.getLc().getCalls().length > 0) {
                LinphoneCall calls[] = LinphoneManager.getLc().getCalls();
                if (calls.length > 0) {
                    LinphoneCall call = calls[0];

                    if (call != null && call.getState() != LinphoneCall.State.IncomingReceived) {
                        if (call.getCurrentParamsCopy().getVideoEnabled()) {
                            startVideoActivity(call);
                        } else {
                            startIncallActivity(call);
                        }
                    }
                }

                // If a call is ringing, start incomingcallactivity
                Collection<LinphoneCall.State> incoming = new ArrayList<LinphoneCall.State>();
                incoming.add(LinphoneCall.State.IncomingReceived);
                if (LinphoneUtils.getCallsInState(LinphoneManager.getLc(), incoming).size() > 0) {
                    if (InCallActivity.isInstanciated()) {
                        InCallActivity.instance().startIncomingCallActivity();
                    } else {
                        startActivity(new Intent(this, IncomingCallActivity.class));
                    }
                }
            }
        }
    }

    //yyppoption add
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        Log.v("yyppdebug", "yyppoption keyevent  000");

        return super.dispatchKeyEvent(event);

    }

    //yyppoption end

    //yyppoption  add   
    @SuppressLint("NewApi")
    private void initPopupWindow() {
        Log.v("yyppdebug", "yyppoption init 000");
        view = getLayoutInflater().inflate(R.layout.option_menu, null);
        pop = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setOutsideTouchable(true);

        // ??
        mlayout_setting = (LinearLayout) view.findViewById(R.id.option_menu_aaa);
        mlayout_about = (LinearLayout) view.findViewById(R.id.option_menu_bbb);
        mlayout_exit = (LinearLayout) view.findViewById(R.id.option_menu_ccc);

        mlayout_setting.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (pop.isShowing()) {
                    pop.dismiss();

                    isPopShowing = false;
                }
                //do somethiing
                LinphoneActivity.instance().changeCurrentFragment(FragmentsAvailable.TITTLE_SETTINGS, null);
                //-----------------

            }
        });

        mlayout_about.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            public void onClick(View v) {
                if (pop.isShowing()) {
                    pop.dismiss();
                    isPopShowing = false;

                }
                //do something...

                AlertDialog.Builder buildernew = new AlertDialog.Builder(LinphoneActivity.instance(),
                        AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                String tmpmsg = "?????????www.wecare200.com";
                buildernew.setIconAttribute(android.R.attr.alertDialogIcon);
                buildernew.setTitle("?");
                buildernew.setMessage(tmpmsg);

                buildernew.setNegativeButton("?", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                    }
                });

                buildernew.create().show();

                //---------------------------------------------------------

            }
        });

        mlayout_exit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (pop.isShowing()) {
                    pop.dismiss();
                    isPopShowing = false;
                }
                //do something...

                //LinphoneActivity.instance().exit();
                //----------------------------------
                startActivity(new Intent().setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));

            }
        });
    }
    //yyppoption end   

    @SuppressLint("NewApi")
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Log.v("LinphoneActiviey.class", "yypp exit wecareapp 000");

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //yyppoption add
            if ((statusFragment != null) && (event.getRepeatCount() < 1)) {
                if (pop.isShowing()) {
                    pop.dismiss();
                    isPopShowing = false;
                    return true;
                }
            }
            //yyppoption end
            if (currentFragment == FragmentsAvailable.DIALER) {
                //yyppexit  add
                /*
                Dialog dialog= new AlertDialog.Builder(this).setTitle("??????")  
                       .setIcon(android.R.drawable.ic_dialog_info)  
                       .setPositiveButton("", new DialogInterface.OnClickListener() {
                   @Override  
                   public void onClick(DialogInterface dialog, int which) {
                   // ???  
                    // System.exit(0);
                    LinphoneActivity.instance().exit();
                      //?
                       //startActivity(new Intent().setAction(Intent.ACTION_MAIN)
                        //.addCategory(Intent.CATEGORY_HOME));
                   }
                       })
                       .setNegativeButton("??", new DialogInterface.OnClickListener() {
                   @Override  
                   public void onClick(DialogInterface dialog, int which) {
                   // ???,??  
                    // System.exit(0);
                    //LinphoneActivity.instance().exit();
                      //?
                       startActivity(new Intent().setAction(Intent.ACTION_MAIN)
                           .addCategory(Intent.CATEGORY_HOME));        
                    
                   }  
                       }).show(); 
                    
                */
                //yyppexit end            
                //yyppexit 222 add
                /*
                    AlertDialog.Builder builder = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                    builder.setTitle("?")    //
                .setIcon(android.R.drawable.ic_dialog_info)    //icon
                .setCancelable(false)    //??back
                .setMessage("??-????")    //?
                //
                .setPositiveButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       //
                       dialog.dismiss();
                 // System.exit(0);
                 LinphoneActivity.instance().exit();
                   //?
                    //startActivity(new Intent().setAction(Intent.ACTION_MAIN)
                     //.addCategory(Intent.CATEGORY_HOME));                           
                    }
                })
                .setNeutralButton("?", new DialogInterface.OnClickListener() {                        
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       //
                       dialog.dismiss();
                            
                    }
                })
                .setNegativeButton("??", new DialogInterface.OnClickListener() {                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       //
                       dialog.dismiss();
                 // System.exit(0);
                 //LinphoneActivity.instance().exit();
                   //?
                    startActivity(new Intent().setAction(Intent.ACTION_MAIN)
                     .addCategory(Intent.CATEGORY_HOME));                          
                    }
                }).show();
                    //Dialog
                    //AlertDialog dlg = builder.create();
                    */

                //yyppexit 222 end            

                //yyppexit 333 add

                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    //Log.v("LinphoneActiviey.class", "yypp exit wecareapp 222");
                    Toast.makeText(getApplicationContext(), "??", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                    //changeCurrentFragment(FragmentsAvailable.DIALER, null);
                    return true;
                } else {
                    //Log.v("LinphoneActiviey.class", "yypp exit wecareapp 333");
                    //finish();
                    //System.exit(0);

                    //?
                    LinphoneActivity.instance().exit();
                    //?
                    //this.startActivity(new Intent().setAction(Intent.ACTION_MAIN)
                    //.addCategory(Intent.CATEGORY_HOME));

                    return true;
                }

                //yyppexit 333 end                  

                /*
                if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) {
                       
                   Log.v("LinphoneActiviey.class", "yypp exit wecareapp 444");
                   return true;
                       
                       
                }
                */
                //???????
            } else if (!isTablet()) {
                int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
                if (backStackEntryCount <= 1) {
                    showStatusBar();
                }

                if (currentFragment == FragmentsAvailable.SETTINGS) {
                    showStatusBar();
                    reloadConfig();
                    updateAnimationsState();
                }
                if (currentFragment == FragmentsAvailable.SETTINGS || currentFragment == FragmentsAvailable.CHATLIST
                        || currentFragment == FragmentsAvailable.HISTORY
                        || currentFragment == FragmentsAvailable.CONTACTS) {
                    changeCurrentFragment(FragmentsAvailable.DIALER, null);
                    return true;
                } else if (currentFragment == FragmentsAvailable.SET_CHONGZHI
                        || currentFragment == FragmentsAvailable.SET_MES
                        || currentFragment == FragmentsAvailable.SET_QUERY) {
                    if (tableindex == 1)
                        changeCurrentFragment(FragmentsAvailable.SETTINGS, null);
                    else
                        changeCurrentFragment(FragmentsAvailable.CHATLIST, null);
                    //               resetSelection();
                    //               settings.setSelected(true);
                    return true;
                } else if (currentFragment == FragmentsAvailable.SET_CHONGZHIKA
                        || currentFragment == FragmentsAvailable.SET_ALIPAY) {
                    changeCurrentFragment(FragmentsAvailable.SET_CHONGZHI, new Bundle());
                    //               resetSelection();
                    //               settings.setSelected(true);
                    return true;
                }
            }
        } else if (keyCode == KeyEvent.KEYCODE_MENU && statusFragment != null) {

            Log.v("yyppdebug", "yyppoption keyevent  menu 000");
            if (event.getRepeatCount() < 1) {
                // statusFragment.openOrCloseStatusBar();
                Log.v("yyppdebug", "yyppoption keyevent  menu 111");
                //yyppoption add
                if (!pop.isShowing()) {
                    Log.v("yyppdebug", "yyppoption keyevent  menu 222");
                    //pop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                    pop.showAtLocation(findViewById(R.id.menu), Gravity.BOTTOM, 0, 0);
                    isPopShowing = true;
                } else {
                    Log.v("yyppdebug", "yyppoption keyevent  menu 333");
                    pop.dismiss();
                    isPopShowing = false;
                }
                return true;

                //yyppoption end

            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onEcCalibrationStatus(EcCalibratorStatus status, int delayMs) {

    }

    public void startEcCalibration() {
        try {
            LinphoneManager.getInstance().startEcCalibration(this);
        } catch (LinphoneCoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @SuppressLint("ValidFragment")
    class AcceptNewFriendDialog extends DialogFragment {
        private Contact contact;
        private String sipUri;

        public AcceptNewFriendDialog(Contact c, String a) {
            contact = c;
            sipUri = a;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.new_friend_request_dialog, container);
            getDialog().setTitle(R.string.linphone_friend_new_request_title);

            Button yes = (Button) view.findViewById(R.id.yes);
            yes.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    acceptNewFriend(contact, sipUri, true);
                }
            });

            Button no = (Button) view.findViewById(R.id.no);
            no.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    acceptNewFriend(contact, sipUri, false);
                }
            });

            return view;
        }
    }

    public class SoChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Common.SOCHANGE_ACTION)) {
                app.setList();
            }
        }

    }

    public class ContactsObServer extends ContentObserver {

        public ContactsObServer(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {

            new Thread() {
                public void run() {
                    prepareContactsInBackground();
                }
            }.start();
            new GetContact().start();
        }
    }

    class GetContact extends Thread {
        @Override
        public void run() {
            if (ContactDB.Instance().getIsUpdate() == ContactDB.SELETE) {
                ContactDB.Instance().setAllNull();
                ContactDB.Instance().setContact(0, 50);
            } else {
                if (ContactDB.Instance().getIsUpdate() == ContactDB.INSERT) {
                    ContactDB.Instance().insertTopOne(getApplicationContext());
                }
                ContactDB.Instance().setIsUpdate(ContactDB.SELETE);
            }
        }
    }

    public class CallLogObServer extends ContentObserver {
        private Handler handler;

        public CallLogObServer(Handler handler) {
            super(handler);
            this.handler = handler;
        }

        public void onChange(boolean selfChange) {
            handler.post(new Runnable() {

                @Override
                public void run() {
                    CallsLogUtils.instance().setCallsLogs(db.getAllCallsLog());
                    if (currentFragment == FragmentsAvailable.HISTORY) {
                        //                  chistory.changeData();
                    }
                }
            });
        };
    }

    @Override
    public void onClick(String info) {
        addnum = info;

    }

}

interface ContactPicked {
    void setAddresGoToDialerAndCall(String number, String name, Uri photo);

    void goToDialer();
}