public class GuillotineAnimation {
    private static final String ROTATION = "rotation";
    private static final float GUILLOTINE_CLOSED_ANGLE = -90f;
    private static final float GUILLOTINE_OPENED_ANGLE = 0f;
    private static final int DEFAULT_DURATION = 625;
    private static final float ACTION_BAR_ROTATION_ANGLE = 3f;

    private final View mGuillotineView;
    private final long mDuration;
    private final ObjectAnimator mOpeningAnimation;
    private final ObjectAnimator mClosingAnimation;
    private final GuillotineListener mListener;
    private final boolean mIsRightToLeftLayout;
    private final TimeInterpolator mInterpolator;
    private final View mActionBarView;
    private final long mDelay;

    private boolean isOpening;
    private boolean isClosing;
    private boolean isOpen=false;
    private boolean isClose=true;

    private GuillotineAnimation(GuillotineBuilder builder) {
        this.mActionBarView = builder.actionBarView;
        this.mListener = builder.guillotineListener;
        this.mGuillotineView = builder.guillotineView;
        this.mDuration = builder.duration > 0 ? builder.duration : DEFAULT_DURATION;
        this.mDelay = builder.startDelay;
        this.mIsRightToLeftLayout = builder.isRightToLeftLayout;
        this.mInterpolator = builder.interpolator == null ? new GuillotineInterpolator() : builder.interpolator;
        setUpOpeningView(builder.openingView);
        setUpClosingView(builder.closingView);
        this.mOpeningAnimation = buildOpeningAnimation();
        this.mClosingAnimation = buildClosingAnimation();
        if (builder.isClosedOnStart) {
            mGuillotineView.setRotation(GUILLOTINE_CLOSED_ANGLE);
            mGuillotineView.setVisibility(View.INVISIBLE);
        }
        //TODO handle right-to-left layouts
        //TODO handle landscape orientation
    }

    public void open() {
        if (!isOpening) {
            mOpeningAnimation.start();
            isOpen=true;
            isClose=false;
        }
    }

    public void close() {
        if (!isClosing) {
            mClosingAnimation.start();
            isClose=true;
            isOpen=false;
        }

    }
    public boolean isOpening(){
        return isOpen;
    }
    public boolean isClosing(){
        return isClose;
    }

