public class ChatActivity extends BaseMessageActivity implements OnItemClickListener {

    private static final Logger logger = Logger.getLogger(ChatActivity.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivitiesManager.initChatActivity(this);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    // 监听返回键
    @Override
    public void onBackPressed() {
        if (mLayoutMessagePlusBar.isShown()) {
            hidePlusBar();
        }
        else if (mInputView.isShown()) {
            mIbTextDitorKeyBoard.setVisibility(View.GONE);
            mIbTextDitorEmote.setVisibility(View.VISIBLE);
            mInputView.setVisibility(View.GONE);
        }
        else if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
            mIbTextDitorKeyBoard.setVisibility(View.VISIBLE);
            mIbTextDitorEmote.setVisibility(View.GONE);
            hideKeyBoard();
        }
        else if (mLayoutScroll.getCurScreen() == 1) {
            mLayoutScroll.snapToScreen(0);
        }
        else {
            finish();
        }
    }

    @Override
    public void finish() {
        ActivitiesManager.removeChatActivity();

        if (null != mDBOperate) {// 关闭数据库连接
            mDBOperate.close();
            mDBOperate = null;
        }
        mRecordThread = null;
        super.finish();
    }

    @Override
    protected void initViews() {
        mClvList = (MultiListView) findViewById(R.id.chat_clv_list);
        mLayoutScroll = (ScrollLayout) findViewById(R.id.chat_slayout_scroll);
        mLayoutRounds = (LinearLayout) findViewById(R.id.chat_layout_rounds);
        mInputView = (EmoteInputView) findViewById(R.id.chat_eiv_inputview);

        mIbTextDitorPlus = (ImageButton) findViewById(R.id.chat_textditor_ib_plus);
        mIbTextDitorKeyBoard = (ImageButton) findViewById(R.id.chat_textditor_ib_keyboard);
        mIbTextDitorEmote = (ImageButton) findViewById(R.id.chat_textditor_ib_emote);
        mIvTextDitorAudio = (ImageView) findViewById(R.id.chat_textditor_iv_audio);
        mBtnTextDitorSend = (Button) findViewById(R.id.chat_textditor_btn_send);
        mEetTextDitorEditer = (EmoticonsEditText) findViewById(R.id.chat_textditor_eet_editer);

        mIbAudioDitorPlus = (ImageButton) findViewById(R.id.chat_audioditor_ib_plus);
        mIbAudioDitorKeyBoard = (ImageButton) findViewById(R.id.chat_audioditor_ib_keyboard);
        mIvAudioDitorAudioBtn = (ImageView) findViewById(R.id.chat_audioditor_iv_audiobtn);

        mLayoutFullScreenMask = (LinearLayout) findViewById(R.id.fullscreen_mask);
        mLayoutMessagePlusBar = (LinearLayout) findViewById(R.id.message_plus_layout_bar);
        mLayoutMessagePlusPicture = (LinearLayout) findViewById(R.id.message_plus_layout_picture);
        mLayoutMessagePlusCamera = (LinearLayout) findViewById(R.id.message_plus_layout_camera);
        mLayoutMessagePlusFile = (LinearLayout) findViewById(R.id.message_plus_layout_file);
    }

    @Override
    protected void initEvents() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        mClvList.setStackFromBottom(true);
        mClvList.setFastScrollEnabled(true);