    private void setUpOpeningView(final View openingView) {
        if (mActionBarView != null) {
            mActionBarView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        mActionBarView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mActionBarView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                    mActionBarView.setPivotX(calculatePivotX(openingView));
                    mActionBarView.setPivotY(calculatePivotY(openingView));
                }
            });
        }
        openingView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                open();
            }
        });
    }

    private void setUpClosingView(final View closingView) {
        mGuillotineView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mGuillotineView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    mGuillotineView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                mGuillotineView.setPivotX(calculatePivotX(closingView));
                mGuillotineView.setPivotY(calculatePivotY(closingView));
            }
        });

        closingView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });
    }

    private ObjectAnimator buildOpeningAnimation() {
        ObjectAnimator rotationAnimator = initAnimator(ObjectAnimator.ofFloat(mGuillotineView, ROTATION, GUILLOTINE_CLOSED_ANGLE, GUILLOTINE_OPENED_ANGLE));
        rotationAnimator.setInterpolator(mInterpolator);
        rotationAnimator.setDuration(mDuration);
        rotationAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mGuillotineView.setVisibility(View.VISIBLE);
                isOpening = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isOpening = false;
                if (mListener != null) {
                    mListener.onGuillotineOpened();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        return rotationAnimator;
    }

    private ObjectAnimator buildClosingAnimation() {
        ObjectAnimator rotationAnimator = initAnimator(ObjectAnimator.ofFloat(mGuillotineView, ROTATION, GUILLOTINE_OPENED_ANGLE, GUILLOTINE_CLOSED_ANGLE));
        rotationAnimator.setDuration((long) (mDuration * GuillotineInterpolator.ROTATION_TIME));
        rotationAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isClosing = true;
                mGuillotineView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isClosing = false;
                mGuillotineView.setVisibility(View.GONE);
                startActionBarAnimation();

                if (mListener != null) {
                    mListener.onGuillotineClosed();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        return rotationAnimator;
    }

    private void startActionBarAnimation() {
        ObjectAnimator actionBarAnimation = ObjectAnimator.ofFloat(mActionBarView, ROTATION, GUILLOTINE_OPENED_ANGLE, ACTION_BAR_ROTATION_ANGLE);
        actionBarAnimation.setDuration((long) (mDuration * (GuillotineInterpolator.FIRST_BOUNCE_TIME + GuillotineInterpolator.SECOND_BOUNCE_TIME)));
        actionBarAnimation.setInterpolator(new ActionBarInterpolator());
        actionBarAnimation.start();
    }

    private ObjectAnimator initAnimator(ObjectAnimator animator) {
        animator.setStartDelay(mDelay);
        return animator;
    }

    private float calculatePivotY(View burger) {
        return burger.getTop() + burger.getHeight() / 2;
    }

    private float calculatePivotX(View burger) {
        return burger.getLeft() + burger.getWidth() / 2;
    }

    public static class GuillotineBuilder {
        private final View guillotineView;
        private final View openingView;
        private final View closingView;
        private View actionBarView;
        private GuillotineListener guillotineListener;
        private long duration;
        private long startDelay;
        private boolean isRightToLeftLayout;
        private TimeInterpolator interpolator;
        private boolean isClosedOnStart;

        public GuillotineBuilder(View guillotineView, View closingView, View openingView) {
            this.guillotineView = guillotineView;
            this.openingView = openingView;
            this.closingView = closingView;
        }

        public GuillotineBuilder setActionBarViewForAnimation(View view) {
            this.actionBarView = view;
            return this;
        }

        public GuillotineBuilder setGuillotineListener(GuillotineListener guillotineListener) {
            this.guillotineListener = guillotineListener;
            return this;
        }

        public GuillotineBuilder setDuration(long duration) {
            this.duration = duration;
            return this;
        }

        public GuillotineBuilder setStartDelay(long startDelay) {
            this.startDelay = startDelay;
            return this;
        }

        public GuillotineBuilder setRightToLeftLayout(boolean isRightToLeftLayout) {
            this.isRightToLeftLayout = isRightToLeftLayout;
            return this;
        }

        public GuillotineBuilder setInterpolator(TimeInterpolator interpolator) {
            this.interpolator = interpolator;
            return this;
        }

        public GuillotineBuilder setClosedOnStart(boolean isClosedOnStart) {
            this.isClosedOnStart = isClosedOnStart;
            return this;
        }

        public GuillotineAnimation build() {
            return new GuillotineAnimation(this);
        }
    }
} public class MyApplication extends Application{
    private BluetoothSocket bluetoothSocket;
    private Handler handler;
    private boolean isCalling;
    @Override
    public void onCreate() {
        super.onCreate();
        bluetoothSocket=null;
        handler=null;
    }
    public void setBluetoothSocket(BluetoothSocket bluetoothSocket){
        this.bluetoothSocket=bluetoothSocket;
    }
    public BluetoothSocket getBluetoothSocket(){
        return bluetoothSocket;
    }

    public void setHandler(Handler handler){
        this.handler=handler;
    }
    public Handler getHandler(){
        return handler;
    }
    public void setPhoneState(boolean isCalling){
        this.isCalling=isCalling;
    }
    public boolean getPhoneState(){
        return isCalling;
    }
} public class GuardFragment extends Fragment {
    private LinearLayout ll_guard;
    private RippleBackground rippleBackground;
    private Button btn_start;

    private MyApplication mMyApplication;
    private HintPopupWindow hintPopupWindow;
    private Intent intentService;
    private Intent mIntent;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mMyApplication = (MyApplication) getActivity().getApplication();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_guard, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        ll_guard = (LinearLayout) view.findViewById(R.id.ll_guard);
        rippleBackground = (RippleBackground) view.findViewById(R.id.ripplebackgroud);
        final ImageView iv_protect = (ImageView) view.findViewById(R.id.iv_guard);
        btn_start = (Button) view.findViewById(R.id.btn_startService);

        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMyApplication.getBluetoothSocket() != null) {
                    if(!btn_start.getText().equals("点击重启服务")) {
                        intentService = new Intent();
                        intentService.setClass(getActivity(), BtService.class);
                        getActivity().startService(intentService);
                        // iv_protect.setBackgroundResource(R.drawable.protect);
                        //btn_start.setText("正在为您保驾护航");
                        ll_guard.setVisibility(View.GONE);
                        rippleBackground.setVisibility(View.VISIBLE);
                        rippleBackground.startRippleAnimation();
                    }else{//这里的重启服务只是唤醒通信线程
                        mIntent = new Intent();
                        mIntent.setAction("RESTART_SERVICE");
                        getActivity().sendBroadcast(mIntent);
                        ll_guard.setVisibility(View.GONE);
                        rippleBackground.setVisibility(View.VISIBLE);
                        rippleBackground.startRippleAnimation();
                    }
                } else {
                    Toast.makeText(getActivity(), "开启失败请先连接上智能挂饰", Toast.LENGTH_LONG).show();
                }
            }
        });
        ArrayList<String> strList = new ArrayList<>();
        strList.add("暂停服务");
        strList.add("停止服务");
        strList.add("断开连接");

        ArrayList<View.OnClickListener> clickList = new ArrayList<>();
        View.OnClickListener clickListener_pause_service = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIntent = new Intent();
                mIntent.setAction("PAUSE_SERVICE");
                getActivity().sendBroadcast(mIntent);
                hintPopupWindow.dismissPopupWindow();
                rippleBackground.stopRippleAnimation();
                rippleBackground.setVisibility(View.GONE);
                ll_guard.setVisibility(View.VISIBLE);
                btn_start.setText("点击重启服务");
            }
        };
        View.OnClickListener clickListener_stop_service = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIntent = new Intent();
                mIntent.setAction("STOP_SERVICE");
                mIntent.setAction("CUT_CONNECT");////////////////////////////
                getActivity().sendBroadcast(mIntent);
                hintPopupWindow.dismissPopupWindow();
                //关闭服务不仅仅会停止服务，还会关闭通信线程，为关闭app做准备
                rippleBackground.stopRippleAnimation();
                rippleBackground.setVisibility(View.GONE);
                ll_guard.setVisibility(View.VISIBLE);
                getActivity().stopService(intentService);//停止蓝牙服务
                btn_start.setText("开启侦测模式");

            }
        };
        View.OnClickListener clickListener_cut_connect = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIntent = new Intent();
                mIntent.setAction("CUT_CONNECT");
                getActivity().sendBroadcast(mIntent);
                hintPopupWindow.dismissPopupWindow();
                //得去蓝牙设备连接界面重新去连接设备
                rippleBackground.setVisibility(View.GONE);
                ll_guard.setVisibility(View.VISIBLE);
            }
        };
        clickList.add(clickListener_pause_service);
        clickList.add(clickListener_stop_service);
        clickList.add(clickListener_cut_connect);


        hintPopupWindow = new HintPopupWindow(getActivity(), strList, clickList);
        ImageView button = (ImageView) view.findViewById(R.id.centerImage);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hintPopupWindow.showPopupWindow(view);
                hintPopupWindow.dismissPopupWindow();
            }
        });
    }
} public class LinkDeviceFragment extends Fragment{
    // 使能请求码
    private static final int REQUES_BT_ENABLE_CODE = 0x1002;
    //发送与接收到消息
    //发送与接收到消息
    public static final int TASK_SEND_MSG = 1;
    public static final int TASK_RECV_MSG = 2;
    public static final int TASK_GET_SOCKET = 3;
    public static final int TASK_GET_SOCKET_FAILED=4;
    public static final int TASK_DISCONNECT=5;
    // UUID号，表示不同的数据协议
    private final String UUID_STR = "00001101-0000-1000-8000-00805F9B34FB";
    private ArrayAdapter<String> adapter;          //Listview的适配器
    private ArrayList<String> mArrayList = new ArrayList<String>();    //ListView的显示内容
    private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();  //用于保存搜索到的蓝牙，避免重复添加
   // private Button mBtn_searchBle;   //搜索蓝牙按钮
    private CircularProgressButton mCpb_connect;
    private ImageView iv_connect;
    private BluetoothAdapter mBluetoothAdapter;    //蓝牙适配器
    private BluetoothDevice Selectdevice;          //保存连接的蓝牙地址
    private AcceptThread mAcceptThread;            //作为服务端监听线程
    private ConnectThread mRequestThread;          //作为客服端请求线程
    private ConnectedThread mangerThread;

    private LocationUtils locationUtils;
    private Vibrator vibrator;
    private AssetManager assetManager;

    private boolean isServiceStart=false;
    private MyApplication mApplication;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.fragment_linkdevice,container,false);
        //mBtn_searchBle= (Button) view.findViewById(R.id.btn_search);
        mCpb_connect= (CircularProgressButton) view.findViewById(R.id.cpb_connect);
        iv_connect= (ImageView) view.findViewById(R.id.iv_conntect);
        adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, mArrayList);
        locationUtils=new LocationUtils(getApplicationContext());
        vibrator = (Vibrator) getActivity(). getSystemService(VIBRATOR_SERVICE);
        mApplication= (MyApplication) getActivity().getApplication();
        mCpb_connect.setIndeterminateProgressMode(true);
        mCpb_connect.setOnClickListener(new mCpb_connectClick());
        //打开蓝牙
        openBtDevice();
        // 动态注册广播接收器
        // 用来接收扫描到的设备信息
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        getActivity().registerReceiver(mReceiver, filter);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    //打开蓝牙，启动启动服务器端线程,蓝牙通讯运行在app全程
    private boolean openBtDevice() {
        // 获得蓝牙匹配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 蓝牙设备不被支持
        if (mBluetoothAdapter == null) {
            Toast.makeText(getActivity(), "该设备没有蓝牙设备", Toast.LENGTH_LONG).show();
            return false;
        }

        // 蓝牙如果没打开，直接提示需要打开蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            // 隐式Intent
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUES_BT_ENABLE_CODE);  //在onActivityResult有打开服务端线程的操作哦
        } else {
            // 如果蓝牙在运行本程序前已经人为打开，那么直接启动服务器端线程
            Toast.makeText(getActivity(), "蓝牙已经打开！	", Toast.LENGTH_LONG).show();
            //暂时不启动服务端线程，因为手机充当的总是客服端
//            mAcceptThread = new AcceptThread(mBluetoothAdapter,mHandler); // // // // // // // // // // // // // // // // // // // // // // // // //
//            mAcceptThread.start(); // // // // // // // // // // // // // // // //蓝牙提前打开就启动服务端线程？ // // // // // //
        }
        return true;
    }

    //搜索蓝牙监听事件
    private class mCpb_connectClick implements View.OnClickListener {  //目的是开启蓝牙（有可能已经开启了），最重要的是开启服务端线程

        @Override
        public void onClick(View v) {

            if (mCpb_connect.getProgress()==0||mCpb_connect.getProgress()==-1){//如果是还没连接或者是连接失败，那就重新来过呗

                // 蓝牙没有正在搜索
                if (!mBluetoothAdapter.isDiscovering()) {//如果蓝牙没在搜索，防止手残党多次点按此button
                    //服务器端线程未建立或蓝牙未开启，这个判断基本用不着，因为这线程一定开启了，所以这if绝壁不会执行
                    //////下面的逻辑执行一定会执行
                    queryPairedDevice();     //显示已配对蓝牙，首现找到已经配对的设备，再开始搜索新设备，是不是多次一举呢
                    mBluetoothAdapter.startDiscovery();  //开始搜索

                  /*准备适配器*/

                    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(),R.style.myCorDialog);
                    //dialog.setTitle("附近的设备");
                    View title=LayoutInflater.from(getActivity()).inflate(R.layout.notificaitn_title_linkdev,null);
                    dialog.setCustomTitle(title);

                    /**
                     * 为对话绑定适配器
                     *
                     * @param adapter:适配器，可以是Arrayadapter，SimpleAdapter等
                     * @param listener：当适配器中数据源被点时触发的方法
                     */
                    dialog.setAdapter(adapter, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO: 2016/12/14  点击设备名，直接连接
                            String address = mDeviceList.get(which).getAddress();
                            Selectdevice = mBluetoothAdapter.getRemoteDevice(address);  //获得远程设备,作为服务端
                            mRequestThread = new ConnectThread(Selectdevice, mBluetoothAdapter, mHandler); // // // ////建立客户端线程 // // // // // // // // // // // // // // //
                            mRequestThread.start(); // // // // // // // //// // //客户端线程启动：选择蓝牙列表中的设备，会启动客户端线程 // // // // // //
                            mCpb_connect.setProgress(0);//如果当前是-1，不置0，圆圈转不起来。
                            mCpb_connect.setProgress(50);//开始转起来
                            // Toast.makeText(MainActivity.this, "连接" + mDeviceList.get(which).getName() + "成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                    dialog.create().show();

                }
            }else {//说明已经连接成功，这里可以在对话框复用封装好之后，加个是否确定断开现有连接的提示
                //TODO 是否确定断开现有连接的提示
            }
        }
    }

    //显示已配对蓝牙
    private void queryPairedDevice() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if (mDeviceList.contains(device)) {  //避免重复添加设备
                    return; //避免执行后续逻辑的好方法，记住！
                }
                mArrayList.add(device.getName() + "\n" + device.getAddress());//先把配对好的设备添加到listview的数据源中
                mDeviceList.add(device);//再添加到存放蓝牙设备的集合中，方便以后与查找到的设备比对是否在该集合中，不在就添加到这里和listview的数据源中
            }
        }
        adapter.notifyDataSetChanged();//通知适配器数据发生变化，刷新蓝牙设备列表
    }

    //广播接收器实时更新搜索到的蓝牙蓝牙列表，而广播由搜索蓝牙蓝牙时，系统自动发出广播
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated mEt_msgContenthod stub
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (mDeviceList.contains(device)) {  //防止重复添加蓝牙设备
                    return;
                }
                mArrayList.add(device.getName() + "\n" + device.getAddress());
                mDeviceList.add(device);
                adapter.notifyDataSetChanged();    //通知数据源更新，刷新蓝牙列表
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //Toast.makeText(MainActivity.this, "搜索完成！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    // 当startActivityForResult启动的 画面结束的时候，该方法被回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //
        if (requestCode == REQUES_BT_ENABLE_CODE && resultCode == RESULT_OK) {
            // 直接启动服务器端线程
//            mAcceptThread = new AcceptThread(mBluetoothAdapter,mHandler);
//            mAcceptThread.start(); //  //  //  //  //  //  // 蓝牙打开成功，直接启动服务端线程 //  //  //  //  //  //  //  //  //  //
            Toast.makeText(getActivity(), "蓝牙打开成功！", Toast.LENGTH_LONG).show();
        }
    }

    //Handler，负责将通信的信息更新到UI上显示，这个Handler是全局变量
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
//                case TASK_RECV_MSG://接收到对方的蓝牙信息
//                    String rcv= (String) msg.obj;  // 获得远程设备发送的消息
//                    Toast.makeText(getContext(),rcv,Toast.LENGTH_SHORT).show();
//                    if (!mApplication.getPhoneState())
//                        handleReceivedBleMsg(rcv);
//                    break;
                case TASK_GET_SOCKET:
                    mApplication.setBluetoothSocket((BluetoothSocket) msg.obj);
                    mApplication.setHandler(mHandler);
//                    mangerThread= new ConnectedThread(app.getBluetoothSocket(),getContext(),app.getHandler());
//                    mangerThread.start();
                    iv_connect.setBackgroundResource(R.drawable.connect_success);
                   // mBtn_searchBle.setText("一切准备就绪");
                    mCpb_connect.setProgress(100);
                    mRequestThread=null;//置空连接线程
                    break;
                case TASK_GET_SOCKET_FAILED:
                   // iv_connect.setBackgroundResource(R.drawable.);
                    mCpb_connect.setProgress(-1);
                    mRequestThread=null;//置空连接线程，为重新请求连接做准备
                    Toast.makeText(getActivity(), "连接失败，请重试！", Toast.LENGTH_SHORT).show();
                    break;
                case TASK_DISCONNECT:
                    mCpb_connect.setProgress(0);
                    break;
            }
        }

    };
    private void playRing() {
        try {
            MediaPlayer player=null;
            assetManager = getActivity().getAssets();
            AssetFileDescriptor afd = assetManager.openFd("caution.mp3");
            player = new MediaPlayer();
            player.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("55555555","onDestroy");
        getActivity().unregisterReceiver(mReceiver);
    }

} public class SettingFragment extends Fragment{
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        prefs = getActivity().getSharedPreferences("SettingData", MODE_PRIVATE);//这玩意不能放在定义全局变量时初始化，否则没用
//        preferences=getContext().getSharedPreferences("Location_data", MODE_PRIVATE);
        editor=prefs.edit();
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.fragment_setting,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        TextView txt_contactNum,txt_tellOthers;
        final SwitchButton sb_gesture,sb_position,sb_shake,sb_fingerprint;
        txt_contactNum= (TextView) view.findViewById(R.id.txt_contactNum);
        sb_gesture= (SwitchButton) view.findViewById(R.id.sb_gesture);
        sb_gesture.setChecked(prefs.getBoolean("gesture",true));
        txt_tellOthers= (TextView) view.findViewById(R.id.txt_tellOthers);



        txt_contactNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), SosContacterActivity.class);
                startActivity(intent);
            }
        });

        sb_gesture.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(final SwitchButton view, final boolean isChecked) {
                Log.e("777777","onCheckedChange被调用");
                if (isChecked){
                    editor.putBoolean("gesture",true);
                    final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
                    builder.setTitle(R.string.prompt);
                    builder.setMessage("已经开启铡刀菜单快捷开关,空白处左滑动打开,右滑关闭。");
                    builder.setPositiveButton(R.string.confirm, dialogButtonClickListener);
                    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            view.setChecked(false);
                            editor.putBoolean("gesture",false);
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }else{
                    editor.putBoolean("gesture",false);
                    CustomDialog.Builder builder1 = new CustomDialog.Builder(getActivity());
                    builder1.setTitle(R.string.prompt);
                    builder1.setMessage("确定关闭铡刀菜单快捷开关?");
                    builder1.setPositiveButton(R.string.confirm,dialogButtonClickListener);
                    builder1.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            view.setChecked(true);
                            editor.putBoolean("gesture",true);
                            dialog.dismiss();
                        }
                    });
                    builder1.create().show();
                }
                editor.commit();
            }
        });

        txt_tellOthers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_TEXT, "给各位伙伴们安利一个神器——智能挂饰app");
                shareIntent.setType("text/plain");
                //设置分享列表的标题，并且每次都显示分享列表
                startActivity(Intent.createChooser(shareIntent, "分享到"));
            }
        });