        mLayoutScroll.setOnScrollToScreen(this);
        mIbTextDitorPlus.setOnClickListener(this);
        mIbTextDitorEmote.setOnClickListener(this);
        mIbTextDitorKeyBoard.setOnClickListener(this);
        mBtnTextDitorSend.setOnClickListener(this);
        mIvTextDitorAudio.setOnClickListener(this);
        mEetTextDitorEditer.addTextChangedListener(this);
        mEetTextDitorEditer.setOnTouchListener(this);
        mIbAudioDitorPlus.setOnClickListener(this);
        mIbAudioDitorKeyBoard.setOnClickListener(this);
        mIvAudioDitorAudioBtn.setOnTouchListener(this);
        mIvAudioDitorAudioBtn.setOnLongClickListener(this);
        mLayoutFullScreenMask.setOnTouchListener(this);
        mLayoutMessagePlusPicture.setOnClickListener(this);
        mLayoutMessagePlusCamera.setOnClickListener(this);
        mLayoutMessagePlusFile.setOnClickListener(this);

    }

    private void init() {
        mID = SessionUtils.getLocalUserID();
        mNickName = SessionUtils.getNickname();
        mIMEI = SessionUtils.getIMEI();
        mChatUser = getIntent().getParcelableExtra(Users.ENTITY_PEOPLE);
        mDBOperate = new SqlDBOperate(this);
        mSenderID = mDBOperate.getIDByIMEI(mChatUser.getIMEI());

        mMessagesList = new ArrayList<Message>();
        mMessagesList = mDBOperate.getScrollMessageOfChattingInfo(0, 5, mSenderID, mID);

        mInputView.setEditText(mEetTextDitorEditer);
        setTitle(mChatUser.getNickname());
        initRounds();
        initfolder();

        mAdapter = new ChatAdapter(ChatActivity.this, mMessagesList);
        mAdapter.setListView(mClvList);
        mAdapter.setChatUser(mChatUser);
        mClvList.setAdapter(mAdapter);        
        mClvList.setOnItemClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_chat, menu);
        return true;
    }

    // actionBar的监听
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_userinfo:
                Intent intent = new Intent(ChatActivity.this, OtherProfileActivity.class);
                intent.putExtra(Users.ENTITY_PEOPLE, mChatUser);
                startActivity(intent);
                break;
            case android.R.id.home:
                finish();
                break;

            default:
                break;
        }
        return true;
    }

    @Override
    public void doAction(int whichScreen) {
        switch (whichScreen) {
            case 0:
                ((ImageView) mLayoutRounds.getChildAt(0)).setImageBitmap(mRoundsSelected);
                ((ImageView) mLayoutRounds.getChildAt(1)).setImageBitmap(mRoundsNormal);
                break;

            case 1:
                ((ImageView) mLayoutRounds.getChildAt(1)).setImageBitmap(mRoundsSelected);
                ((ImageView) mLayoutRounds.getChildAt(0)).setImageBitmap(mRoundsNormal);
                mIbTextDitorKeyBoard.setVisibility(View.GONE);
                mIbTextDitorEmote.setVisibility(View.VISIBLE);
                if (mInputView.isShown()) {
                    mInputView.setVisibility(View.GONE);
                }
                hideKeyBoard();
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                if (recordState == RECORD_OFF) {
                    switch (v.getId()) {
                        case R.id.chat_textditor_eet_editer:
                            mIbTextDitorKeyBoard.setVisibility(View.GONE);
                            mIbTextDitorEmote.setVisibility(View.VISIBLE);
                            showKeyBoard();
                            break;

                        case R.id.fullscreen_mask:
                            hidePlusBar();
                            break;

                        case R.id.chat_audioditor_iv_audiobtn:
                            downY = event.getY();
                            break;
                    }
                }
                break;

            case MotionEvent.ACTION_MOVE:
                if (recordState == RECORD_ON) {
                    float moveY = event.getY();
                    if (moveY - downY < -50) {
                        isMove = true;
                        showVoiceDialog(1);
                    }
                    else if (moveY - downY < -20) {
                        isMove = false;
                        showVoiceDialog(0);
                    }
                }
                break;

            case MotionEvent.ACTION_UP:
                if (recordState == RECORD_ON) {

                    stopRecord();

                    if (mRecordDialog.isShowing()) {
                        mRecordDialog.dismiss();
                    }

                    if (!isMove) {
                        if (recodeTime < MIN_RECORD_TIME) {
                            showWarnToast(R.string.chat_toast_record_shorttime);
                        }
                        else {
                            mVoicePath = mAudioRecorder.getVoicePath();
                            sendMessage(mVoicePath, CONTENT_TYPE.VOICE);
                            refreshAdapter();
                        }
                    }

                    isMove = false;
                }

                if (mAudioRecorder != null)
                    mAudioRecorder = null;
                mLayoutScroll.requestDisallowInterceptTouchEvent(false); // 恢复监测滚动事件
                break;

        }

        return false;
    }

    @Override
    public boolean onLongClick(View v) {
        mLayoutScroll.requestDisallowInterceptTouchEvent(true); // 屏蔽滚动事件
        startRecord();
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chat_textditor_ib_plus:
                if (!mLayoutMessagePlusBar.isShown()) {
                    showPlusBar();
                }
                break;

            case R.id.chat_textditor_ib_emote:
                mIbTextDitorKeyBoard.setVisibility(View.VISIBLE);
                mIbTextDitorEmote.setVisibility(View.GONE);
                mEetTextDitorEditer.requestFocus();
                if (mInputView.isShown()) {
                    hideKeyBoard();
                }
                else {
                    hideKeyBoard();
                    mInputView.setVisibility(View.VISIBLE);
                }
                break;

            case R.id.chat_textditor_ib_keyboard:
                mIbTextDitorKeyBoard.setVisibility(View.GONE);
                mIbTextDitorEmote.setVisibility(View.VISIBLE);
                showKeyBoard();
                break;

            case R.id.chat_textditor_btn_send:
                String content = mEetTextDitorEditer.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    mEetTextDitorEditer.setText(null);
                    sendMessage(content, CONTENT_TYPE.TEXT);
                    refreshAdapter();
                }
                break;

            case R.id.chat_textditor_iv_audio:
                mLayoutScroll.snapToScreen(1);
                break;

            case R.id.chat_audioditor_ib_plus:
                if (!mLayoutMessagePlusBar.isShown()) {
                    showPlusBar();
                }
                break;

            case R.id.chat_audioditor_ib_keyboard:
                mLayoutScroll.snapToScreen(0);
                break;

            case R.id.message_plus_layout_picture:
                ImageUtils.selectPhoto(ChatActivity.this);
                hidePlusBar();
                break;

            case R.id.message_plus_layout_camera:
                mCameraImagePath = ImageUtils.takePicture(ChatActivity.this);
                hidePlusBar();
                break;

            case R.id.message_plus_layout_file:
                showFileChooser();
                hidePlusBar();
                break;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)) {
            mIvTextDitorAudio.setVisibility(View.VISIBLE);
            mBtnTextDitorSend.setVisibility(View.GONE);
        }
        else {
            mIvTextDitorAudio.setVisibility(View.GONE);
            mBtnTextDitorSend.setVisibility(View.VISIBLE);
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.INTENT_REQUEST_CODE_ALBUM:
                if (data == null) {
                    return;
                }
                if (resultCode == RESULT_OK) {
                    if (data.getData() == null) {
                        return;
                    }
                    if (!FileUtils.isSdcardExist()) {
                        showShortToast(R.string.toast_sdcard_unavailable);
                        return;
                    }
                    Uri uri = data.getData();
                    String[] proj = { MediaStore.Images.Media.DATA };
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    if (cursor != null) {
                        int column_index = cursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                            
                            String path = cursor.getString(column_index);
                            
                            mCameraImagePath = path;
                            Bitmap bitmap = ImageUtils.getBitmapFromPath(path);
                            if (ImageUtils.bitmapIsLarge(bitmap)) {
                                ImageUtils.cropPhoto(this, this, path);
                            }
                            else {
                                if (path != null) {
                                    ImageUtils.createThumbnail(this, path, THUMBNAIL_PATH
                                            + File.separator);
                                    sendMessage(path, CONTENT_TYPE.IMAGE);
                                    refreshAdapter();
                                }
                            }
                        }
                    }
                }
                break;

            case ImageUtils.INTENT_REQUEST_CODE_CAMERA:
                if (resultCode == RESULT_OK) {
                    if (mCameraImagePath != null) {
                        mCameraImagePath = ImageUtils.savePhotoToSDCard(
                                ImageUtils.CompressionPhoto(mScreenWidth, mCameraImagePath, 2),
                                BaseApplication.CAMERA_IMAGE_PATH, null);
                        ImageUtils.fliterPhoto(this, this, mCameraImagePath);
                    }
                }
                break;

            case ImageUtils.INTENT_REQUEST_CODE_CROP:
                if (resultCode == RESULT_OK) {
                    String path = data.getStringExtra("path");
                    mCameraImagePath = path;
                    if (path != null) {
                        ImageUtils.createThumbnail(this, path, THUMBNAIL_PATH + File.separator);
                        sendMessage(path, CONTENT_TYPE.IMAGE);
                        refreshAdapter();
                    }
                }
                break;

            case ImageUtils.INTENT_REQUEST_CODE_FLITER:
                if (resultCode == RESULT_OK) {
                    String path = data.getStringExtra("path");
                    if (path != null) {
                        ImageUtils.createThumbnail(this, path, THUMBNAIL_PATH + File.separator);
                        sendMessage(path, CONTENT_TYPE.IMAGE);
                        refreshAdapter();
                    }
                }
                break;

            case FILE_SELECT_CODE: {
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    String path = uri.getPath();

                    if (path != null) {
                        sendFilePath = path;
                        sendMessage(sendFilePath, CONTENT_TYPE.FILE);
                        refreshAdapter();
                    }
                }
            }
                break;
        }
    }

    public boolean isThisActivityMsg(Message msg) {
        String senderIMEI = msg.getSenderIMEI();
        if (mChatUser.getIMEI().equals(senderIMEI)) {
            mMessagesList.add(msg);
            return true;
        }
        return false;

    }

    public void processMessage(android.os.Message pMsg) {
        switch (pMsg.what) {
            case IPMSGConst.IPMSG_SENDMSG:
                if (isThisActivityMsg((Message) pMsg.obj)) {
                    handler.sendEmptyMessage(1);
                }
                break;

            case IPMSGConst.IPMSG_CONFIRM_IMAGE_DATA: { // 图片开始发送
                logger.d("接收方确认图片请求,发送的文件为" + mCameraImagePath);
                tcpClient = TcpClient.getInstance(ChatActivity.this);
                tcpClient.startSend();
                tcpClient.sendFile(mCameraImagePath, mChatUser.getIpaddress(),
                        Message.CONTENT_TYPE.IMAGE);
            }
                break;

            case IPMSGConst.IPMSG_CONFIRM_VOICE_DATA: { // 语音开始发送
                logger.d("接收方确认语音请求,发送的文件为" + mVoicePath);
                tcpClient = TcpClient.getInstance(ChatActivity.this);
                tcpClient.startSend();
                if (FileUtils.isFileExists(mVoicePath))
                    tcpClient.sendFile(mVoicePath, mChatUser.getIpaddress(),
                            Message.CONTENT_TYPE.VOICE);
            }
                break;

            case IPMSGConst.IPMSG_CONFIRM_FILE_DATA: { // 文件开始发送
                logger.d("接收方确认文件请求,发送的文件为" + sendFilePath);
                tcpClient = TcpClient.getInstance(ChatActivity.this);
                tcpClient.startSend();
                if (FileUtils.isFileExists(sendFilePath))
                    tcpClient.sendFile(sendFilePath, mChatUser.getIpaddress(),
                            Message.CONTENT_TYPE.FILE);
            }
                break;

        }
        // End of switch
    }

    private void startRecord() {
        recordState = RECORD_ON;
        RECORD_FILENAME = System.currentTimeMillis()
                + hillfly.wifichat.util.TextUtils.getRandomNumStr(3);

        mAudioRecorder = new AudioRecorderUtils();
        mAudioRecorder.setVoicePath(VOICE_PATH, RECORD_FILENAME);
        mRecordThread = new Thread(recordThread);

        try {
            mAudioRecorder.start();
            mRecordThread.start();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        showVoiceDialog(0);

    }

    private void stopRecord() {
        recordState = RECORD_OFF;
        try {
            mRecordThread.interrupt();
            mRecordThread = null;
            mAudioRecorder.stop();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        voiceValue = 0.0;
    }

    // 录音线程
    private Runnable recordThread = new Runnable() {

        @Override
        public void run() {
            recodeTime = 0.0f;
            while (recordState == RECORD_ON) {
                // 限制录音时长
                // if (recodeTime >= MAX_RECORD_TIME && MAX_RECORD_TIME != 0) {
                // imgHandle.sendEmptyMessage(0);
                // } else
                {
                    try {
                        Thread.sleep(200);
                        recodeTime += 0.2;
                        // 获取音量，更新dialog
                        if (!isMove) {
                            voiceValue = mAudioRecorder.getAmplitude();
                            handler.sendEmptyMessage(0);
                        }
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    };

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0: // 更新录音音量
                    setDialogImage();
                    break;

                case 1:
                    refreshAdapter(); // 更新消息显示
                    break;

                default:
                    break;
            }

        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub
        Message msg = mMessagesList.get((int) id);
        switch (msg.getContentType()) {
            case IMAGE:
                Intent imgIntent = new Intent(mContext, ImageBrowserActivity.class);
                imgIntent
                        .putExtra(ImageBrowserActivity.IMAGE_TYPE, ImageBrowserActivity.TYPE_PHOTO);
                imgIntent.putExtra(ImageBrowserActivity.PATH, msg.getMsgContent());
                startActivity(imgIntent);
                overridePendingTransition(R.anim.zoom_enter, 0);

                break;

            case VOICE:
                // 播放录音
                final ImageView imgView = (ImageView) view
                        .findViewById(R.id.voice_message_iv_msgimage);
                if (!isPlay) {
                    mMediaPlayer = new MediaPlayer();
                    String filePath = msg.getMsgContent();
                    try {
                        mMediaPlayer.setDataSource(filePath);
                        mMediaPlayer.prepare();
                        imgView.setImageResource(R.drawable.voicerecord_stop);
                        isPlay = true;
                        mMediaPlayer.start();
                        // 设置播放结束时监听
                        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                if (isPlay) {
                                    imgView.setImageResource(R.drawable.voicerecord_right);
                                    isPlay = false;
                                    mMediaPlayer.stop();
                                    mMediaPlayer.release();
                                }
                            }
                        });
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.stop();
                        mMediaPlayer.release();
                        isPlay = false;
                    }
                    else {
                        isPlay = false;
                        mMediaPlayer.release();
                    }
                    imgView.setImageResource(R.drawable.voicerecord_right);
                }

                break;

            case FILE:
                Intent fileIntent = new Intent();
                fileIntent.setType("*/*");
                fileIntent.setData(Uri.parse("file://"
                        + FileUtils.getPathByFullPath(msg.getMsgContent())));
                mContext.startActivity(fileIntent);
                break;

            default:
                break;

        }

    }

} public class ActivitiesManager {
    private static Stack<BaseActivity> queue;
    private static UDPMessageListener mListener;
    private static ChatActivity mChatActivity;

    public static void init() {
        queue = new Stack<BaseActivity>();
    }

    public static void addActivity(BaseActivity activity) {
        queue.add(activity);
    }

    public static void finishActivity(BaseActivity activity) {
        if (activity != null) {
            queue.remove(activity);
        }
    }

    public static void finishAllActivities(Context context) {
        mListener = UDPMessageListener.getInstance(context);
        mListener.notifyOffline();
        mListener.stopUDPSocketThread();
        mListener = null;
        for (BaseActivity activity : queue) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
        queue.clear();
    }

    public static int getActivitiesNum() {
        if (!queue.isEmpty()) {
            return queue.size();
        }
        return 0;
    }

    public static BaseActivity getCurrentActivity() {
        if (!queue.isEmpty()) {
            return queue.lastElement();
        }
        return null;
    }

    public static void initChatActivity(ChatActivity pActivity) {
        mChatActivity = pActivity;
    }

    public static void removeChatActivity() {
        mChatActivity = null;
    }

    public static ChatActivity getChatActivity() {
        return mChatActivity;
    }

} public class BaseApplication extends Application {
    
    public static boolean isDebugmode = false;
    private boolean isPrintLog = true;
    private int logLevel = Log.DEBUG;

    /** 静音、震动默认开关 **/
    private static boolean isSlient = false;
    private static boolean isVIBRATE = true;

    /** 新消息提醒 **/
    private static int notiSoundPoolID;
    private static SoundPool notiMediaplayer;
    private static Vibrator notiVibrator;

    /** 缓存 **/
    private Map<String, SoftReference<Bitmap>> mAvatarCache;

    public static HashMap<String, FileState> sendFileStates;
    public static HashMap<String, FileState> recieveFileStates;

    /** 本地图像、缩略图、声音、文件存储路径 **/
    public static String IMAG_PATH;
    public static String THUMBNAIL_PATH;
    public static String VOICE_PATH;
    public static String FILE_PATH;
    public static String SAVE_PATH;
    public static String CAMERA_IMAGE_PATH;

    /** mEmoticons 表情 **/
    public static Map<String, Integer> mEmoticonsId;
    public static List<String> mEmoticons;
    public static List<String> mEmoticons_Zem;

    private static BaseApplication instance;
    private static Logger logger;

    /**
     * <p>
     * 获取BaseApplication实例
     * <p>
     * 单例模式，返回唯一实例
     * 
     * @return instance
     */
    public static BaseApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (instance == null) {
            instance = this;
        }

        sendFileStates = new HashMap<String, FileState>();
        recieveFileStates = new HashMap<String, FileState>();
        mAvatarCache = new HashMap<String, SoftReference<Bitmap>>();

        ActivitiesManager.init(); // 初始化活动管理器
        logger = Logger.initLogger(instance, isPrintLog, logLevel); // 初始化日志

        initEmoticons();
        initNotification();
        initFolder();

    }

    private void initEmoticons() {
        mEmoticonsId = new HashMap<String, Integer>();
        mEmoticons = new ArrayList<String>();
        mEmoticons_Zem = new ArrayList<String>();

        // 预载表情
        for (int i = 1; i < 64; i++) {
            String emoticonsName = "[zem" + i + "]";
            int emoticonsId = getResources().getIdentifier("zem" + i, "drawable", getPackageName());
            mEmoticons.add(emoticonsName);
            mEmoticons_Zem.add(emoticonsName);
            mEmoticonsId.put(emoticonsName, emoticonsId);
        }
    }

    private void initNotification() {
        notiMediaplayer = new SoundPool(3, AudioManager.STREAM_SYSTEM, 5);
        notiSoundPoolID = notiMediaplayer.load(this, R.raw.crystalring, 1);
        notiVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        logger.e("onLowMemory");
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        logger.e("onTerminate");
    }

    // 函数创建文件存储目录
    private void initFolder() {
        if (null == IMAG_PATH) {
            SAVE_PATH = FileUtils.getSDPath();// 获取SD卡的根目录路径,如果不存在就返回Null
            if (null == SAVE_PATH) {
                SAVE_PATH = instance.getFilesDir().toString();// 获取内置存储区目录
            }
            SAVE_PATH += File.separator + instance.getString(R.string.app_name);
            IMAG_PATH = SAVE_PATH + File.separator + "image";
            THUMBNAIL_PATH = SAVE_PATH + File.separator + "thumbnail";
            VOICE_PATH = SAVE_PATH + File.separator + "voice";
            FILE_PATH = SAVE_PATH + File.separator + "file";
            CAMERA_IMAGE_PATH = IMAG_PATH + File.separator;
            if (!FileUtils.isFileExists(IMAG_PATH))
                FileUtils.createDirFile(BaseApplication.IMAG_PATH);
            if (!FileUtils.isFileExists(THUMBNAIL_PATH))
                FileUtils.createDirFile(BaseApplication.THUMBNAIL_PATH);
            if (!FileUtils.isFileExists(VOICE_PATH))
                FileUtils.createDirFile(BaseApplication.VOICE_PATH);
            if (!FileUtils.isFileExists(FILE_PATH))
                FileUtils.createDirFile(BaseApplication.FILE_PATH);

        }
    }

    public void addAvatarCache(String paramAvatarName, Bitmap bitmap) {
        mAvatarCache.put(paramAvatarName, new SoftReference<Bitmap>(bitmap));
    }

    public Reference<Bitmap> getAvatarCache(String paramAvatarName) {
        return mAvatarCache.get(paramAvatarName);
    }

    public void removeAvatarCache(String paramAvatarName) {
        mAvatarCache.remove(paramAvatarName);
    }

    public Map<String, SoftReference<Bitmap>> getAvatarCache() {
        return mAvatarCache;
    }

    /* 设置声音提醒 */
    public static boolean getSoundFlag() {
        return !isSlient;
    }

    public static void setSoundFlag(boolean pIsSlient) {
        isSlient = pIsSlient;
    }

    /* 设置震动提醒 */
    public static boolean getVibrateFlag() {
        return isVIBRATE;
    }

    public static void setVibrateFlag(boolean pIsvibrate) {
        isVIBRATE = pIsvibrate;
    }

    /**
     * 新消息提醒 - 声音提醒、振动提醒
     */
    public static void playNotification() {
        if (!isSlient) {
            notiMediaplayer.play(notiSoundPoolID, 1, 1, 0, 0, 1);
        }
        if (isVIBRATE) {
            notiVibrator.vibrate(200);
        }

    }
} public class TcpService implements Runnable {
    private static final Logger logger = Logger.getLogger(TcpService.class);

    private ServerSocket serviceSocket;
    private boolean SCAN_FLAG = false; // 接收扫描标识
    private Thread mThread;
    ArrayList<FileState> receivedFileNames;
    ArrayList<SaveFileToDisk> saveFileToDisks;
    private static Handler mHandler;
    private String filePath = null; // 存放接收文件的路径

    private static TcpService instance; // 唯一实例

    private boolean IS_THREAD_STOP = false; // 是否线程开始标志

    private TcpService() {
        try {
            serviceSocket = new ServerSocket(Constant.TCP_SERVER_RECEIVE_PORT);
            saveFileToDisks = new ArrayList<TcpService.SaveFileToDisk>();
            logger.d("建立监听服务器ServerSocket成功");
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            logger.d("建立监听服务器ServerSocket失败");
            e.printStackTrace();
        }
        mThread = new Thread(this);
    }

    /**
     * <p>
     * 获取TcpService实例
     * <p>
     * 单例模式，返回唯一实例
     */
    public static TcpService getInstance(Context context) {
        if (instance == null) {
            instance = new TcpService();
        }
        return instance;
    }

    public static void setHandler(Handler paramHandler) {
        mHandler = paramHandler;
    }

    public void setSavePath(String fileSavePath) {
        logger.d("设置存储路径成功,路径为" + fileSavePath);
        this.filePath = fileSavePath;
        // REV_FLAG=true;
    }

    public TcpService(Context context) {
        this();
    }

    private void scan_recv() {
        try {
            Socket socket = serviceSocket.accept(); // 接收UDP数据报
            // socket.setSoTimeout(5000); // 设置掉线时间
            logger.d("客户端连接成功");

            SaveFileToDisk fileToDisk = new SaveFileToDisk(socket, filePath);
            fileToDisk.start();

        }
        catch (IOException e) {
            e.printStackTrace();
            logger.d("客户端连接失败");
            SCAN_FLAG = false;
        }
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        logger.d("TCP_Service线程开启");
        while (!IS_THREAD_STOP) {
            if (SCAN_FLAG) {
                scan_recv();

            }
        }
    }

    public void release() {
        if (null != serviceSocket && !serviceSocket.isClosed())
            try {
                serviceSocket.close();
                serviceSocket = null;
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        while (SCAN_FLAG == true)
            ;// 直到SCAN_FLAG为false的时候退出循环
        SCAN_FLAG = false;
        IS_THREAD_STOP = true;
    }

    public void startReceive() {
        SCAN_FLAG = true; // 使能扫描接收标识
        if (!mThread.isAlive())
            mThread.start(); // 开启线程
    }

    public void startReceive(ArrayList<FileState> receivedFileNames) {
        SCAN_FLAG = true; // 使能扫描接收标识
        if (!mThread.isAlive())
            mThread.start(); // 开启线程
        this.receivedFileNames = receivedFileNames;
    }

    public void stopReceive() {
        while (SCAN_FLAG == true)
            ;
        SCAN_FLAG = false; // 失能扫描接收标识
    }

    public class SaveFileToDisk extends Thread {
        private boolean SCAN_RECIEVE = true;
        private InputStream input = null;
        private DataInputStream dataInput;
        private byte[] mBuffer = new byte[Constant.READ_BUFFER_SIZE];// 声明接收数组
        private String savePath;
        private String type[] = { "TEXT", "IMAGE", "FILE", "VOICE" };

        public SaveFileToDisk(Socket socket) {
            try {
                input = socket.getInputStream();
                dataInput = new DataInputStream(input);
                logger.d("获取网络输入流成功");
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                logger.d("获取网络输入流失败");
                SCAN_RECIEVE = false;
                e.printStackTrace();
            }
        }

        public SaveFileToDisk(Socket socket, String savePath) {
            this(socket);
            this.savePath = savePath;
        }

        public void recieveFile() {
            int readSize = 0;
            FileOutputStream fileOutputStream = null;
            BufferedOutputStream bufferOutput = null;
            String strFiledata;
            String[] strData = null;
            String fileSavePath;

            try {
                strFiledata = dataInput.readUTF().toString();
                strData = strFiledata.split("!");
                long length = Long.parseLong(strData[1]);// 文件大小

                logger.d("传输文件类型:" + strData[3]);
                fileSavePath = savePath + File.separator + strData[2] + File.separator + strData[0];
                fileOutputStream = new FileOutputStream(new File(fileSavePath));// 创建文件流
                logger.d("文件存储路径:" + fileSavePath);
                FileState fileState = new FileState(length, 0, fileSavePath, getType(strData[3]));
                BaseApplication.recieveFileStates.put(fileSavePath, fileState);
                FileState fs = BaseApplication.recieveFileStates.get(fileSavePath);
                bufferOutput = new BufferedOutputStream(fileOutputStream);// 创建带缓冲区的文件流
                long currentLength = 0;
                int count = 0;
                while (-1 != (readSize = dataInput.read(mBuffer))) {
                    bufferOutput.write(mBuffer, 0, readSize);
                    currentLength += readSize;
                    count++;
                    if (count % 10 == 0) {
                        //long Length = currentLength - lastLength;
                        fs.currentSize = currentLength;
                        fs.percent = (int) ((float) currentLength / (float) length * 100);

                        switch (fs.type) {
                            case IMAGE:
                                break;

                            case VOICE:
                                break;

                            case FILE:
                                android.os.Message msg = mHandler.obtainMessage();
                                msg.obj = fs;
                                msg.sendToTarget();
                                break;

                            default:
                                break;
                        }
                    }
                }

                // 将byte数组的数据写进指定路径
                bufferOutput.flush();

                input.close();
                dataInput.close();
                bufferOutput.close();
                fileOutputStream.close();

                switch (fs.type) {
                    case IMAGE:
                        break;

                    case VOICE:
                        break;

                    case FILE:
                        android.os.Message msg = mHandler.obtainMessage();
                        fs.percent = 100;
                        msg.obj = fs;
                        msg.sendToTarget();
                        break;

                    default:
                        break;
                }

                BaseApplication.recieveFileStates.remove(fs.fileName);
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                logger.d("写入文件失败");
                e.printStackTrace();
            }
        }

        private Message.CONTENT_TYPE getType(String string) {
            if (string.equals(type[0]))
                return CONTENT_TYPE.TEXT;
            else if (string.equals(type[1]))
                return CONTENT_TYPE.IMAGE;
            else if (string.equals(type[2]))
                return CONTENT_TYPE.FILE;
            else if (string.equals(type[3]))
                return CONTENT_TYPE.VOICE;
            return null;

        }

        @Override
        public void run() {
            super.run();
            logger.d("SaveFileToDisk线程开启");
            if (SCAN_RECIEVE)
                recieveFile();
        }
    }
} public class SqlDBOperate {
    private SQLHelper chatInfoSQLHelper; // 数据库类(t_chatting)
    private SQLiteDatabase chatInfoDataBase; // 数据库(t_chatting)的操作类
    private DBHelper userSQLHelper; // 数据库类(t_user)
    private SQLiteDatabase userDataBase;// 数据库(t_user)的操作类

    /*
     * 构造函数参数：context对象通过db的方法来操作数据库的增删改查
     */
    public SqlDBOperate(Context context) {
        chatInfoSQLHelper = new SQLHelper(context);
        chatInfoDataBase = chatInfoSQLHelper.getWritableDatabase();
        userSQLHelper = new DBHelper(context);
        userDataBase = userSQLHelper.getWritableDatabase();
    }

    /* 关闭数据库 */
    public void close() {
        userSQLHelper.close();
        userDataBase.close();
        chatInfoSQLHelper.close();
        chatInfoDataBase.close();
    }

    /*
     * 参数：userInfo类 作用：用来添加用户信息
     */
    public void addUserInfo(UserInfo user) {

        ContentValues values = new ContentValues();
        values.put("name", user.getName());
        values.put("sex", user.getSex());
        values.put("age", user.getAge());
        values.put("IMEI", user.getIMEI());
        values.put("ip", user.getIPAddr());
        values.put("status", user.getIsOnline());
        values.put("avater", user.getAvater());
        values.put("lastdate", user.getLastDate());
        values.put("device", user.getDevice());
        values.put("constellation", user.getConstellation());
        int id = getIDByIMEI(user.getIMEI());
        if (id != 0) {
            user.setId(id);
            updateUserInfo(user);
        }
        else
            userDataBase.insert(userSQLHelper.getTableName(), "id", values);
    }

    /* 获取在线信息尚未完善,默认在线状态(0) */
    public void addUserInfo(Users people) {
        ContentValues values = new ContentValues();
        values.put("name", people.getNickname());
        values.put("sex", people.getGender());
        values.put("age", people.getAge());
        values.put("IMEI", people.getIMEI());
        values.put("ip", people.getIpaddress());
        values.put("status", people.getOnlineStateInt());
        values.put("avater", people.getAvatar());
        values.put("lastdate", people.getLogintime());
        values.put("device", people.getDevice());
        values.put("constellation", people.getConstellation());
        int id = getIDByIMEI(people.getIMEI());
        if (id != 0) {
            userDataBase.update(userSQLHelper.getTableName(), values, "id = ?",
                    new String[] { String.valueOf(id) });
        }
        else
            userDataBase.insert(userSQLHelper.getTableName(), "id", values);
    }

    /*
     * 参数：userInfo类 作用：用来更新用户信息
     */
    public void updateUserInfo(UserInfo user) {
        // db=helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", user.getName());
        values.put("sex", user.getSex());
        values.put("age", user.getAge());
        values.put("IMEI", user.getIMEI());
        values.put("ip", user.getIPAddr());
        values.put("status", user.getIsOnline());
        values.put("avater", user.getAvater());
        values.put("lastdate", user.getLastDate());
        values.put("device", user.getDevice());
        values.put("constellation", user.getConstellation());
        userDataBase.update(userSQLHelper.getTableName(), values, "id = ?",
                new String[] { String.valueOf(user.getId()) });
    }

    /*
     * 参数：用户的IMEI序列码结果返回IMEI码对应用户的ID
     */
    public int getIDByIMEI(String imei) {
        Cursor cursor = userDataBase.query(userSQLHelper.getTableName(), new String[] { "id" },
                "IMEI=?", new String[] { imei }, null, null, null);
        if (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            cursor.close();
            return id;
        }
        cursor.close();
        return 0;
    }

    /*
     * 参数：用户对应序号ID 作用:用来查找对应的用户 返回IMEI
     */
    public String getIMEIByUserID(int id) {
        Cursor cursor = userDataBase.query(userSQLHelper.getTableName(), new String[] { "IMEI" },
                "id=?", new String[] { String.valueOf(id) }, null, null, null);
        if (cursor.moveToNext()) {
            String IMEI = cursor.getString(cursor.getColumnIndex("IMEI"));
            cursor.close();
            return IMEI;
        }
        cursor.close();
        return null;
    }

    /*
     * 参数：用户对应序号ID 作用:用来查找对应的用户 返回userInfo类
     */
    public UserInfo getUserInfoByID(int id) {
        // db = helper.getWritableDatabase();
        // db.query(table, columns, selection, selectionArgs, groupBy, having,
        // orderBy)
        Cursor cursor = userDataBase.query(userSQLHelper.getTableName(), new String[] { "id",
                "name", "age", "IMEI", "sex", "ip", "status", "avater", "lastdate", "device",
                "constellation" }, "id=?", new String[] { String.valueOf(id) }, null, null, null);
        if (cursor.moveToNext()) {
            UserInfo userInfo = new UserInfo(cursor.getInt(cursor.getColumnIndex("id")),
                    cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor
                            .getColumnIndex("age")),
                    cursor.getString(cursor.getColumnIndex("sex")), cursor.getString(cursor
                            .getColumnIndex("IMEI")),
                    cursor.getString(cursor.getColumnIndex("ip")), cursor.getInt(cursor
                            .getColumnIndex("status")), cursor.getInt(cursor
                            .getColumnIndex("avater")), cursor.getString(cursor
                            .getColumnIndex("lastdate")), cursor.getString(cursor
                            .getColumnIndex("device")), cursor.getString(cursor
                            .getColumnIndex("constellation")));
            cursor.close();
            return userInfo;
        }
        cursor.close();
        return null;
    }

    /*
     * 参数：用户对应的IMEI码 作用:用来查找对应的用户 返回userInfo类
     */
    public UserInfo getUserInfoByIMEI(String imei) {
        // db = helper.getWritableDatabase();
        // db.query(table, columns, selection, selectionArgs, groupBy, having,
        // orderBy)
        Cursor cursor = userDataBase.query(userSQLHelper.getTableName(), new String[] { "id",
                "name", "age", "IMEI", "sex", "ip", "status", "avater", "lastdate", "device",
                "constellation" }, "IMEI=?", new String[] { imei }, null, null, null);
        if (cursor.moveToNext()) {
            UserInfo userInfo = new UserInfo(cursor.getInt(cursor.getColumnIndex("id")),
                    cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor
                            .getColumnIndex("age")),
                    cursor.getString(cursor.getColumnIndex("sex")), cursor.getString(cursor
                            .getColumnIndex("IMEI")),
                    cursor.getString(cursor.getColumnIndex("ip")), cursor.getInt(cursor
                            .getColumnIndex("status")), cursor.getInt(cursor
                            .getColumnIndex("avater")), cursor.getString(cursor
                            .getColumnIndex("lastdate")), cursor.getString(cursor
                            .getColumnIndex("device")), cursor.getString(cursor
                            .getColumnIndex("constellation")));
            cursor.close();
            return userInfo;
        }
        cursor.close();
        return null;
    }

    /*
     * 参数：用户信息的一系列序号如(1,2,3) 作用：用来删除用户信息
     */
    public void deteleUserInfo(Integer... ids) {
        if (ids.length > 0) {
            StringBuffer sb = new StringBuffer();
            String[] strPid = new String[ids.length];
            for (int i = 0; i < ids.length; i++) {
                sb.append('?').append(',');
                strPid[i] = String.valueOf(ids[i]);
            }
            sb.deleteCharAt(sb.length() - 1);
            // db = helper.getWritableDatabase();
            userDataBase.delete(userSQLHelper.getTableName(), "id in (" + sb + ")", strPid);
        }
    }

    /*
     * 用来获取近期的一系列用户信息 参数:start为步数，count为最大记录数，(倒序排列) 放回List<userInfo>
     */
    public List<UserInfo> getScrollDataOfUserInfo(int start, int count) {
        List<UserInfo> users = new ArrayList<UserInfo>();
        // db = helper.getWritableDatabase();
        Cursor cursor = userDataBase.query(userSQLHelper.getTableName(), new String[] { "id",
                "name", "age", "sex", "IMEI", "ip", "status", "avater", "lastdate", "device",
                "constellation" }, null, null, null, null, "id desc", start + "," + count);
        while (cursor.moveToNext()) {
            users.add(new UserInfo(cursor.getInt(cursor.getColumnIndex("id")), cursor
                    .getString(cursor.getColumnIndex("name")), cursor.getInt(cursor
                    .getColumnIndex("age")), cursor.getString(cursor.getColumnIndex("sex")), cursor
                    .getString(cursor.getColumnIndex("IMEI")), cursor.getString(cursor
                    .getColumnIndex("ip")), cursor.getInt(cursor.getColumnIndex("status")), cursor
                    .getInt(cursor.getColumnIndex("avater")), cursor.getString(cursor
                    .getColumnIndex("lastdate")),
                    cursor.getString(cursor.getColumnIndex("device")), cursor.getString(cursor
                            .getColumnIndex("constellation"))));
        }
        cursor.close();
        return users;
    }

    /*
     * 作用: 用来获取表中用户总数量
     */
    public long getCountOfUserInfo() {
        // db = helper.getWritableDatabase();
        Cursor cursor = userDataBase.query(userSQLHelper.getTableName(),
                new String[] { "count(*)" }, null, null, null, null, null);
        if (cursor.moveToNext()) {
            long count = cursor.getLong(0);
            cursor.close();
            return count;
        }
        cursor.close();
        return 0;
    }

    /*
     * 该函数将所有数据库中用户表的信息用JSON形式的String来表示
     */
    public String sendUserInfoToJSON() {
        List<UserInfo> users;
        int count = (int) getCountOfUserInfo();
        users = getScrollDataOfUserInfo(0, count);
        JSONStringer jsonText = new JSONStringer();
        try {
            // 首先是{，对象开始。object和endObject必须配对使用
            jsonText.object();

            jsonText.key("user");

            // 键user的值是数组。array和endArray必须配对使用
            jsonText.array();
            for (UserInfo user : users) {
                jsonText.object();

                jsonText.key("id");
                jsonText.value(user.getId());
                jsonText.key("name");
                jsonText.value(user.getName());
                jsonText.key("sex");
                jsonText.value(user.getSex());
                jsonText.key("age");
                jsonText.value(user.getAge());
                jsonText.key("IMEI");
                jsonText.value(user.getIMEI());
                jsonText.key("ip");
                jsonText.value(user.getIPAddr());
                jsonText.key("status");
                jsonText.value(user.getIsOnline());
                jsonText.key("avater");
                jsonText.value(user.getAvater());
                jsonText.key("lastdate");
                jsonText.value(user.getLastDate());
                jsonText.key("device");
                jsonText.value(user.getDevice());
                jsonText.key("constellation");
                jsonText.value(user.getConstellation());
                jsonText.endObject();
            }
            jsonText.endArray();

            // }，对象结束
            jsonText.endObject();
        }
        catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
        return jsonText.toString();
    }

    /*
     * 参数：发送方ID sendID,接收方ID receiverID结果返回一系列的聊天记录的ID
     */
    public List<Integer> getIDOfChattingInfo(int senderID, int receiverID) {
        List<Integer> ids = new ArrayList<Integer>();
        Cursor cursor = chatInfoDataBase.query(chatInfoSQLHelper.getTableName(),
                new String[] { "id" }, "sendID=? and receiverID=?",
                new String[] { String.valueOf(senderID), String.valueOf(receiverID) }, null, null,
                null);
        while (cursor.moveToNext()) {
            ids.add(Integer.valueOf(cursor.getInt(cursor.getColumnIndex("id"))));
        }
        cursor.close();
        return ids;
    }

    /*
     * 参数：发送方ID sendID,接收方ID receiverID结果返回一系列的聊天记录
     */
    public List<ChattingInfo> getAllMessageFromChattingInfo(int sendID, int receiverID) {
        List<ChattingInfo> infos = new ArrayList<ChattingInfo>();
        Cursor cursor = chatInfoDataBase.query(chatInfoSQLHelper.getTableName(), new String[] {
                "id", "sendID", "receiverID", "chatting", "date", "style" },
                "sendID=? and receiverID=?",
                new String[] { String.valueOf(sendID), String.valueOf(receiverID) }, null, null,
                null);
        while (cursor.moveToNext()) {
            infos.add(new ChattingInfo(cursor.getInt(cursor.getColumnIndex("id")), cursor
                    .getInt(cursor.getColumnIndex("sendID")), cursor.getInt(cursor
                    .getColumnIndex("receiverID")),
                    cursor.getString(cursor.getColumnIndex("date")), cursor.getString(cursor
                            .getColumnIndex("chatting")), cursor.getInt(cursor
                            .getColumnIndex("style"))));
        }
        cursor.close();
        return infos;
    }

    /*
     * 参数：chattinginfo类 作用：用来添加聊天记录
     */
    public void addChattingInfo(ChattingInfo info) {

        ContentValues values = new ContentValues();
        values.put("sendID", info.getSendID());
        values.put("receiverID", info.getReceiverID());
        values.put("chatting", info.getInfo());
        values.put("date", info.getDate());
        values.put("style", info.getStyle());
        chatInfoDataBase.insert(chatInfoSQLHelper.getTableName(), "id", values);
    }

    /*
     * 参数：chattinginfo类 作用：用来添加聊天记录
     */
    public void addChattingInfo(int senderID, int recieverID, String time, String content,
            CONTENT_TYPE type) {

        ContentValues values = new ContentValues();
        values.put("sendID", senderID);
        values.put("receiverID", recieverID);
        values.put("chatting", content);
        values.put("date", time);
        values.put("style", getStyteByContentType(type));
        chatInfoDataBase.insert(chatInfoSQLHelper.getTableName(), "id", values);
    }

    private int getStyteByContentType(CONTENT_TYPE type) {
        if (type == CONTENT_TYPE.TEXT) {
            return 0;
        }
        else if (type == CONTENT_TYPE.IMAGE) {
            return 1;
        }
        else if (type == CONTENT_TYPE.FILE) {
            return 2;
        }
        else if (type == CONTENT_TYPE.VOICE) {
            return 3;
        }
        return -1;
    }

    /*
     * 参数：chattinginfo类 作用：用来添加聊天记录
     */
    public void addChattingInfo(String senderIMEI, String recieverIMEI, String time,
            String content, CONTENT_TYPE type) {

        ContentValues values = new ContentValues();
        values.put("sendID", getIDByIMEI(senderIMEI));
        values.put("receiverID", getIDByIMEI(recieverIMEI));
        values.put("chatting", content);
        values.put("date", time);
        values.put("style", getStyteByContentType(type));
        chatInfoDataBase.insert(chatInfoSQLHelper.getTableName(), "id", values);
    }

    /*
     * 参数：chattinginfo类 作用：用来更新聊天记录
     */
    public void updateChattingInfo(ChattingInfo info) {
        // db=helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("sendID", info.getSendID());
        values.put("receiverID", info.getReceiverID());
        values.put("chatting", info.getInfo());
        values.put("date", info.getDate());
        values.put("style", info.getStyle());
        chatInfoDataBase.update(chatInfoSQLHelper.getTableName(), values, "id = ?",
                new String[] { String.valueOf(info.getId()) });
    }

    /*
     * 参数：聊天记录序号ID 作用:用来查找对应的一条聊天记录 返回chattinginfo类
     */
    public ChattingInfo getChattingInfoByID(int id) {
        // db = helper.getWritableDatabase();
        // db.query(table, columns, selection, selectionArgs, groupBy, having,
        // orderBy)
        Cursor cursor = chatInfoDataBase.query(chatInfoSQLHelper.getTableName(), new String[] {
                "id", "sendID", "receiverID", "chatting", "date", "style" }, "id=?",
                new String[] { String.valueOf(id) }, null, null, null);
        if (cursor.moveToNext()) {
            ChattingInfo chattingInfo = new ChattingInfo(
                    cursor.getInt(cursor.getColumnIndex("id")), cursor.getInt(cursor
                            .getColumnIndex("sendID")), cursor.getInt(cursor
                            .getColumnIndex("receiverID")), cursor.getString(cursor
                            .getColumnIndex("date")), cursor.getString(cursor
                            .getColumnIndex("chatting")), cursor.getInt(cursor
                            .getColumnIndex("style")));
            cursor.close();
            return chattingInfo;
        }
        return null;
    }

    /*
     * 删除所有聊天记录
     */
    public void deteleAllChattingInfo() {
        chatInfoDataBase.delete(chatInfoSQLHelper.getTableName(), null, null);
    }

    /*
     * 参数：聊天记录的一系列序号如(1,2,3) 作用：用来删除聊天记录
     */
    public void deteleChattingInfo(Integer... ids) {
        if (ids.length > 0) {
            StringBuffer sb = new StringBuffer();
            String[] strPid = new String[ids.length];
            for (int i = 0; i < ids.length; i++) {
                sb.append('?').append(',');
                strPid[i] = String.valueOf(ids[i]);
            }
            sb.deleteCharAt(sb.length() - 1);
            // db = helper.getWritableDatabase();
            chatInfoDataBase.delete(chatInfoSQLHelper.getTableName(), "id in (" + sb + ")", strPid);
        }
    }

    /*
     * 用来获取近期的一系列聊天记录 参数:start为开始位置，count为最大记录数，(倒序排列) 放回List<chattingInfo>
     */
    public List<ChattingInfo> getScrollDataOfChattingInfo(int start, int count) {
        List<ChattingInfo> info = new ArrayList<ChattingInfo>();
        // db = helper.getWritableDatabase();
        Cursor cursor = chatInfoDataBase.query(chatInfoSQLHelper.getTableName(), new String[] {
                "id", "sendID", "receiverID", "chatting", "date", "style" }, null, null, null,
                null, "id desc", start + "," + count);
        while (cursor.moveToNext()) {
            info.add(new ChattingInfo(cursor.getInt(cursor.getColumnIndex("id")), cursor
                    .getInt(cursor.getColumnIndex("sendID")), cursor.getInt(cursor
                    .getColumnIndex("receiverID")),
                    cursor.getString(cursor.getColumnIndex("date")), cursor.getString(cursor
                            .getColumnIndex("chatting")), cursor.getInt(cursor
                            .getColumnIndex("style"))));
        }
        cursor.close();
        return info;
    }

    /*
     * 用来获取近期的一系列聊天记录 参数:start为开始位置，count为最大记录数，(倒序排列) 放回List<chattingInfo>
     */
    public List<Message> getScrollMessageOfChattingInfo(int start, int count, int senderID,
            int recieverID) {
        List<Message> messages = new ArrayList<Message>();
        Cursor cursor = chatInfoDataBase.query(
                chatInfoSQLHelper.getTableName(),
                new String[] { "id", "sendID", "receiverID", "chatting", "date", "style" },
                "(sendID=? and receiverID=?) or (receiverID=? and sendID=?)",
                new String[] { String.valueOf(senderID), String.valueOf(recieverID),
                        String.valueOf(senderID), String.valueOf(recieverID) }, null, null,
                "id desc", start + "," + count);
        while (cursor.moveToNext()) {
            Message message = chattingInfoToMessage(new ChattingInfo(cursor.getInt(cursor
                    .getColumnIndex("id")), cursor.getInt(cursor.getColumnIndex("sendID")),
                    cursor.getInt(cursor.getColumnIndex("receiverID")), cursor.getString(cursor
                            .getColumnIndex("date")), cursor.getString(cursor
                            .getColumnIndex("chatting")), cursor.getInt(cursor
                            .getColumnIndex("style"))));
            messages.add(message);
        }
        cursor.close();
        Collections.reverse(messages);
        return messages;
    }

    private Message chattingInfoToMessage(ChattingInfo chattingInfo) {
        Message message = new Message();
        message.setMsgContent(chattingInfo.getInfo()); // 设置聊天信息内容
        message.setSendTime(chattingInfo.getDate());// 设置聊天信息发送时间
        switch (chattingInfo.getStyle())// 设置聊天信息类型
        {
            case 0:
                message.setContentType(CONTENT_TYPE.TEXT);
                break;
            case 1:
                message.setContentType(CONTENT_TYPE.IMAGE);
                break;
            case 2:
                message.setContentType(CONTENT_TYPE.FILE);
                break;
            case 3:
                message.setContentType(CONTENT_TYPE.VOICE);
                break;
        }
        message.setSenderIMEI(getIMEIByUserID(chattingInfo.getSendID()));// 设置发送方ID
        return message;
    }

    /*
     * 作用: 用来获取表中聊天记录总数量
     */
    public long getCountOfChattingInfo() {
        // db = helper.getWritableDatabase();
        Cursor cursor = chatInfoDataBase.query(chatInfoSQLHelper.getTableName(),
                new String[] { "count(*)" }, null, null, null, null, null);
        if (cursor.moveToNext()) {
            long count = cursor.getLong(0);
            cursor.close();
            return count;
        }
        return 0;
    }

    /*
     * 该函数将所有数据库中聊天信息表的信息用JSON形式的String来表示
     */
    public String sendChattingInfoToJSON(int sendID, int receiverID) {
        List<ChattingInfo> infos;

        infos = getAllMessageFromChattingInfo(sendID, receiverID);

        JSONStringer jsonText = new JSONStringer();
        try {
            // 首先是{，对象开始。object和endObject必须配对使用
            jsonText.object();

            jsonText.key("chatting");

            // 键user的值是数组。array和endArray必须配对使用
            jsonText.array();
            for (ChattingInfo info : infos) {
                jsonText.object();

                jsonText.key("id");
                jsonText.value(info.getId());
                jsonText.key("sendID");
                jsonText.value(info.getSendID());
                jsonText.key("receiverID");
                jsonText.value(info.getReceiverID());
                jsonText.key("chatting");
                jsonText.value(info.getInfo());
                jsonText.key("date");
                jsonText.value(info.getDate());
                jsonText.key("style");
                jsonText.value(info.getStyle());
                jsonText.endObject();
            }
            jsonText.endArray();

            // }，对象结束
            jsonText.endObject();
        }
        catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
        return jsonText.toString();
    }
} public class IPMSGConst {
	public static final int VERSION = 0x001;		// 版本号
	public static final int PORT = 0x0979;			// 端口号，飞鸽协议默认端口2425
	
	public static final int IPMSG_NOOPERATION		 = 0x00000000;	//不进行任何操作
	public static final int IPMSG_BR_ENTRY			 = 0x00000001;	//用户上线
	public static final int IPMSG_BR_EXIT		 	 = 0x00000002;	//用户退出
	public static final int IPMSG_ANSENTRY			 = 0x00000003;	//通报在线
	public static final int IPMSG_BR_ABSENCE		 = 0x00000004;	//改为缺席模式
	
	public static final int IPMSG_BR_ISGETLIST		 = 0x00000010;	//寻找有效的可以发送用户列表的成员
	public static final int IPMSG_OKGETLIST			 = 0x00000011;	//通知用户列表已经获得
	public static final int IPMSG_GETLIST			 = 0x00000012;	//用户列表发送请求
	public static final int IPMSG_ANSLIST			 = 0x00000013;	//应答用户列表发送请求
	
	public static final int IPMSG_SENDMSG    		 = 0x00000020;	//发送消息
	public static final int IPMSG_RECVMSG 			 = 0x00000021;	//通报收到消息
	public static final int IPMSG_READMSG 			 = 0x00000030;	//消息打开通知
	public static final int IPMSG_DELMSG 			 = 0x00000031;	//消息丢弃通知
	public static final int IPMSG_ANSREADMSG		 = 0x00000032;	//消息打开确认通知
	
	public static final int IPMSG_GETINFO			 = 0x00000040;	//获得IPMSG版本信息
	public static final int IPMSG_SENDINFO			 = 0x00000041;	//发送IPMSG版本信息
	
	public static final int IPMSG_GETABSENCEINFO	 = 0x00000050;	//获得缺席信息
	public static final int IPMSG_SENDABSENCEINFO	 = 0x00000051;	//发送缺席信息

    public static final int IPMSG_UPDATE_FILEPROCESS = 0x00000060;  //更新文件传输进度
    public static final int IPMSG_SEND_FILE_SUCCESS  = 0x00000061;  //文件发送成功  
    public static final int IPMSG_GET_FILE_SUCCESS   = 0x00000062;  //文件接收成功
    
	public static final int IPMSG_REQUEST_IMAGE_DATA = 0x00000063;  //图片发送请求
	public static final int IPMSG_CONFIRM_IMAGE_DATA = 0x00000064;  //图片接收确认
	public static final int IPMSG_SEND_IMAGE_SUCCESS = 0x00000065;  //图片发送成功
	public static final int IPMSG_REQUEST_VOICE_DATA = 0x00000066;  //录音发送请求
	public static final int IPMSG_CONFIRM_VOICE_DATA = 0x00000067;  //录音接收确认
	public static final int IPMSG_SEND_VOICE_SUCCESS = 0x00000068;  //录音发送成功
	public static final int IPMSG_REQUEST_FILE_DATA  = 0x00000069;  //文件发送请求
	public static final int IPMSG_CONFIRM_FILE_DATA  = 0x00000070;  //文件接收确认
	
	public static final int IPMSG_GETPUBKEY			 = 0x00000072;	//获得RSA公钥
	public static final int IPMSG_ANSPUBKEY			 = 0x00000073;	//应答RSA公钥
	
	/* option for all command */
	public static final int IPMSG_ABSENCEOPT 		 = 0x00000100;	//缺席模式
	public static final int IPMSG_SERVEROPT 		 = 0x00000200;	//服务器（保留）
	public static final int IPMSG_DIALUPOPT 		 = 0x00010000;	//发送给个人
	public static final int IPMSG_FILEATTACHOPT 	 = 0x00200000;	//附加文件
	public static final int IPMSG_ENCRYPTOPT		 = 0x00400000;	//加密

} public class Entity {
	// 本来想做些什么来,暂时空着吧
} public class IPMSGProtocol {
    private static final Logger logger = Logger.getLogger(IPMSGProtocol.class);
    
    private static final String PACKETNO = "packetNo";
    private static final String COMMANDNO = "commandNo";
    private static final String ADDOBJECT = "addObject";
    private static final String ADDSTR = "addStr";
    private static final String ADDTYPE = "addType";

    private String packetNo;// 数据包编号
    private String senderIMEI; // 发送者IMEI
    private int commandNo; // 命令
    private ADDITION_TYPE addType; // 附加数据类型
    private Entity addObject; // 附加对象
    private String addStr; // 附加信息

    public IPMSGProtocol() {
        this.packetNo = getSeconds();
    }

    public enum ADDITION_TYPE {
        USER, MSG, STRING
    }

    // 根据协议字符串初始化
    public IPMSGProtocol(String paramProtocolJSON) {
        try {
            JSONObject protocolJSON = new JSONObject(paramProtocolJSON);
            packetNo = protocolJSON.getString(PACKETNO);
            commandNo = protocolJSON.getInt(COMMANDNO);
            senderIMEI = protocolJSON.getString(Users.IMEI);
            if (protocolJSON.has(ADDTYPE)) { // 若有附加信息
                String addJSONStr = null;
                if (protocolJSON.has(ADDOBJECT)) { // 若为Entity类型
                    addJSONStr = protocolJSON.getString(ADDOBJECT);
                }
                else if (protocolJSON.has(ADDSTR)) { // 若为String类型
                    addJSONStr = protocolJSON.getString(ADDSTR);
                }
                switch (ADDITION_TYPE.valueOf(protocolJSON.getString(ADDTYPE))) {
                    case USER: // 为用户数据
                        addObject = JsonUtils.getObject(addJSONStr, Users.class);
                        break;

                    case MSG: // 为消息数据
                        addObject = JsonUtils.getObject(addJSONStr, Message.class);
                        break;

                    case STRING: // 为String数据
                        addStr = addJSONStr;
                        break;

                    default:
                        break;
                }

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
            logger.e("非标准JSON文本");
        }
    }

    public IPMSGProtocol(String paramSenderIMEI, int paramCommandNo, Entity paramObject) {
        super();
        this.packetNo = getSeconds();
        this.senderIMEI = paramSenderIMEI;
        this.commandNo = paramCommandNo;
        this.addObject = paramObject;
        if (paramObject instanceof Message) { // 若为Message对象
            this.addType = ADDITION_TYPE.MSG;
        }
        else if (paramObject instanceof Users) { // 若为NearByPeople对象
            this.addType = ADDITION_TYPE.USER;
        }
    }

    public IPMSGProtocol(String paramSenderIMEI, int paramCommandNo, String paramStr) {
        super();
        this.packetNo = getSeconds();
        this.senderIMEI = paramSenderIMEI;
        this.commandNo = paramCommandNo;
        this.addStr = paramStr;
        this.addType = ADDITION_TYPE.STRING;
    }

    public IPMSGProtocol(String paramSenderIMEI, int paramCommandNo) {
        super();
        this.packetNo = getSeconds();
        this.senderIMEI = paramSenderIMEI;
        this.commandNo = paramCommandNo;
    }

    @JSONField(name = PACKETNO)
    public String getPacketNo() {
        return this.packetNo;
    }

    public void setPacketNo(String paramPacketNo) {
        this.packetNo = paramPacketNo;
    }

    @JSONField(name = Users.IMEI)
    public String getSenderIMEI() {
        return this.senderIMEI;
    }

    public void setSenderIMEI(String paramSenderIMEI) {
        this.senderIMEI = paramSenderIMEI;
    }

    @JSONField(name = ADDTYPE)
    public ADDITION_TYPE getAddType() {
        return this.addType;
    }

    public void setAddType(ADDITION_TYPE paramType) {
        this.addType = paramType;
    }

    @JSONField(name = COMMANDNO)
    public int getCommandNo() {
        return this.commandNo;
    }

    public void setCommandNo(int paramCommandNo) {
        this.commandNo = paramCommandNo;
    }

    @JSONField(name = ADDOBJECT)
    public Entity getAddObject() {
        return this.addObject;
    }

    public void setAddObject(Entity paramObject) {
        this.addObject = paramObject;
    }

    @JSONField(name = ADDSTR)
    public String getAddStr() {
        return this.addStr;
    }

    public void setAddStr(String paramStr) {
        this.addStr = paramStr;
    }

    // 输出协议JSON串
    @JSONField(serialize = false)
    public String getProtocolJSON() {
        return JsonUtils.createJsonString(this);
    }

    // 得到数据包编号，毫秒数
    @JSONField(serialize = false)
    private String getSeconds() {
        Date nowDate = new Date();
        return Long.toString(nowDate.getTime());
    }

} public class Message extends Entity {

    private String senderIMEI;
    private String sendTime;
    private String MsgContent;
    private CONTENT_TYPE contentType;
    private int percent;

    public Message() {
    }

    public Message(String paramSenderIMEI, String paramSendTime, String paramMsgContent,
            CONTENT_TYPE paramContentType) {
        this.senderIMEI = paramSenderIMEI;
        this.sendTime = paramSendTime;
        this.MsgContent = paramMsgContent;
        this.contentType = paramContentType;
    }

    /** 消息内容类型 **/
    public enum CONTENT_TYPE {
        TEXT, IMAGE, FILE, VOICE;
    }

    /**
     * 获取消息发送方IMEI
     * 
     * @return
     */

    public String getSenderIMEI() {
        return senderIMEI;
    }

    /**
     * 设置消息发送方IMEI
     * 
     * @param paramSenderIMEI
     * 
     */
    public void setSenderIMEI(String paramSenderIMEI) {
        this.senderIMEI = paramSenderIMEI;
    }

    /**
     * 获取消息内容类型
     * 
     * @return
     * @see CONTENT_TYPE
     */
    public CONTENT_TYPE getContentType() {
        return contentType;
    }

    /**
     * 设置消息内容类型
     * 
     * @param paramContentType
     * @see CONTENT_TYPE
     */
    public void setContentType(CONTENT_TYPE paramContentType) {
        this.contentType = paramContentType;
    }

    /**
     * 获取消息发送时间
     * 
     * @return
     */
    public String getSendTime() {
        return sendTime;
    }

    /**
     * 设置消息发送时间
     * 
     * @param paramSendTime
     *            发送时间,格式 xx年xx月xx日 xx:xx:xx
     */
    public void setSendTime(String paramSendTime) {
        this.sendTime = paramSendTime;
    }

    /**
     * 获取消息内容
     * 
     * @return
     */
    public String getMsgContent() {
        return MsgContent;
    }

    /**
     * 设置消息内容
     * 
     * @param paramMsgContent
     */
    public void setMsgContent(String paramMsgContent) {
        this.MsgContent = paramMsgContent;
    }

    /**
     * 克隆对象
     * 
     * @param
     */

    public Message clone() {
        return new Message(senderIMEI, sendTime, MsgContent, contentType);
    }

    @JSONField(serialize = false)
    public int getPercent() {
        return percent;
    }

    public void setPercent(int percent) {
        this.percent = percent;
    }

} public class Users extends Entity implements Parcelable {

    /** 用户常量 **/

    // 共有
    public static final String AGE = "Age";
    public static final String AVATAR = "avatar";
    public static final String ONLINESTATEINT = "OnlineStateInt";
    public static final String NICKNAME = "Nickname";
    public static final String GENDER = "Gender";
    public static final String IMEI = "IMEI";
    public static final String DEVICE = "Device";
    public static final String BIRTHDAY = "birthday";
    public static final String CONSTELLATION = "Constellation";
    public static final String IPADDRESS = "Ipaddress";
    public static final String LOGINTIME = "LoginTime";

    // 个人
    public static final String ID = "ID";
    public static final String ISCLIENT = "isClient";
    public static final String SERVERIPADDRESS = "serverIPaddress";
    public static final String ENTITY_PEOPLE = "entity_people";

    private int mAge;
    private int mAvatar;
    private int mOnlineStateInt;
    private String mNickname;
    private String mGender;
    private String mIMEI;
    private String mDevice;
    private String mBirthday;
    private String mConstellation;
    private String mIpaddress;
    private String mLogintime;

    private int mGenderId;
    private int mGenderBgId;
    private int msgCount;

    public Users() {
        this.msgCount = 0;
    }

    public Users(int age, int avatar, int onlinestate, String nickname, String gender, String IMEI,
            String device, String birthday, String constellation, String ip, String logintime) {
        this.mAge = age;
        this.mAvatar = avatar;
        this.mOnlineStateInt = onlinestate;
        this.mNickname = nickname;
        this.setGender(gender);
        this.mIMEI = IMEI;
        this.mDevice = device;
        this.mBirthday = birthday;
        this.mConstellation = constellation;
        this.mIpaddress = ip;
        this.mLogintime = logintime;

    }

    /** 共用变量 get set **/

    @JSONField(name = Users.AGE)
    public int getAge() {
        return this.mAge;
    }

    @JSONField(name = Users.AVATAR)
    public int getAvatar() {
        return this.mAvatar;
    }

    @JSONField(name = Users.ONLINESTATEINT)
    public int getOnlineStateInt() {
        return this.mOnlineStateInt;
    }

    @JSONField(name = Users.NICKNAME)
    public String getNickname() {
        return this.mNickname;
    }

    @JSONField(name = Users.GENDER)
    public String getGender() {
        return this.mGender;
    }

    @JSONField(name = Users.IMEI)
    public String getIMEI() {
        return this.mIMEI;
    }

    @JSONField(name = Users.DEVICE)
    public String getDevice() {
        return this.mDevice;
    }

    @JSONField(name = Users.BIRTHDAY)
    public String getBirthday() {
        return this.mBirthday;
    }

    @JSONField(name = Users.CONSTELLATION)
    public String getConstellation() {
        return this.mConstellation;
    }

    @JSONField(name = Users.IPADDRESS)
    public String getIpaddress() {
        return this.mIpaddress;
    }

    @JSONField(name = Users.LOGINTIME)
    public String getLogintime() {
        return this.mLogintime;
    }

    public void setAge(int paramAge) {
        this.mAge = paramAge;
    }

    public void setAvatar(int paramAvatar) {
        this.mAvatar = paramAvatar;
    }

    public void setOnlineStateInt(int paramOnlineState) {
        this.mOnlineStateInt = paramOnlineState;
    }

    public void setNickname(String paramNickname) {
        this.mNickname = paramNickname;
    }

    public void setGender(String paramGender) {
        this.mGender = paramGender;
        if ("女".equals(paramGender)) {
            setGenderId(R.drawable.ic_user_famale);
            setGenderBgId(R.drawable.bg_gender_famal);
        }
        else {
            setGenderId(R.drawable.ic_user_male);
            setGenderBgId(R.drawable.bg_gender_male);
        }
    }

    public void setIMEI(String paramIMEI) {
        this.mIMEI = paramIMEI;
    }

    public void setDevice(String paramDevice) {
        this.mDevice = paramDevice;
    }

    public void setBirthday(String paramBirthday) {
        this.mBirthday = paramBirthday;
    }

    public void setConstellation(String paramConstellation) {
        this.mConstellation = paramConstellation;
    }

    public void setIpaddress(String paramIpaddress) {
        this.mIpaddress = paramIpaddress;
    }

    public void setLogintime(String paramLogintime) {
        this.mLogintime = paramLogintime;
    }

    /** 个人变量 get set **/

    @JSONField(serialize = false)
    public int getGenderId() {
        return this.mGenderId;
    }

    public void setGenderId(int paramGenderId) {
        this.mGenderId = paramGenderId;
    }

    @JSONField(serialize = false)
    public int getGenderBgId() {
        return this.mGenderBgId;
    }

    public void setGenderBgId(int paramGenderBgId) {
        this.mGenderBgId = paramGenderBgId;
    }

    @JSONField(serialize = false)
    public int getMsgCount() {
        return this.msgCount;
    }

    public void setMsgCount(int paramMsgCount) {
        this.msgCount = paramMsgCount;
    }

    public static Parcelable.Creator<Users> getCreator() {
        return CREATOR;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mAge);
        dest.writeInt(mAvatar);
        dest.writeInt(mOnlineStateInt);
        dest.writeString(mNickname);
        dest.writeString(mGender);
        dest.writeString(mIMEI);
        dest.writeString(mDevice);
        dest.writeString(mBirthday);
        dest.writeString(mConstellation);
        dest.writeString(mIpaddress);
        dest.writeString(mLogintime);
        dest.writeInt(msgCount);
    }

    public static final Parcelable.Creator<Users> CREATOR = new Parcelable.Creator<Users>() {

        @Override
        public Users createFromParcel(Parcel source) {
            Users user = new Users();
            user.setAge(source.readInt());
            user.setAvatar(source.readInt());
            user.setOnlineStateInt(source.readInt());
            user.setNickname(source.readString());
            user.setGender(source.readString());
            user.setIMEI(source.readString());
            user.setDevice(source.readString());
            user.setBirthday(source.readString());
            user.setConstellation(source.readString());
            user.setIpaddress(source.readString());
            user.setLogintime(source.readString());
            user.setMsgCount(source.readInt());
            return user;
        }

        @Override
        public Users[] newArray(int size) {
            return new Users[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

} public class ImageUtils {

    /** 相册的RequestCode **/
    public static final int INTENT_REQUEST_CODE_ALBUM = 0;
    /** 相机的RequestCode **/
    public static final int INTENT_REQUEST_CODE_CAMERA = 1;
    /** 裁剪照片的RequestCode **/
    public static final int INTENT_REQUEST_CODE_CROP = 2;
    /** 滤镜图片的RequestCode **/
    public static final int INTENT_REQUEST_CODE_FLITER = 3;

    /**
     * 通过手机相册获取图片
     * 
     * @param activity
     */
    public static void selectPhoto(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(intent, INTENT_REQUEST_CODE_ALBUM);
    }

    /**
     * 通过手机照相获取图片
     * 
     * @param activity
     * @return 照相后图片的路径
     */
    public static String takePicture(Activity activity) {
        FileUtils.createDirFile(BaseApplication.CAMERA_IMAGE_PATH);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String path = BaseApplication.CAMERA_IMAGE_PATH + UUID.randomUUID().toString() + "jpg";
        File file = FileUtils.createNewFile(path);
        if (file != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        }
        activity.startActivityForResult(intent, INTENT_REQUEST_CODE_CAMERA);
        return path;
    }

    /**
     * 裁剪图片
     * 
     * @param context
     * @param activity
     * @param path
     *            需要裁剪的图片路径
     */
    public static void cropPhoto(Context context, Activity activity, String path) {
        Intent intent = new Intent(context, ImageFactoryActivity.class);
        if (path != null) {
            intent.putExtra("path", path);
            intent.putExtra(ImageFactoryActivity.TYPE, ImageFactoryActivity.CROP);
        }
        activity.startActivityForResult(intent, INTENT_REQUEST_CODE_CROP);
    }

    /**
     * 滤镜图片
     * 
     * @param context
     * @param activity
     * @param path
     *            需要滤镜的图片路径
     */
    public static void fliterPhoto(Context context, Activity activity, String path) {
        Intent intent = new Intent(context, ImageFactoryActivity.class);
        if (path != null) {
            intent.putExtra("path", path);
            intent.putExtra(ImageFactoryActivity.TYPE, ImageFactoryActivity.FLITER);
        }
        activity.startActivityForResult(intent, INTENT_REQUEST_CODE_FLITER);
    }

    /**
     * 从文件中获取图片
     * 
     * @param path
     *            图片的路径
     * @return
     */
    public static Bitmap getBitmapFromPath(String path) {
        return BitmapFactory.decodeFile(path);
    }

    public static Bitmap getBitmapFromID(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 获取drawble中指定文件名的ID
     * 
     * @param 文件名
     * @return 文件对应ID
     * 
     */
    public static int getImageID(String imgName) {
        Class<drawable> draw = R.drawable.class;
        try {
            Field field = draw.getDeclaredField(imgName);
            return field.getInt(imgName);
        }
        catch (SecurityException e) {
            return R.drawable.app_icon;
        }
        catch (NoSuchFieldException e) {
            return R.drawable.app_icon;
        }
        catch (IllegalArgumentException e) {
            return R.drawable.app_icon;
        }
        catch (IllegalAccessException e) {
            return R.drawable.app_icon;
        }
    }

    /**
     * 创建图片缩略图
     * 
     * @param path
     *            图片路径
     * @param w
     *            宽度
     * @param h
     *            高度
     */
    public static void createThumbnail(Context context, String path, String dir) {
        int imagePX = dp2px(context, 100);
        savePhotoToSDCard(decodedBitmapFromPath(path, imagePX, imagePX), dir,
                FileUtils.getNameByPath(path));
    }

    /**
     * 缩放图片
     * 
     * @param path
     *            图片的路径
     * @param w
     *            宽度
     * @param h
     *            长度
     * @return
     */
    public static Bitmap decodedBitmapFromPath(String path, int reqWidth, int reqHeight) {
        try {

            // 首先设置 inJustDecodeBounds=true 来获取图片尺寸
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);

            // 计算 inSampleSize 的值
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

            // 根据计算出的 inSampleSize 来解码图片生成Bitmap
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(path, options);
        }
        catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }

    /**
     * 计算缩放系数
     * 
     * @param options
     * @param reqWidth
     *            目标宽度
     * @param reqHeight
     *            目标高度
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
            int reqHeight) {
        // 原始图片的宽高
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下，取可能的inSampleSize的最大值
            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * 获取图片的长度和宽度
     * 
     * @param bitmap
     *            图片bitmap对象
     * @return
     */
    public static Bundle getBitmapWidthAndHeight(Bitmap bitmap) {
        Bundle bundle = null;
        if (bitmap != null) {
            bundle = new Bundle();
            bundle.putInt("width", bitmap.getWidth());
            bundle.putInt("height", bitmap.getHeight());
            return bundle;
        }
        return null;
    }

    /**
     * 判断图片高度和宽度是否过大
     * 
     * @param bitmap
     *            图片bitmap对象
     * @return
     */
    public static boolean bitmapIsLarge(Bitmap bitmap) {
        final int MAX_WIDTH = 60;
        final int MAX_HEIGHT = 60;
        Bundle bundle = getBitmapWidthAndHeight(bitmap);
        if (bundle != null) {
            int width = bundle.getInt("width");
            int height = bundle.getInt("height");
            if (width > MAX_WIDTH && height > MAX_HEIGHT) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据比例缩放图片
     * 
     * @param screenWidth
     *            手机屏幕的宽度
     * @param filePath
     *            图片的路径
     * @param ratio
     *            缩放比例
     * @return
     */
    public static Bitmap CompressionPhoto(float screenWidth, String filePath, int ratio) {
        Bitmap bitmap = ImageUtils.getBitmapFromPath(filePath);
        Bitmap compressionBitmap = null;
        float scaleWidth = screenWidth / (bitmap.getWidth() * ratio);
        float scaleHeight = screenWidth / (bitmap.getHeight() * ratio);
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        try {
            compressionBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
        }
        catch (Exception e) {
            return bitmap;
        }
        return compressionBitmap;
    }

    /**
     * 保存图片到SD卡
     * 
     * @param bitmap
     *            图片的bitmap对象
     */
    public static String savePhotoToSDCard(Bitmap bitmap, String filedir, String paramFilename) {

        if (!FileUtils.isSdcardExist()) {
            return null;
        }
        FileUtils.createDirFile(filedir);
        int quality = 60; // 缩略图没必要高质量
        String filename = paramFilename;

        if (TextUtils.isEmpty(paramFilename)) {
            filename = UUID.randomUUID().toString() + ".jpg";
            quality = 100;
        }

        String newFilePath = filedir + filename;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(newFilePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        catch (IOException e1) {
            return null;
        }
        return newFilePath;
    }

    /**
     * 根据滤镜类型获取图片
     * 
     * @param filterType
     *            滤镜类型
     * @param defaultBitmap
     *            默认图片
     * @return
     */
    public static Bitmap getFilter(FilterType filterType, Bitmap defaultBitmap) {
        Bitmap returnBitmap = null;
        switch (filterType) {
            case 默认:
                returnBitmap = defaultBitmap;
                break;

            case LOMO:
                returnBitmap = lomoFilter(defaultBitmap);
                break;
        }
        return returnBitmap;
    }

    /**
     * 滤镜效果--LOMO
     * 
     * @param bitmap
     * @return
     */
    public static Bitmap lomoFilter(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int dst[] = new int[width * height];
        bitmap.getPixels(dst, 0, width, 0, 0, width, height);

        int ratio = width > height ? height * 32768 / width : width * 32768 / height;
        int cx = width >> 1;
        int cy = height >> 1;
        int max = cx * cx + cy * cy;
        int min = (int) (max * (1 - 0.8f));
        int diff = max - min;

        int ri, gi, bi;
        int dx, dy, distSq, v;

        int R, G, B;

        int value;
        int pos, pixColor;
        int newR, newG, newB;
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                pos = y * width + x;
                pixColor = dst[pos];
                R = Color.red(pixColor);
                G = Color.green(pixColor);
                B = Color.blue(pixColor);

                value = R < 128 ? R : 256 - R;
                newR = (value * value * value) / 64 / 256;
                newR = (R < 128 ? newR : 255 - newR);

                value = G < 128 ? G : 256 - G;
                newG = (value * value) / 128;
                newG = (G < 128 ? newG : 255 - newG);

                newB = B / 2 + 0x25;

                // ==========边缘黑暗==============//
                dx = cx - x;
                dy = cy - y;
                if (width > height)
                    dx = (dx * ratio) >> 15;
                else
                    dy = (dy * ratio) >> 15;

                distSq = dx * dx + dy * dy;
                if (distSq > min) {
                    v = ((max - distSq) << 8) / diff;
                    v *= v;

                    ri = (int) (newR * v) >> 16;
                    gi = (int) (newG * v) >> 16;
                    bi = (int) (newB * v) >> 16;

                    newR = ri > 255 ? 255 : (ri < 0 ? 0 : ri);
                    newG = gi > 255 ? 255 : (gi < 0 ? 0 : gi);
                    newB = bi > 255 ? 255 : (bi < 0 ? 0 : bi);
                }
                // ==========边缘黑暗end==============//

                dst[pos] = Color.rgb(newR, newG, newB);
            }
        }

        Bitmap acrossFlushBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        acrossFlushBitmap.setPixels(dst, 0, width, 0, 0, width, height);
        return acrossFlushBitmap;
    }

    /**
     * 获取圆角图片
     * 
     * @param bitmap
     * @param pixels
     * @return
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {

        Bitmap output = Bitmap
                .createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 获取颜色的圆角bitmap
     * 
     * @param context
     * @param color
     * @return
     */
    public static Bitmap getRoundBitmap(Context context, int color) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        int width = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12.0f,
                metrics));
        int height = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4.0f,
                metrics));
        int round = Math.round(TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2.0f, metrics));
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(color);
        canvas.drawRoundRect(new RectF(0.0F, 0.0F, width, height), round, round, paint);
        return bitmap;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
} public class Logger {

    private static boolean logFlag;
    private static String tag;
    private static int logLevel;
    private static Hashtable<String, Logger> sLoggerTable;

    private Logger() {

    }

    /**
     * Logger初始化
     * 
     * @param mContext
     *            上下文
     * @param 是否输出日志标识
     * @param 输出日志等级
     * 
     */
    public static Logger initLogger(Context mContext, boolean flag, int level) {
        tag = AppUtils.getAppName(mContext);
        logFlag = flag;
        logLevel = level;
        sLoggerTable = new Hashtable<String, Logger>();
        
        return getLogger(mContext.getClass());
    }

    /**
     * 
     * @param className
     * @return
     */
    public static Logger getLogger(Class<?> cls) {
        String className = cls.getName();
        Logger classLogger = (Logger) sLoggerTable.get(className);
        if (classLogger == null) {
            classLogger = new Logger();
            sLoggerTable.put(className, classLogger);
        }
        return classLogger;
    }

    /**
     * Get The Current Function Name
     * 
     * @return
     */
    private String getFunctionName() {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();
        if (sts == null) {
            return null;
        }
        for (StackTraceElement st : sts) {
            if (st.isNativeMethod()) {
                continue;
            }
            if (st.getClassName().equals(Thread.class.getName())) {
                continue;
            }
            if (st.getClassName().equals(this.getClass().getName())) {
                continue;
            }
            return "[ " + Thread.currentThread().getName() + ": " + st.getFileName() + ":"
                    + st.getLineNumber() + " " + st.getMethodName() + " ]";
        }
        return null;
    }

    /**
     * The Log Level:i
     * 
     * @param str
     */
    public void i(Object str) {
        if (logFlag) {
            if (logLevel <= Log.INFO) {
                String name = getFunctionName();
                if (name != null) {
                    Log.i(tag, name + " - " + str);
                }
                else {
                    Log.i(tag, str.toString());
                }
            }
        }

    }

    /**
     * The Log Level:d
     * 
     * @param str
     */
    public void d(Object str) {
        if (logFlag) {
            if (logLevel <= Log.DEBUG) {
                String name = getFunctionName();
                if (name != null) {
                    Log.d(tag, name + " - " + str);
                }
                else {
                    Log.d(tag, str.toString());
                }
            }
        }
    }

    /**
     * The Log Level:V
     * 
     * @param str
     */
    public void v(Object str) {
        if (logFlag) {
            if (logLevel <= Log.VERBOSE) {
                String name = getFunctionName();
                if (name != null) {
                    Log.v(tag, name + " - " + str);
                }
                else {
                    Log.v(tag, str.toString());
                }
            }
        }
    }

    /**
     * The Log Level:w
     * 
     * @param str
     */
    public void w(Object str) {
        if (logFlag) {
            if (logLevel <= Log.WARN) {
                String name = getFunctionName();
                if (name != null) {
                    Log.w(tag, name + " - " + str);
                }
                else {
                    Log.w(tag, str.toString());
                }
            }
        }
    }

    /**
     * The Log Level:e
     * 
     * @param str
     */
    public void e(Object str) {
        if (logFlag) {
            if (logLevel <= Log.ERROR) {
                String name = getFunctionName();
                if (name != null) {
                    Log.e(tag, name + " - " + str);
                }
                else {
                    Log.e(tag, str.toString());
                }
            }
        }
    }

    /**
     * The Log Level:e
     * 
     * @param ex
     */
    public void e(Exception ex) {
        if (logFlag) {
            if (logLevel <= Log.ERROR) {
                Log.e(tag, "error", ex);
            }
        }
    }

    /**
     * The Log Level:e
     * 
     * @param log
     * @param tr
     */
    public void e(String log, Throwable tr) {
        if (logFlag) {
            String line = getFunctionName();
            Log.e(tag, "{Thread:" + Thread.currentThread().getName() + "}" + "[" + line + ":] "
                    + log + "\n", tr);
        }
    }
} public class SessionUtils {

    private static Users localUserInfo;
    private static HashMap<String, String> mlocalUserSession = new HashMap<String, String>(15);

    public static Users getLocalUserInfo() {
        if (localUserInfo == null) {
            localUserInfo = new Users(getAge(), getAvatar(), getOnlineStateInt(), getNickname(),
                    getGender(), getIMEI(), getDevice(), getBirthday(), getConstellation(),
                    getLocalIPaddress(), getLoginTime());

        }
        return localUserInfo;
    }

    public static void setLocalUserInfo(Users pUsers) {
        localUserInfo = pUsers;
        mlocalUserSession.put(Users.AGE, String.valueOf(pUsers.getAge()));
        mlocalUserSession.put(Users.AVATAR, String.valueOf(pUsers.getAvatar()));
        mlocalUserSession.put(Users.ONLINESTATEINT, String.valueOf(pUsers.getOnlineStateInt()));
        mlocalUserSession.put(Users.NICKNAME, pUsers.getNickname());
        mlocalUserSession.put(Users.GENDER, pUsers.getGender());
        mlocalUserSession.put(Users.IMEI, pUsers.getIMEI());
        mlocalUserSession.put(Users.DEVICE, pUsers.getDevice());
        mlocalUserSession.put(Users.BIRTHDAY, pUsers.getBirthday());
        mlocalUserSession.put(Users.CONSTELLATION, pUsers.getConstellation());
        mlocalUserSession.put(Users.IPADDRESS, pUsers.getIpaddress());
        mlocalUserSession.put(Users.LOGINTIME, pUsers.getLogintime());

    }

    public static void updateUserInfo() {
        localUserInfo = new Users(getAge(), getAvatar(), getOnlineStateInt(), getNickname(),
                getGender(), getIMEI(), getDevice(), getBirthday(), getConstellation(),
                getLocalIPaddress(), getLoginTime());
    }

    public static String getBirthday() {
        return mlocalUserSession.get(Users.BIRTHDAY);
    }

    /**
     * 获取用户数据库id
     * 
     * @return
     */
    public static int getLocalUserID() {
        return Integer.parseInt(mlocalUserSession.get(Users.ID));
    }

    /**
     * 获取本地IP
     * 
     * @return localIPaddress
     */
    public static String getLocalIPaddress() {
        return mlocalUserSession.get(Users.IPADDRESS);
    }

    /**
     * 获取热点IP
     * 
     * @return serverIPaddress
     */
    public static String getServerIPaddress() {
        return mlocalUserSession.get(Users.SERVERIPADDRESS);
    }

    /**
     * 获取昵称
     * 
     * @return Nickname
     */
    public static String getNickname() {
        return mlocalUserSession.get(Users.NICKNAME);
    }

    /**
     * 获取性别
     * 
     * @return Gender
     */
    public static String getGender() {
        return mlocalUserSession.get(Users.GENDER);
    }

    /**
     * 获取IMEI
     * 
     * @return IMEI
     */
    public static String getIMEI() {
        return mlocalUserSession.get(Users.IMEI);
    }

    /**
     * 获取设备品牌型号
     * 
     * @return device
     */
    public static String getDevice() {
        return mlocalUserSession.get(Users.DEVICE);
    }

    /**
     * 获取头像编号
     * 
     * @return AvatarNum
     */
    public static int getAvatar() {
        return Integer.parseInt(mlocalUserSession.get(Users.AVATAR));
    }

    /**
     * 获取星座
     * 
     * @return
     */
    public static String getConstellation() {
        return mlocalUserSession.get(Users.CONSTELLATION);
    }

    /**
     * 获取年龄
     * 
     * @return Age
     */
    public static int getAge() {
        return Integer.parseInt(mlocalUserSession.get(Users.AGE));
    }

    /**
     * 获取登录状态编码
     * 
     * @return OnlineStateInt
     */
    public static int getOnlineStateInt() {
        return Integer.parseInt(mlocalUserSession.get(Users.ONLINESTATEINT));
    }

    /**
     * 获取是否为客户端
     * 
     * @return isClient
     */
    public static boolean getIsClient() {
        return Boolean.parseBoolean(mlocalUserSession.get(Users.ISCLIENT));
    }

    /**
     * 获取登录时间
     * 
     * @return Data 登录时间 年月日
     */
    public static String getLoginTime() {
        return mlocalUserSession.get(Users.LOGINTIME);
    }

    public static void setBirthday(String birthday) {
        mlocalUserSession.put(Users.BIRTHDAY, birthday);
    }

    /**
     * 设置用户数据库id
     * 
     * @param paramID
     */
    public static void setLocalUserID(int paramID) {
        mlocalUserSession.put(Users.ID, String.valueOf(paramID));
    }

    /**
     * 设置登录时间
     * 
     * @param paramLoginTime
     */
    public static void setLoginTime(String paramLoginTime) {
        mlocalUserSession.put(Users.LOGINTIME, paramLoginTime);
    }

    /**
     * 设置本地IP
     * 
     * @param paramLocalIPaddress
     *            本地IP地址值
     */
    public static void setLocalIPaddress(String paramLocalIPaddress) {
        mlocalUserSession.put(Users.IPADDRESS, paramLocalIPaddress);
    }

    /**
     * 设置热点IP
     * 
     * @param paramServerIPaddress
     *            热点IP地址值
     */
    public static void setServerIPaddress(String paramServerIPaddress) {
        mlocalUserSession.put(Users.SERVERIPADDRESS, paramServerIPaddress);
    }

    /**
     * 设置昵称
     * 
     * @param paramNickname
     * 
     */
    public static void setNickname(String paramNickname) {
        mlocalUserSession.put(Users.NICKNAME, paramNickname);
    }

    /**
     * 设置星座
     * 
     * @param paramConstellation
     */
    public static void setConstellation(String paramConstellation) {
        mlocalUserSession.put(Users.CONSTELLATION, paramConstellation);
    }

    /**
     * 设置性别
     * 
     * @param paramGender
     * 
     */
    public static void setGender(String paramGender) {
        mlocalUserSession.put(Users.GENDER, paramGender);
    }

    /**
     * 设置IMEI
     * 
     * @param paramIMEI
     *            本机的IMEI值
     */
    public static void setIMEI(String paramIMEI) {
        mlocalUserSession.put(Users.IMEI, paramIMEI);
    }

    /**
     * 设置设备品牌型号
     * 
     * @param paramDevice
     */
    public static void setDevice(String paramDevice) {
        mlocalUserSession.put(Users.DEVICE, paramDevice);
    }

    /**
     * 设置登陆状态编码
     * 
     * <p>
     * 登陆编码：0 - 在线 , 1 - 忙碌 , 2 - 隐身 , 3 - 离开
     * </p>
     * 
     * @param paramOnlineStateInt
     *            登陆状态的具体编码
     */
    public static void setOnlineStateInt(int paramOnlineStateInt) {
        mlocalUserSession.put(Users.ONLINESTATEINT, String.valueOf(paramOnlineStateInt));
    }

    /**
     * 设置头像编号
     * 
     * @param paramAvatar
     *            选择的头像编号
     */
    public static void setAvatar(int paramAvatar) {
        mlocalUserSession.put(Users.AVATAR, String.valueOf(paramAvatar));
    }

    /**
     * 设置年龄
     * 
     * @param paramAge
     */
    public static void setAge(int paramAge) {
        mlocalUserSession.put(Users.AGE, String.valueOf(paramAge));
    }

    /**
     * 设置是否为客户端
     * 
     * @param paramIsClient
     */
    public static void setIsClient(boolean paramIsClient) {
        mlocalUserSession.put(Users.ISCLIENT, String.valueOf(paramIsClient));
    }

    public static boolean isLocalUser(String paramIMEI) {
        if (paramIMEI == null) {
            return false;
        }
        else if (getIMEI().equals(paramIMEI)) {
            return true;
        }
        return false;
    }

    /** 清空全局登陆Session信息 **/
    public static void clearSession() {
        mlocalUserSession.clear();
    }

}
import hillfly.wifichat.activity.ChatActivity;
import hillfly.wifichat.common.ActivitiesManager;
import hillfly.wifichat.common.BaseApplication;
import hillfly.wifichat.common.socket.tcp.TcpService;
import hillfly.wifichat.common.sql.SqlDBOperate;
import hillfly.wifichat.consts.IPMSGConst;
import hillfly.wifichat.model.Entity;
import hillfly.wifichat.model.IPMSGProtocol;
import hillfly.wifichat.model.Message;
import hillfly.wifichat.model.Users;
import hillfly.wifichat.util.ImageUtils;
import hillfly.wifichat.util.Logger;
import hillfly.wifichat.util.SessionUtils;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.content.Context;
        if (instance == null) {
            mContext = context;
            instance = new UDPMessageListener();
        }
        return instance;
    }

    @Override
    public void run() {
        while (isThreadRunning) {

            try {
                UDPSocket.receive(receiveDatagramPacket);
            }
            catch (IOException e) {
                isThreadRunning = false;
                receiveDatagramPacket = null;
                if (UDPSocket != null) {
                    UDPSocket.close();
                    UDPSocket = null;
                }
                receiveUDPThread = null;
                logger.e("UDP数据包接收失败！线程停止");
                e.printStackTrace();
                break;
            }

            if (receiveDatagramPacket.getLength() == 0) {
                logger.e("无法接收UDP数据或者接收到的UDP数据为空");
                continue;
            }

            String UDPListenResStr = "";
            try {
                UDPListenResStr = new String(receiveBuffer, 0, receiveDatagramPacket.getLength(),
                        "gbk");
            }
            catch (UnsupportedEncodingException e) {
                logger.e("系统不支持GBK编码");
            }

            IPMSGProtocol ipmsgRes = new IPMSGProtocol(UDPListenResStr);
            int commandNo = ipmsgRes.getCommandNo(); // 获取命令字
            String senderIMEI = ipmsgRes.getSenderIMEI();
            String senderIp = receiveDatagramPacket.getAddress().getHostAddress();

            if (BaseApplication.isDebugmode) {
                processMessage(commandNo, ipmsgRes, senderIMEI, senderIp);
            }
            else {
                if (!SessionUtils.isLocalUser(senderIMEI)) {
                    processMessage(commandNo, ipmsgRes, senderIMEI, senderIp);
                }
            }

            // 每次接收完UDP数据后，重置长度。否则可能会导致下次收到数据包被截断。
            if (receiveDatagramPacket != null) {
                receiveDatagramPacket.setLength(BUFFERLENGTH);
            }

        }

        receiveDatagramPacket = null;
        if (UDPSocket != null) {
            UDPSocket.close();
            UDPSocket = null;
        }
        receiveUDPThread = null;

    }

    public void processMessage(int commandNo, IPMSGProtocol ipmsgRes, String senderIMEI,
            String senderIp) {
        TcpService tcpService;
        switch (commandNo) {

        // 收到上线数据包，添加用户，并回送IPMSG_ANSENTRY应答。
            case IPMSGConst.IPMSG_BR_ENTRY: {
                logger.i("收到上线通知");
                addUser(ipmsgRes);
                sendUDPdata(IPMSGConst.IPMSG_ANSENTRY, receiveDatagramPacket.getAddress(),
                        mLocalUser);
                logger.i("成功发送上线应答");
            }
                break;

            // 收到上线应答，更新在线用户列表
            case IPMSGConst.IPMSG_ANSENTRY: {
                logger.i("收到上线应答");
                addUser(ipmsgRes);
            }
                break;

            // 收到下线广播
            case IPMSGConst.IPMSG_BR_EXIT: {
                removeOnlineUser(senderIMEI, 1);
                logger.i("成功删除imei为" + senderIMEI + "的用户");
            }
                break;

            case IPMSGConst.IPMSG_REQUEST_IMAGE_DATA:
                logger.i("收到IMAGE发送请求");

                tcpService = TcpService.getInstance(mContext);
                tcpService.setSavePath(BaseApplication.IMAG_PATH);
                tcpService.startReceive();
                sendUDPdata(IPMSGConst.IPMSG_CONFIRM_IMAGE_DATA, senderIp);
                break;

            case IPMSGConst.IPMSG_REQUEST_VOICE_DATA:
                logger.i("收到VOICE发送请求");

                tcpService = TcpService.getInstance(mContext);
                tcpService.setSavePath(BaseApplication.VOICE_PATH);
                tcpService.startReceive();
                sendUDPdata(IPMSGConst.IPMSG_CONFIRM_VOICE_DATA, senderIp);
                break;

            case IPMSGConst.IPMSG_SENDMSG: {
                logger.i("收到MSG消息");
                Message msg = (Message) ipmsgRes.getAddObject();