//
//        LocationUtils locationUtils=new LocationUtils(getContext());
//        locationUtils.startLocation();
//        Toast.makeText(getContext(), preferences.getString("location",""), Toast.LENGTH_SHORT).show();

    }
    private DialogInterface.OnClickListener dialogButtonClickListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
        }
    };

} public class SosFragment extends Fragment {
    private Context mContext;
    private LocationUtils locationUtils;
    private SosUtils sosUtils;
   /* @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
        prefs = context.getSharedPreferences("SettingData", MODE_PRIVATE);//这玩意不能放在定义全局变量时初始化，否则没用
        preferences=context.getSharedPreferences("Location_data", MODE_PRIVATE);
        locationUtils=new LocationUtils(context);
    }*/

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext=activity;
        locationUtils=new LocationUtils(mContext);
        sosUtils=new SosUtils(mContext);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view=LayoutInflater.from(getActivity()).inflate(R.layout.fragment_sos,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Button btn_sos= (Button) view.findViewById(R.id.btn_sos);
        btn_sos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationUtils.startLocation();
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sosUtils.callForHelp();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        locationUtils.stopListener();
    }
} public class BtService extends Service{
    private AcceptThread mAcceptThread;            //作为服务端监听线程
    private ConnectedThread mangerThread;          //作为客服端请求线程
    private MyApplication application;
    private BluetoothSocket bluetoothSocket;
    private LocationUtils locationUtils;
    private Vibrator vibrator;
    private AssetManager assetManager;
    private Intent shakeService;
    private boolean isServiceStart=false;
    private MyApplication mApplication;

    private SosUtils sosUtils;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sosUtils=new SosUtils(getApplicationContext());
        locationUtils=new LocationUtils(getApplicationContext());
        vibrator = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE);
        application= (MyApplication) getApplication();
        bluetoothSocket=application.getBluetoothSocket();
        mangerThread= new ConnectedThread(bluetoothSocket,getApplicationContext(),application.getHandler());
        mangerThread.start();
        mangerThread.write("1");//写入1，让智能挂饰开始工作
        Log.i("Test2222", "蓝牙数据处理服务成功开启，发送指令1让让挂饰开始工作");
        mangerThread.recieve(new ConnectedThread.OnReusltListener() {
            @Override
            public void handlerBLEmsg(String bleData) {
                //Log.e("eeeeeee",bleData);//这里不能显示toast，因为是子线程，但是处理数据还是可以的,需要用handler.post()
               // Toast.makeText(getApplicationContext(),bleData,Toast.LENGTH_SHORT).show();
                if (!application.getPhoneState()){
                    handleReceivedBleMsg(bleData);
                }
            }
            private void handleReceivedBleMsg(String rcv) {
                if (rcv.equals("1")){
                    Log.i("Test2222", "接收到指令1，手机执行振动操作");
                    Toast.makeText(getApplicationContext(), "蓝色警报——手机振动", Toast.LENGTH_SHORT).show();
                    vibrator.vibrate(500);//手机振动
                }else if (rcv.equals("2")){
                    Log.i("Test2222", "接收到指令2，手机执行振动并响铃操作");
                    Toast.makeText(getApplicationContext(), "黄色警报——手机振动并响铃", Toast.LENGTH_SHORT).show();
                    vibrator.vibrate(1000);//手机振动
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            playRing();
                        }
                    }).start();

                }else if (rcv.equals("3")){
                    //紧急状态，定位，发送短信并拨通电话
                    Log.i("Test4444", "接收到指令3，手机开启百度定位来获取当前位置");
                    locationUtils.startLocation();
                    if (!isServiceStart) {
                        Log.i("Test2222", "接收到指令3，开启摇一摇求助服务");
                        shakeService = new Intent();//开启摇一摇打电话的功能
                        shakeService.setClass(getApplicationContext(), ShakeService.class);
                        getApplicationContext().startService(shakeService);
                        Toast.makeText(getApplicationContext(), "橙色警报--摇一摇求助功能已经开启", Toast.LENGTH_SHORT).show();
                        isServiceStart=true;
                    }
                }else if (rcv.equals("4")){
                   /* Log.i("Test4444", "接收到指令4，手机开启百度定位来获取当前位置");

                    vibrator.vibrate(2000);//手机振动
                    Log.i("Test2222", "接收到指令4，手机开始执行自动求救操作");
                    Log.i("Test6666","接收到指令4，手机自动拨打联系人电话和发送求救短信");*/
                    Toast.makeText(getApplicationContext(), "红色警报--自动发定位短信和拨打电话", Toast.LENGTH_SHORT);
                    sosUtils.callForHelp();
                }
            }


        });


        IntentFilter filter = new IntentFilter();
        filter.addAction("PAUSE_SERVICE");
        filter.addAction("RESTART_SERVICE");
        filter.addAction("STOP_SERVICE");
        filter.addAction("CUT_CONNECT");
        getApplicationContext().registerReceiver(mReceiver, filter);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mangerThread.close();
        mangerThread=null;
        application.setBluetoothSocket(null);//通信连接置为空
        getApplicationContext().unregisterReceiver(mReceiver);
    }
    private void playRing() {
        try {
            MediaPlayer player=null;
            assetManager = getApplicationContext().getAssets();
            AssetFileDescriptor afd = assetManager.openFd("caution.mp3");
            player = new MediaPlayer();
            player.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            player.prepare();
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private final BroadcastReceiver mReceiver =new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent  stopService=new Intent();
            String action = intent.getAction();
            if ("PAUSE_SERVICE".equals(action)){
                Toast.makeText(getApplicationContext(),"暂停服务",Toast.LENGTH_SHORT).show();
                mangerThread.write("0");
                mangerThread.pause();//暂停管理线程
            }else if ("STOP_SERVICE".equals(action)){
                Toast.makeText(getApplicationContext(),"停止服务",Toast.LENGTH_SHORT).show();
                stopService.setClass(getApplicationContext(), ShakeService.class);
                getApplicationContext().stopService(stopService);//关闭摇一摇服务
                mangerThread.write("0"); //关闭挂饰
                application.setBluetoothSocket(null);//通信连接置为空
            }else if ("CUT_CONNECT".equals(action)){
                Toast.makeText(getApplicationContext(),"断开连接",Toast.LENGTH_SHORT).show();
                mangerThread.write("0");
                mangerThread.close();  //关闭管理线程
                application.setBluetoothSocket(null);//通信连接置为空
            }else if ("RESTART_SERVICE".equals(action)){
                Toast.makeText(getApplicationContext(),"重启服务",Toast.LENGTH_SHORT).show();
                mangerThread.reStart();
                mangerThread.write("1");
            }
        }
    };
} public class ShakeService extends Service {
    public static final String TAG = "ShakeService";
    private SensorManager mSensorManager;
    private SensorManager sensorManager;
    private Vibrator vibrator;

    private static final int SENSOR_SHAKE = 10;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS=2;

    private SharedPreferences prefs,preferences ;
    private SharedPreferences.Editor editor;
    private SosContacter mSosContacter;
    private SosContacterDAO mSosContacterDAO;


    private SosUtils sosUtils;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        sosUtils=new SosUtils(getApplicationContext());
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        sensorManager.unregisterListener(sensorEventListener);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        if (sensorManager != null) {// 注册监听器
            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private final SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度，向右为正
            float y = values[1]; // y轴方向的重力加速度，向前为正
            float z = values[2]; // z轴方向的重力加速度，向上为正
            //	Log.i(TAG, "x轴方向的重力加速度" + x +  "；y轴方向的重力加速度" + y +  "；z轴方向的重力加速度" + z);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            int medumValue = 30;
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
                Log.i("Test5555", "x轴方向的重力加速度" + x + "；y轴方向的重力加速度" + y + "；z轴方向的重力加速度" + z);
                vibrator.vibrate(200);
                Message msg = new Message();
                msg.what = SENSOR_SHAKE;
                handler.sendMessage(msg);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO 自动生成的方法存根

        }
    };


    /**
     * 处理监听器发送的信息，触发相应动作的执行*/

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SENSOR_SHAKE:
                    sosUtils.callForHelp();
                    Toast.makeText(getApplicationContext(), "短信发送成功！", Toast.LENGTH_SHORT).show();
                    Log.i("Test6666","检测到手机摇晃，手机自动拨打联系人电话和发送求救短信");
                    break;
            }
        }

    };


    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
} public class AcceptThread extends Thread {
    // UUID号，表示不同的数据协议
    private final String UUID_STR = "00001101-0000-1000-8000-00805F9B34FB";
    private final BluetoothServerSocket mServerSocket;
    private boolean isCancel = false;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    public ConnectedThread mConnectedThread;
    public AcceptThread(BluetoothAdapter bluetoothAdapter, Handler handler) {
        mBluetoothAdapter=bluetoothAdapter;
        BluetoothServerSocket tmp = null;
        mHandler=handler;
        try {
            //监听RFCOMM
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
                    "Bluetooth_Chat_Room", UUID.fromString(UUID_STR));
        } catch (IOException e) {

        }
        mServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        while (true) {
            try {
                // 阻塞等待
                socket = mServerSocket.accept(); //监听的socket接收连接请求后，返回一个BluetoothSocket
            } catch (IOException e) {
                if (!isCancel) {
                    try {
                        mServerSocket.close();
                    } catch (IOException e1) {

                    }
                    // 异常结束时，再次监听
                   // mAcceptThread = new MainActivity.AcceptThread();
                   // mAcceptThread.start();
                    //this.start();不知道可行；
                }
                break;
            }
            if (socket != null) {  //如果监听请求连接的Socket已经建立了
                // 管理已经连接的客户端******************************************************
              //  mConnectedThread=new ConnectedThread(socket,mHandler);
                mConnectedThread.start();
                try {
                    mServerSocket.close();  //那么就能关闭监听的socker了
                } catch (IOException e) {

                }
               // mAcceptThread = null;又是释放资源
                break;
            }
        }
    }
    /** Will cancel the listening socket, and cause the thread to finish */
//    public void cancel() {
//        try {
//            isCancel = true;
//            mServerSocket.close();
//            mAcceptThread = null;
//            if (mConnThread != null && mConnThread.isAlive()) {
//                mConnThread.cancel();
//            }
//        } catch (IOException e) {
//
//        }还得传入一个连接线程，不够麻烦的！
//    }
} public class ConnectThread extends Thread {
    // UUID号，表示不同的数据协议
    private final String UUID_STR = "00001101-0000-1000-8000-00805F9B34FB";
    private final BluetoothSocket mSocket;
    private final BluetoothDevice mDevice;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    public ConnectThread(BluetoothDevice device, BluetoothAdapter bluetoothAdapter, Handler handler) {
        mBluetoothAdapter=bluetoothAdapter;
        BluetoothSocket tmp = null;
        mDevice = device;
        mHandler=handler;
        try {
            //创建RFCOMM通道
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(UUID_STR));
        } catch (IOException e) {
//            Log.d(TAG, "createRfcommSocketToServiceRecord error!");
        }

        mSocket = tmp;
    }

    public BluetoothDevice getDevice() {
        return mDevice;
    }

    public void run() {
        Message handlerMsg = mHandler.obtainMessage();
        // 取消设备扫描，都开始连接了，还扫个毛！
        mBluetoothAdapter.cancelDiscovery();
        try {
            // 连接远程服务器设备，另一方的服务端会收到连接请求
            mSocket.connect();

            handlerMsg.what = TASK_GET_SOCKET;
            handlerMsg.obj = mSocket;
            mHandler.sendMessage(handlerMsg);
        } catch (IOException connectException) {
//            Log.e(TAG, "Connect server failed");
            handlerMsg.what=TASK_GET_SOCKET_FAILED;
            handlerMsg.obj="failed";
            mHandler.sendMessage(handlerMsg);
            try {
                mSocket.close();
            } catch (IOException closeException) {}
            // 连接服务器失败，则自己作为服务器监听
//            mAcceptThread = new MainActivity.AcceptThread();
//            mAcceptThread.start();
            return;
        }

//        mConnectedThread=new ConnectedThread(mSocket,mHandler);
//        mConnectedThread.start();
    }

} public class LocationUtils {
    private LocationClient mLocationClient=null;

    private SharedPreferences prefs ;
    private SharedPreferences.Editor editor;
    private Context context;
    public LocationUtils(Context context){
        prefs = context.getSharedPreferences("Location_data", MODE_PRIVATE);//这玩意不能放在定义全局变量时初始化，否则没用
        editor=prefs.edit();
        this.context=context;
        mLocationClient=new LocationClient(context);
        initLocation();//给mLocationClient设置定位的各种参数
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=100;
        option.setScanSpan(span);//大于等于1000ms时，使用定时定位模式。调用requestLocation()后，每隔设定的时间定定一次位
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);

        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //Receive Location
                StringBuffer sb = new StringBuffer(256);
                sb.append("定位时间: ");
                sb.append(location.getTime());
                sb.append("，纬度: ");
                sb.append(location.getLatitude());
                sb.append(",经度: ");
                sb.append(location.getLongitude());
                sb.append("，定位精度: ");
                sb.append(location.getRadius()+"米;");
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                   /*  sb.append(";我的速度");
                     sb.append(location.getSpeed());// 单位：公里每小时*/
//                     sb.append("\nsatellite : ");
//                     sb.append(location.getSatelliteNumber());
//                     sb.append("\nheight : ");
//                     sb.append(location.getAltitude());// 单位：米
//                     sb.append("\ndirection : ");
//                     sb.append(location.getDirection());// 单位度
                    sb.append("所在地址: ");
                    sb.append(location.getAddrStr());
                     sb.append("；定位方式: ");
                     sb.append("gps定位成功");

                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    sb.append("所在位置: ");
                    sb.append(location.getAddrStr());
                    //运营商信息
//                     sb.append("\noperationers : ");
//                     sb.append(location.getOperators());
//                     sb.append("；定位方式: ");
//                     sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                     sb.append("；定位方式: ");
//                     sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
//                     sb.append("；定位方式: ");
//                     sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                   /*  sb.append("；定位方式: : ");
                     sb.append("网络不同导致定位失败，请检查网络是否通畅");*/
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                     sb.append("；定位方式:");
//                     sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                sb.append(";位置描述: ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
//                 List<Poi> list = location.getPoiList();// POI数据
//                 if (list != null) {
//                     sb.append("\npoilist size = : ");
//                     sb.append(list.size());
//                     for (Poi p : list) {
//                         sb.append("\npoi= : ");
//                         sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
//                     }
//                 }
                editor.putString("location",sb.toString()).commit();

                Log.i("111111111111",sb.toString());
//               Toast.makeText(context, prefs.getString("location",""), Toast.LENGTH_LONG).show();


            }
        });
    }
     public void startLocation(){

         if (mLocationClient!=null&&mLocationClient.isStarted()){
             mLocationClient.requestLocation();
         }else {
             mLocationClient.start();
             mLocationClient.requestLocation();
         }

     }
    public void stopListener() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient = null;
        }
    }

   /* public int requestLocation()
    发起定位，异步获取当前位置。因为是异步的，所以立即返回，不会引起阻塞。定位结果在ReceiveListener的方法OnReceive方法的参数中返回。
    需要注意：当定位SDK从定位依据判定，位置和上一次没发生变化，而且上一次定位结果可用时，则不会发起网络请求，而是返回上一次的定位结果。 返回值：
            0：正常发起了定位。
            1：服务没有启动。
            2：没有监听函数。
            6：请求间隔过短。 前后两次请求定位时间间隔不能小于1000ms。*/
} public static final int TASK_RECV_MSG = 2;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.edu.chzu.fg.smartornament.R;
import com.edu.chzu.fg.smartornament.animation.GuillotineAnimation;
import com.edu.chzu.fg.smartornament.application.MyApplication;
import com.edu.chzu.fg.smartornament.fragment.GuardFragment;
import com.edu.chzu.fg.smartornament.fragment.LinkDeviceFragment;
import com.edu.chzu.fg.smartornament.fragment.SettingFragment;
import com.edu.chzu.fg.smartornament.fragment.SosFragment;
import com.edu.chzu.fg.smartornament.service.BtService;
import com.edu.chzu.fg.smartornament.service.ShakeService;
import com.edu.chzu.fg.smartornament.thread.AcceptThread;
import com.edu.chzu.fg.smartornament.thread.ConnectThread;
import com.edu.chzu.fg.smartornament.utils.LocationUtils;
import java.util.ArrayList;
import java.util.Set;
import static android.view.Gravity.LEFT;
import static android.view.Gravity.RIGHT;
import static com.edu.chzu.fg.smartornament.fragment.LinkDeviceFragment.TASK_RECV_MSG;
                break;
            case R.id.btn_settings:
                setChecked(3);
                txt_title.setText("系统设置");
               mAnimation.close();
                break;

        }
    }

    private GestureDetector.OnGestureListener onGestureListener =
            new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                       float velocityY) {
                    float x = e2.getX() - e1.getX();
                    float y = e2.getY() - e1.getY();
                    if (x > 0) {
                        doResult(RIGHT);
                    } else if (x < 0) {
                        doResult(LEFT);
                    }
                    return true;
                }
            };

    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    public void doResult(int action) {

        switch (action) {
            case RIGHT:
                System.out.println("go right");
                if (mAnimation.isOpening()){//close 都无反应  !close打开：可以右滑动关闭，关闭：有重复动画
                    // open都无反应   ！isOpen打开：可以右滑动关闭，关闭：有重复动画
                    mAnimation.close();
                }
                break;

            case LEFT:
                System.out.println("go left");
                if (mAnimation.isClosing()){
                    mAnimation.open();
                }
                break;

        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);//true对任何Activity都适用,false表示只对第一个启动的Acitivity有用
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


//双击返回键退出app
//    private long exitTime = 0;
//    public void ExitApp()
//    {
//        if ((System.currentTimeMillis() - exitTime) > 2000)
//        {
//            Toast.makeText(this.activity, "再按一次退出程序", Toast.LENGTH_SHORT).show();
//            exitTime = System.currentTimeMillis();
//        } else
//        {     stopService(intentService);//按返回键会停止该服务，并且关闭通信socket，和通信线程
//            this.activity.finish();
//        }
//    }


    private void setChecked(int i) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        //=======================================================================
        // 1.隐藏已将加载过的Fragment
        //=======================================================================
        if (linkDevice != null) {
            transaction.hide(linkDevice);
        }
        if (guardFragment != null) {
            transaction.hide(guardFragment);
        }
        if (sosFragment != null) {
            transaction.hide(sosFragment);
        }
        if (settingFragment != null) {
            transaction.hide(settingFragment);
        }

        //=======================================================================
        //2. 开始加载当前选中的Framgment
        //=======================================================================
        switch (i) {
            case 0:
                if (linkDevice==null){
                    linkDevice=new LinkDeviceFragment();
                    transaction.add(R.id.fl_container,linkDevice);
                }else {
                    transaction.show(linkDevice);
                }
                break;
            case 1:
                if (guardFragment == null) {
                    //第一次加载
                    guardFragment = new GuardFragment();
                    transaction.add(R.id.fl_container, guardFragment);
                } else {
                    transaction.show(guardFragment);
                }
                break;
            case 2:
                if (sosFragment == null) {
                    sosFragment = new SosFragment();