public class AuthorizeActivity extends BaseActivity {

    private Toolbar mToolbar;
    private WebView mWebView;
    public static final String RESPONSE_URL = "https://api.weibo.com/oauth2/default.html?code=";

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, AuthorizeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        String url = AppConstant.AUTHORIZE_URL + "?redirect_uri=" + AppConstant.REDIRECT_URL +
                "&display=mobile&response_type=code" + "&client_id=" + AppConstant.APP_KEY +
                "&scope=friendships_groups_read,friendships_groups_write,statuses_to_me_read,follow_app_official_microblog";
        LogUtils.i("OAuth认证url ：" + url);
        if (URLUtil.isNetworkUrl(url)) {
            mWebView.loadUrl(url);
        }
    }

    @Override
    protected void initToolBar() {
        mToolbar.setTitle(R.string.app_authorize);
        mToolbar.setTitleTextColor(Color.WHITE);
        mToolbar.setNavigationIcon(R.drawable.ic_drawer_oauth_sina_normal);
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setHomeButtonEnabled(false);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_authorize);
        mWebView = (WebView) findViewById(R.id.wv_main);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && url.startsWith(RESPONSE_URL)) {
                    final String code = url.substring(url.indexOf("=") + 1);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstant.ACCESS_TOKEN_URL, listener, errorListener) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("client_id", AppConstant.APP_KEY);
                            map.put("client_secret", AppConstant.APP_SECRET);
                            map.put("grant_type", "authorization_code");
                            map.put("code", code);
                            map.put("redirect_uri", AppConstant.REDIRECT_URL);
                            return map;
                        }
                    };
                    mQueue.add(stringRequest);
                }
                return false;
            }
        });
    }

    protected Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            processData(s);
        }
    };

    private void processData(String s) {
        String access_token = JsonUtils.getString(s, "access_token");
        String expires_in = JsonUtils.getString(s, "expires_in");
        String remind_in = JsonUtils.getString(s, "remind_in");
        String uid = JsonUtils.getString(s, "uid");
        if (access_token != null) {
            SharePrefUtil.saveString(AuthorizeActivity.this, "access_token", access_token);
        }
        if (expires_in != null) {
            SharePrefUtil.saveString(AuthorizeActivity.this, "expires_in", expires_in);
        }
        if (remind_in != null) {
            SharePrefUtil.saveString(AuthorizeActivity.this, "remind_in", remind_in);
        }
        if (uid != null) {
            SharePrefUtil.saveString(AuthorizeActivity.this, "uid", uid);
        }
        Intent intent = new Intent(AuthorizeActivity.this, MainActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        finish();
    }

    protected Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            LogUtils.e("network error :" + volleyError.getMessage());
        }
    };

} public class PublishActivity extends BaseActivity implements RevealBackgroundView.OnStateChangeListener {

    private Toolbar mToolbar;
    private ActionBar actionBar;
    private ImageButton ib_location;
    private ImageButton ib_photo;
    private ImageButton ib_emotion;
    private ImageButton ib_noti;
    private ImageButton ib_sharp;
    private ImageButton ib_send;
    private ImageView iv_add;
    private TextView tv_location;
    private EditText et_content;
    private CheckBox cb_comment_to_auth;
    private TextView tv_word_num;
    private LinearLayout ll_images;
    private HorizontalScrollView mHorizontalScrollView;
    private Map<DeleteImageView, String> imageMap = new HashMap<>();
    private List<String> strList = new ArrayList<>();
    private LoadImageAsyncTask loadImageAsyncTask;
    private GridView gv_emotion;
    private EmotionAdapter adapter;
    private RevealBackgroundView vRevealBackground;

    public static final int SEND_WEIBO = 1010; //发布微博
    public static final int SEND_COMMENT = 1020; //发布评论
    public static final int SEND_REPOST = 1030; //转发微博
    public static final int REFRESH_DRAFT = 1040; //刷新草稿箱
    public static final int REPLY_COMMENT = 1050; //回复评论

    public static final String ARG_REVEAL_START_LOCATION = "reveal_start_location";

    private static final int TAKE_PHOTO = 1002; //相机拍照
    private static final int TAKE_GALLERY = 1003; //系统图库

    private boolean isPicture = false; //是否发含有图片的微博
    private boolean isLocation = false; //是否定位
    private double longitude; //经度
    private double latitude; //维度
    private int type; //源Activity 类型
    private String url; //网络url
    private String idstr; //微博ID

    public static final int SEND_WEIBO_SUCCESS = 1200; //发微博成功
    public static final int SEND_COMMENT_SUCCESS = 1250; //评论成功
    public static final int SEND_REPOST_SUCCESS = 1300; //转发成功

    private LinearLayout mLinearLayout;
    private boolean isFromFAButton; //是否从含有FloatingActionButton的界面跳转过来
    private int draft_id; //草稿箱ID
    private String cid; // 回复某人评论时的评论ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (type == PublishActivity.SEND_WEIBO && isFromFAButton) {
            setupRevealBackground(savedInstanceState);
        } else {
            mLinearLayout.setBackgroundColor(getResources().getColor(R.color.activity_bg_color));
            vRevealBackground.setVisibility(View.GONE);
        }
    }

    private void setupRevealBackground(Bundle savedInstanceState) {
        vRevealBackground.setFillPaintColor(getResources().getColor(R.color.Indigo_colorPrimary));
        vRevealBackground.setOnStateChangeListener(this);
        if (savedInstanceState == null) {
            final int[] startingLocation = getIntent().getIntArrayExtra(ARG_REVEAL_START_LOCATION);
            vRevealBackground.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    vRevealBackground.getViewTreeObserver().removeOnPreDrawListener(this);
                    vRevealBackground.startFromLocation(startingLocation);
                    return false;
                }
            });
        } else {
            vRevealBackground.setToFinishedFrame();
        }
    }

    @Override
    public void onStateChange(int state) {
        if (RevealBackgroundView.STATE_FINISHED == state) {
            if (RevealBackgroundView.STATE_FINISHED == state) {
                vRevealBackground.setVisibility(View.GONE);
                mLinearLayout.setBackgroundColor(getResources().getColor(R.color.activity_bg_color));
            }
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        draft_id = intent.getIntExtra("draft_id", 0);
        type = intent.getIntExtra("type", 0);
        isFromFAButton = intent.getBooleanExtra("isFromFAButton", false);
        idstr = intent.getStringExtra("idstr");
        cid = intent.getStringExtra("cid");
        String text = intent.getStringExtra("text");
        if (text != null) {
            et_content.setText(text);
        }
        switch (type) {
            case SEND_WEIBO:   //发微博
                actionBar.setTitle(R.string.publish_weibo);
                url = AppConstant.STATUSES_UPDATE_URL;
                break;
            case SEND_COMMENT:  //评论
                boolean isReweeted = intent.getBooleanExtra("isReweeted", false);
                actionBar.setTitle(R.string.comment_weibo);
                ib_location.setVisibility(View.GONE);
                ib_photo.setVisibility(View.GONE);
                et_content.setHint(R.string.comment_weibo);
                if (isReweeted) {
                    cb_comment_to_auth.setVisibility(View.VISIBLE);
                    cb_comment_to_auth.setText(R.string.comment_to_original_weibo);
                }
                url = AppConstant.COMMENTS_CREATE_URL;
                break;
            case SEND_REPOST:  //转发
                actionBar.setTitle(R.string.repost_weibo);
                ib_location.setVisibility(View.GONE);
                ib_photo.setVisibility(View.GONE);
                ib_sharp.setVisibility(View.GONE);
                cb_comment_to_auth.setVisibility(View.VISIBLE);
                et_content.setHint(R.string.repost_weibo);
                et_content.setSelection(0);
                url = AppConstant.STATUSES_REPOST_URL;
                break;
            case REPLY_COMMENT:
                actionBar.setTitle(R.string.reply_comment);
                ib_location.setVisibility(View.GONE);
                ib_photo.setVisibility(View.GONE);
                cb_comment_to_auth.setVisibility(View.VISIBLE);
                et_content.setHint(R.string.reply_comment);
                url = AppConstant.COMMENTS_REPLY_URL;
                break;
            default:
                break;
        }

    }

    @Override
    protected void initToolBar() {
        mToolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_publish);
        mToolbar = (Toolbar) findViewById(R.id.mToolbar);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.mHorizontalScrollView);
        iv_add = (ImageView) findViewById(R.id.iv_add);
        et_content = (EditText) findViewById(R.id.et_content);
        ll_images = (LinearLayout) findViewById(R.id.ll_images);
        ib_location = (ImageButton) findViewById(R.id.ib_location);
        ib_photo = (ImageButton) findViewById(R.id.ib_photo);
        ib_emotion = (ImageButton) findViewById(R.id.ib_emotion);
        ib_noti = (ImageButton) findViewById(R.id.ib_noti);
        ib_sharp = (ImageButton) findViewById(R.id.ib_sharp);
        ib_send = (ImageButton) findViewById(R.id.ib_send);
        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_word_num = (TextView) findViewById(R.id.tv_word_num);
        gv_emotion = (GridView) findViewById(R.id.gv_emotion);
        cb_comment_to_auth = (CheckBox) findViewById(R.id.cb_comment_to_auth);
        vRevealBackground = (RevealBackgroundView) findViewById(R.id.vRevealBackground);
        mLinearLayout = (LinearLayout) findViewById(R.id.mLinearLayout);

        adapter = new EmotionAdapter(this, new ArrayList<Emotion>());
        gv_emotion.setAdapter(adapter);
        gv_emotion.setOnItemClickListener(onItemClickListener);
        et_content.addTextChangedListener(watcher);
        et_content.setOnClickListener(listener);
        ib_location.setOnClickListener(listener);
        ib_photo.setOnClickListener(listener);
        ib_emotion.setOnClickListener(listener);
        ib_noti.setOnClickListener(listener);
        ib_sharp.setOnClickListener(listener);
        ib_send.setOnClickListener(listener);
        iv_add.setOnClickListener(listener);
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String content = s.toString();
            String num = tv_word_num.getText().toString();
            tv_word_num.setText(content.length() + num.substring(num.indexOf("/"), num.length()));
        }
    };

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ib_location:
                    processLocation();
                    break;
                case R.id.ib_photo:
                    processPhoto(v);
                    break;
                case R.id.ib_emotion:
                    processEmotion();
                    break;
                case R.id.ib_noti:
                    processNoti();
                    break;
                case R.id.ib_sharp:
                    processTopic();
                    break;
                case R.id.iv_add:
                    processPhoto(v);
                    break;
                case R.id.ib_send:
                    processSendWeibo(v);
                    break;
                case R.id.et_content:
                    if (gv_emotion.isShown()) {
                        gv_emotion.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Emotion emotion = adapter.getList().get(position);
            Bitmap bitmap = BitmapFactory.decodeByteArray(emotion.getData(), 0, emotion.getData().length);
            if (bitmap != null) {
                SpannableString ss = new SpannableString(emotion.getKey());
                ImageSpan imageSpan = new ImageSpan(PublishActivity.this, bitmap, ImageSpan.ALIGN_BOTTOM);
                ss.setSpan(imageSpan, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                et_content.getText().insert(et_content.getSelectionEnd(), ss);
            }
        }
    };

    // 处理 @ 事件
    private void processNoti() {
        Intent intent = new Intent(this, SearchUserActivity.class);
        intent.putExtra("type", SearchUserActivity.AT_USER);
        startActivityForResult(intent, SearchUserActivity.AT_USER);
    }

    //选择表情
    private void processEmotion() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(PublishActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        if (gv_emotion.isShown()) {
            gv_emotion.postDelayed(new Runnable() {
                @Override
                public void run() {
                    gv_emotion.setVisibility(View.GONE);
                }
            }, 300);
        } else {
            gv_emotion.setVisibility(View.VISIBLE);
        }
    }

    // 发布微博
    private void processSendWeibo(View v) {
        if (gv_emotion.isShown()) {
            gv_emotion.setVisibility(View.GONE);
        }
        final String content = et_content.getText().toString();
        if (TextUtils.isEmpty(content.trim()) && type != SEND_REPOST) {
            CommonUtil.showSnackbar(v, R.string.content_cannot_be_empty, getResources().getColor(R.color.Indigo_colorPrimary));
            return;
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, sendWeiboListener, errorListener) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap();
                map.put("access_token", SharePrefUtil.getString(PublishActivity.this, "access_token", ""));
                map.put("status", content);
                switch (type) {
                    case SEND_WEIBO:
                        map.put("status", content);
                        if (isLocation) {
                            map.put("lat", String.valueOf(latitude));
                            map.put("long", String.valueOf(longitude));
                        }
                        break;
                    case SEND_COMMENT:
                        map.put("comment", content);
                        map.put("id", idstr);
                        if (cb_comment_to_auth.isChecked()) {
                            map.put("comment_ori", "1");
                        }
                        break;
                    case SEND_REPOST:
                        map.put("status", content);
                        map.put("id", idstr);
                        if (cb_comment_to_auth.isChecked()) {
                            map.put("is_comment", "1");
                        }
                        break;
                    case REPLY_COMMENT:
                        map.put("comment", content);
                        map.put("cid", cid);
                        map.put("id", idstr);
                        if (cb_comment_to_auth.isChecked()) {
                            map.put("comment_ori", "1");
                        }
                }
                return map;
            }
        };
        mQueue.add(stringRequest);
    }

    Response.Listener<String> sendWeiboListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                String idstr = jsonObject.getString("idstr");
                if (!TextUtils.isEmpty(idstr)) {
                    if (type == SEND_WEIBO) {
                        setResult(SEND_WEIBO_SUCCESS);
                    } else if (type == SEND_COMMENT) {
                        setResult(SEND_COMMENT_SUCCESS);
                    } else if (type == SEND_REPOST) {
                        setResult(SEND_REPOST_SUCCESS);
                    }
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    // 处理点击 位置 事件
    private void processLocation() {
        Location location = CommonUtil.getLocation(PublishActivity.this);
        if (!isLocation) {
            if (location == null) {
                tv_location.setVisibility(View.VISIBLE);
                tv_location.setText(R.string.unknown_address);
            } else {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                isLocation = true;
                LogUtils.i("GPS坐标  longitude :" + longitude + ", latitude :" + latitude);
                String url = AppConstant.GEO_TO_ADDRESS_URL + "?access_token=" + SharePrefUtil.getString(PublishActivity.this, "access_token", "") + "&coordinate=" + longitude + "," + latitude;
                LogUtils.i("根据地理信息坐标返回实际地址 :" + url);
                getJsonData(url, jsonlistener, errorListener);
            }
        } else {
            tv_location.setVisibility(View.GONE);
            isLocation = false;
        }
    }

    Response.Listener<JSONObject> jsonlistener = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject json) {
            try {
                JSONArray geo = json.getJSONArray("geos");
                JSONObject geo0 = geo.getJSONObject(0);
                String address = geo0.getString("address");
                LogUtils.i("实际地址 :" + address);
                tv_location.setVisibility(View.VISIBLE);
                tv_location.setText(address);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            CommonUtil.showToast(PublishActivity.this, "Network Error");
        }
    };

    private String imageUrl;

    // 处理点击 图片 事件
    private void processPhoto(View v) {
        if (imageMap.size() > 8) {
            Snackbar.make(v, R.string.no_more_pictures, Snackbar.LENGTH_SHORT).show();
            return;
        }
        CommonUtil.createItemAlertDialog(PublishActivity.this, getResources().getStringArray(R.array.photo_items), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent;
                switch (which) {
                    case 0:
                        File DatalDir = Environment.getExternalStorageDirectory();
                        File myDir = new File(DatalDir, "/DCIM/Camera");
                        myDir.mkdirs();
                        String mDirectoryname = DatalDir.toString() + "/DCIM/Camera";
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss", Locale.SIMPLIFIED_CHINESE);
                        File tempfile = new File(mDirectoryname, "IMG_" + sdf.format(new Date()) + ".jpg");//tempfile为图片的路径
                        if (tempfile.isFile())
                            tempfile.delete();
                        intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        imageUrl = tempfile.getAbsolutePath();
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUrl);
                        startActivityForResult(intent, TAKE_PHOTO);
                        break;
                    case 1:
                        String url = CommonUtil.getLatestCameraPicture(PublishActivity.this);
                        loadImageAsyncTask = new LoadImageAsyncTask();
                        loadImageAsyncTask.execute(url);
                        break;
                    case 2:
//                        intent = new Intent(Intent.ACTION_PICK,
//                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//调用android的图库
//                        startActivityForResult(intent, TAKE_GALLERY);
                        startActivityForResult(new Intent(PublishActivity.this, GridImageActivity.class), TAKE_GALLERY);
                        break;
                }
            }
        },true);
    }

    // 处理点击 # 事件
    private void processTopic() {
        et_content.getText().append("##");
        et_content.setSelection(et_content.getText().length() - 1);
    }

    class LoadImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private DeleteImageView mDeleteImageView;
        private String url;
        private int imageWidth;
        private int imageHeight;
        private View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_images.removeView(mDeleteImageView);
                if (imageMap.containsKey(mDeleteImageView)) {
                    imageMap.remove(mDeleteImageView);
                }
                if(imageMap.size() == 0){
                    mHorizontalScrollView.setVisibility(View.GONE);
                }
            }
        };

        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO 优化图片
            url = params[0];
            Bitmap bitmap = BitmapUtil.decodeSampledBitmapFromUrl(url, imageWidth, imageHeight);
            return bitmap;
        }


        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                mDeleteImageView.setImageBitmap(bitmap);
                mDeleteImageView.setOnDeleteClickListener(listener);
                imageMap.put(mDeleteImageView, url);
                strList.add(url);
            }
            if (imageMap.size() > 8) {
                iv_add.setVisibility(View.GONE);
            }
            LogUtils.i("image_url :" + url + ", imageMap_size :" + imageMap.size());
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mHorizontalScrollView.getVisibility() != View.VISIBLE) {
                mHorizontalScrollView.setVisibility(View.VISIBLE);
            }
            mDeleteImageView = new DeleteImageView(PublishActivity.this);
            mDeleteImageView.setBackgroundResource(R.drawable.bg_unselected_card_item_light);
            ll_images.addView(mDeleteImageView, ll_images.getChildCount() - 1);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mDeleteImageView.getLayoutParams();
            layoutParams.width = CommonUtil.dip2px(PublishActivity.this, 90);
            layoutParams.height = CommonUtil.dip2px(PublishActivity.this, 90);
            layoutParams.setMargins(CommonUtil.dip2px(PublishActivity.this, 10), 0, CommonUtil.dip2px(PublishActivity.this, 10), 0);
            imageWidth = layoutParams.width;
            imageHeight = layoutParams.height;
            LogUtils.i("imageView" + (ll_images.getChildCount() - 1) + "width :" + imageWidth + " , height :" + imageHeight);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    if (uri == null) {
                        if (imageUrl != null) {
                            Bitmap bitmap = data.getParcelableExtra("data");
                            try {
                                OutputStream out = new FileOutputStream(imageUrl);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                                out.flush();
                                out.close();
                                loadImageAsyncTask = new LoadImageAsyncTask();
                                loadImageAsyncTask.execute(imageUrl);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        String path = uri.getPath();
                        loadImageAsyncTask = new LoadImageAsyncTask();
                        loadImageAsyncTask.execute(path);
                    }
                }
                break;
            case TAKE_GALLERY:
                if (resultCode == RESULT_OK) {
//                    Uri uri = data.getData();
                    List<String> urls = data.getStringArrayListExtra("urls");
//                    Cursor cursor = getContentResolver().query(uri, null,
//                            null, null, null);
//                    cursor.moveToFirst();
//                    String imgPath = cursor.getString(1); // 图片文件路径
                    for (int i = 0; i < urls.size(); i++) {
                        LoadImageAsyncTask loadImageAsyncTask = new LoadImageAsyncTask();
                        loadImageAsyncTask.execute(urls.get(i));
                    }

                }
                break;
            case SearchUserActivity.AT_USER:
                if (resultCode == RESULT_OK) {
                    String screen_name = data.getStringExtra("screen_name");
                    et_content.getText().insert(et_content.getSelectionEnd(), "@" + screen_name + " ");
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                saveToDraft();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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

    /*
     *返回提示是否保存到草稿箱
     */
    private void saveToDraft() {
        //如果表情框出现，则隐藏
        if (gv_emotion.isShown()) {
            gv_emotion.setVisibility(View.GONE);
            return;
        }
        // 如果是回复评论，直接finish
        if (type == REPLY_COMMENT) {
            finish();
            return;
        }
        final String content = et_content.getText().toString();
        if (!TextUtils.isEmpty(content)) {
            CommonUtil.createMessageAlertDialog(this, getResources().getString(R.string.tip), getResources().getString(R.string.save_draft), getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }, getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyApplication.getExecutor().execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    if (draft_id == 0) {
                                        Draft d = new Draft(0, type, content, strList, idstr);
                                        DraftDB.addDraft(d);
                                    } else {
                                        Draft d = new Draft(draft_id, type, content, strList, idstr);
                                        DraftDB.updateDraft(d);
                                    }
                                }
                            });
                    if (draft_id != 0) {
                        setResult(REFRESH_DRAFT);
                    }
                    finish();
                }
            }, true);
        } else {
            finish();
        }

    }

} public class AppConstant {
    /**
     * App Key
     */
    public static final String APP_KEY = "2146675350";
    /**
     * App Secret
     */
    public static final String APP_SECRET = "2c990a9d6f2fd0a59a3f76da68663a58";
    /**
     * 默认回调页面
     */
    public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
    /**
     * OAuth2的authorize接口
     */
    public static final String AUTHORIZE_URL = "https://open.weibo.cn/oauth2/authorize";
    /**
     * OAuth2的access_token接口
     */
    public static final String ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
    /**
     * 根据用户ID获取用户信息
     */
    public static final String USERS_SHOW_URL = "https://api.weibo.com/2/users/show.json";
    /**
     * 查询用户access_token的授权相关信息，包括授权时间，过期时间和scope权限。
     */
    public static final String GET_TOKEN_INFO_URL = "https://api.weibo.com/oauth2/get_token_info";
    /**
     * 获取当前登录用户及其所关注用户的最新微博
     */
    public static final String HOME_TIMELINE_URL = "https://api.weibo.com/2/statuses/home_timeline.json";
    /**
     * 搜索用户时的联想搜索建议
     */
    public static final String SEARCH_USER_URL = "https://api.weibo.com/2/search/suggestions/users.json";
    /**
     * 根据地理信息坐标返回实际地址
     */
    public static final String GEO_TO_ADDRESS_URL = "https://api.weibo.com/2/location/geo/geo_to_address.json";
    /**
     * 发布一条新微博
     */
    public static final String STATUSES_UPDATE_URL = "https://api.weibo.com/2/statuses/update.json";
    /**
     * 上传图片并发布一条新微博
     */
    public static final String STATUSES_UPLOAD_URL = "https://upload.api.weibo.com/2/statuses/upload.json";
    /**
     * 获取双向关注用户的最新微博
     */
    public static final String STATUSES_BILATERAL_TIMELINE_URL = "https://api.weibo.com/2/statuses/bilateral_timeline.json";
    /**
     * 转发一条微博
     */
    public static final String STATUSES_REPOST_URL = "https://api.weibo.com/2/statuses/repost.json";
    /**
     * 对一条微博进行评论
     */
    public static final String COMMENTS_CREATE_URL = "https://api.weibo.com/2/comments/create.json";
    /**
     * 获取用户的关注列表
     */
    public static final String FRIENDSHIPS_FRIENDS_URL = "https://api.weibo.com/2/friendships/friends.json";
    /**
     * 获取某个位置周边的动态
     */
    public static final String PLACE_NEARBY_TIMELINE_URL = "https://api.weibo.com/2/place/nearby_timeline.json";
    /**
     * 获取我的收藏
     */
    public static final String MY_FAVORITE_URL = "https://api.weibo.com/2/favorites.json";
    /**
     * 添加一条微博到收藏里
     */
    public static final String FAVORITE_CREATE_URL = "https://api.weibo.com/2/favorites/create.json";
    /**
     * 取消收藏一条微博
     */
    public static final String FAVORITE_DESTROY_URL = "https://api.weibo.com/2/favorites/destroy.json";
    /**
     * 根据微博ID返回某条微博的评论列表
     */
    public static final String COMMENTS_SHOW_URL = "https://api.weibo.com/2/comments/show.json";
    /**
     * 获取指定微博的转发微博列表
     */
    public static final String STATUSES_REPOST_TIMELINE_URL = "https://api.weibo.com/2/statuses/repost_timeline.json";
    /**
     * 批量获取指定微博的转发数评论数
     */
    public static final String STATUSES_COUNT_URL = "https://api.weibo.com/2/statuses/count.json";
    /**
     * 回复一条评论
     */
    public static final String COMMENTS_REPLY_URL = "https://api.weibo.com/2/comments/reply.json";
    /**
     * 获取某个用户最新发表的微博列表
     */
    public static final String STATUSES_USER_TIMELINE_URL = "https://api.weibo.com/2/statuses/user_timeline.json";
    /**
     * 返回最新的公共微博
     */
    public static final String STATUSES_PUBLIC_TIMELINE_URL = "https://api.weibo.com/2/statuses/public_timeline.json";
    /**
     * 获取某个用户的各种消息未读数
     */
    public static final String REMIND_UNREAD_COUNT_URL = "https://rm.api.weibo.com/2/remind/unread_count.json";
    /**
     * 授权回收接口，帮助开发者主动取消用户的授权。
     */
    public static final String OAUTH2_REVOKEOAUTH2_URL = "https://api.weibo.com/oauth2/revokeoauth2";
    /**
     * 获取最新的提到当前登录用户的评论，即@我的评论
     */
    public static final String COMMENTS_MENTIONS_URL = "https://api.weibo.com/2/comments/mentions.json";
    /**
     * 获取当前登录用户所接收到的评论列表
     */
    public static final String COMMENTS_TO_ME_URL = "https://api.weibo.com/2/comments/to_me.json";
    /**
     * 获取最新的提到登录用户的微博列表，即@我的微博
     */
    public static final String STATUSES_MENTIONS_URL = "https://api.weibo.com/2/statuses/mentions.json";
} public class RefreshWeiboTimelineReceiver extends BroadcastReceiver {

    public static final String INTENT_UNREAD_UPDATE = "com.yuqirong.koku.receiver.RefreshWeiboTimelineReceiver.update_unread";
    public static final String INTENT_FAB_CHANGE = "com.yuqirong.koku.receiver.RefreshWeiboTimelineReceiver.fab_change";

    private OnUpdateUIListener listener;

    public void setOnUpdateUIListener(OnUpdateUIListener listener) {
        this.listener = listener;
    }

    public interface OnUpdateUIListener {
        /**
         * 接受到广播后更新ui
         */
        void updateUI(int unreadCount);

        void updateFab();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_SCREEN_OFF.equals(action)) {
            LogUtils.i("broadcast receiver received : Screen Off");
            Intent it = new Intent(context, CheckUnreadService.class);
            it.setAction(CheckUnreadService.STOP_TIMER);
            context.startService(it);
        } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
            LogUtils.i("broadcast receiver received : Screen Unlock");
            Intent it = new Intent(context, CheckUnreadService.class);
            it.setAction(CheckUnreadService.START_TIMER);
            context.startService(it);
        } else if (INTENT_UNREAD_UPDATE.equals(action)) {
            if (listener != null) {
                int unreadCount = intent.getIntExtra("unread_count", 0);
                listener.updateUI(unreadCount);
            }
        } else if (INTENT_FAB_CHANGE.equals(action)) {
            if (listener != null) {
                listener.updateFab();
            }
        }
    }

} public class CommonUtil {

    /**
     * 如果转发数或评论数超过一万，就简写成 n万
     *
     * @param num
     * @return
     */
    public static String getNumString(int num) {
        if (num < 100000) {
            return String.valueOf(num);
        } else {
            int number = num / 10000;
            return number + "万";
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(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 static void createMessageAlertDialog(Context context, String title, String message,
                                                String negativeMessage, DialogInterface.OnClickListener negativeListener,
                                                String positiveMessage, DialogInterface.OnClickListener positiveListener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title).setMessage(message).setNegativeButton(negativeMessage, negativeListener).setPositiveButton(positiveMessage, positiveListener).setCancelable(cancelable).create().show();
    }

    public static void createMessageAlertDialog(Context context, int titleId, int messageId,
                                                int negativeMessageId, DialogInterface.OnClickListener negativeListener,
                                                int positiveMessageId, DialogInterface.OnClickListener positiveListener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(titleId).setMessage(messageId).setNegativeButton(negativeMessageId, negativeListener).setPositiveButton(positiveMessageId, positiveListener).setCancelable(cancelable).create().show();
    }

    public static void createItemAlertDialog(Context context, CharSequence[] items,
                                             DialogInterface.OnClickListener listener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setItems(items, listener).setCancelable(cancelable).create().show();
    }

    public static void createSingleChoiceAlertDialog(Context context, int itemsId, int checkedId,
                                                     DialogInterface.OnClickListener singleChoiceItemListener, String negativeMessage,
                                                     DialogInterface.OnClickListener negativeListener, String positiveMessage,
                                                     DialogInterface.OnClickListener positiveListener, boolean cancelable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setSingleChoiceItems(itemsId, checkedId, singleChoiceItemListener)
                .setNegativeButton(negativeMessage, negativeListener).setPositiveButton(positiveMessage, positiveListener)
                .setCancelable(cancelable).create().show();
    }


    /**
     * 得到地理信息
     *
     * @param context
     * @return
     */
    public static Location getLocation(Context context) {
        String provider = null;
        Location location = null;
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (providers.contains(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        } else {
            Toast.makeText(context, R.string.location_not_available, Toast.LENGTH_SHORT).show();
        }
        try {
            location = locationManager.getLastKnownLocation(provider);
        } catch (SecurityException e) {
            Toast.makeText(context, R.string.no_location_permission, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        return location;
    }

    /**
     * 获取相机最后一次拍照的url
     *
     * @param activity
     * @return
     */
    public static String getLatestCameraPicture(Activity activity) {
        String[] projection = new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA,
                MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, MediaStore.Images.ImageColumns.DATE_TAKEN,
                MediaStore.Images.ImageColumns.MIME_TYPE};
        final Cursor cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null,
                MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
        if (cursor.moveToFirst()) {
            String path = cursor.getString(1);
            return path;
        }
        return null;
    }

    /**
     * 显示Toast
     *
     * @param context
     * @param message
     */
    public static void showToast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    /**
     * @param context
     * @param milliseconds 震动的时长，单位是毫秒
     */
    public static void setVibrator(Context context, long milliseconds) {
        Vibrator vibator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE); // 取得震动服务
        vibator.vibrate(milliseconds);
    }

    /**
     * Context context
     * long[] pattern  ：自定义震动模式 。数组中数字的含义依次是[静止时长，震动时长，静止时长，震动时长。。。]时长的单位是毫秒
     * boolean isRepeat ： 是否反复震动，如果是true，反复震动，如果是false，只震动一次
     */
    public static void setVibrator(Context context, long[] pattern, boolean isRepeat) {
        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        vib.vibrate(pattern, isRepeat ? 1 : -1);
    }

    /**
     * 发布通知
     *
     * @param context
     * @param titleId
     * @param contentId
     * @param drawableId icon资源文件
     * @param cancelable
     */
    public static void showNotification(Context context, int titleId, int contentId, int drawableId, boolean cancelable) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(context.getString(titleId));
        builder.setContentText(context.getString(contentId));
        builder.setSmallIcon(drawableId);
        builder.setAutoCancel(cancelable);
        Notification mNotification = builder.build();
        notificationManager.notify(0, mNotification);
        if (SharePrefUtil.getBoolean(context, "vibrate_feedback", true)) {
            setVibrator(context, 300);
        }
    }

    /**
     * 显示Snackbar
     *
     * @param v
     * @param text
     * @param backgroundColor
     */
    public static void showSnackbar(View v, int text, int backgroundColor) {
        Snackbar sb = Snackbar.make(v, text, Snackbar.LENGTH_SHORT);
        sb.getView().setBackgroundColor(backgroundColor);
        sb.show();
    }

    public static void showSnackbar(View v, int text) {
        Snackbar.make(v, text, Snackbar.LENGTH_SHORT).show();
    }

    public static void showSnackbar(View v, int text, int backgroundColor, int length, int actionText, View.OnClickListener listener) {
        Snackbar sb = Snackbar.make(v, text, length).setAction(actionText, listener);
        sb.getView().setBackgroundColor(backgroundColor);
        sb.show();
    }

    public static void showPopupMenu(Context context, View v, int resId, PopupMenu.OnMenuItemClickListener listener) {
        PopupMenu mPopupMenu = new PopupMenu(context, v);
        mPopupMenu.getMenuInflater().inflate(resId, mPopupMenu.getMenu());
        mPopupMenu.setOnMenuItemClickListener(listener);
        mPopupMenu.show();
    }

    /**
     * 显示ProgressDialog
     *
     * @param context
     * @param stringResId
     * @param cancelable
     */
    public static ProgressDialog showProgressDialog(Context context, int stringResId, boolean cancelable) {
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage(context.getResources().getString(stringResId));
        progressDialog.setCancelable(cancelable);
        progressDialog.show();
        return progressDialog;
    }

    /**
     * 把文本复制到粘贴板上
     *
     * @param context
     * @param text
     */
    public static void copyToClipboard(Context context, String text) {
        ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clip.setText(text); // 复制
    }

    /**
     * @param context
     * @param status
     */
    public static void shareWeibo(Context context, Status status) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        String title = context.getString(R.string.share_title);
        title = String.format(title, status.getUser().getScreen_name());
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        //设置分享的内容
        intent.putExtra(Intent.EXTRA_TEXT, status.getText());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
    }

    /**
     * 获取当前应用的版本号
     *
     * @param context
     * @return
     * @throws Exception
     */
    public static String getVersionName(Context context) {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void openInBrowser(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        context.startActivity(intent);
    }

} public class LogUtils {
	/** 日志输出级别NONE */

	public static final int LEVEL_NONE = 0;

	/** 日志输出级别V */

	public static final int LEVEL_VERBOSE = 1;

	/** 日志输出级别D */

	public static final int LEVEL_DEBUG = 2;

	/** 日志输出级别I */

	public static final int LEVEL_INFO = 3;

	/** 日志输出级别W */

	public static final int LEVEL_WARN = 4;

	/** 日志输出级别E */

	public static final int LEVEL_ERROR = 5;



	/** 日志输出时的TAG */

	private static String mTag = "koku";

	/** 是否允许输出log */

	private static int mDebuggable = LEVEL_ERROR;



	/** 用于记时的变量 */

	private static long mTimestamp = 0;





	/** 以级别为 d 的形式输出LOG */

	public static void v(String msg) {

		if (mDebuggable >= LEVEL_VERBOSE) {

			Log.v(mTag, msg);

		}

	}



	/** 以级别为 d 的形式输出LOG */

	public static void d(String msg) {

		if (mDebuggable >= LEVEL_DEBUG) {

			Log.d(mTag, msg);

		}

	}



	/** 以级别为 i 的形式输出LOG */

	public static void i(String msg) {

		if (mDebuggable >= LEVEL_INFO) {

			Log.i(mTag, msg);

		}

	}



	/** 以级别为 w 的形式输出LOG */

	public static void w(String msg) {

		if (mDebuggable >= LEVEL_WARN) {

			Log.w(mTag, msg);

		}

	}



	/** 以级别为 w 的形式输出Throwable */

	public static void w(Throwable tr) {

		if (mDebuggable >= LEVEL_WARN) {

			Log.w(mTag, "", tr);

		}

	}



	/** 以级别为 w 的形式输出LOG信息和Throwable */

	public static void w(String msg, Throwable tr) {

		if (mDebuggable >= LEVEL_WARN && null != msg) {

			Log.w(mTag, msg, tr);

		}

	}



	/** 以级别为 e 的形式输出LOG */

	public static void e(String msg) {

		if (mDebuggable >= LEVEL_ERROR) {

			Log.e(mTag, msg);

		}

	}



	/** 以级别为 e 的形式输出Throwable */

	public static void e(Throwable tr) {

		if (mDebuggable >= LEVEL_ERROR) {

			Log.e(mTag, "", tr);

		}

	}


	/** 以级别为 e 的形式输出LOG信息和Throwable */

	public static void e(String msg, Throwable tr) {

		if (mDebuggable >= LEVEL_ERROR && null != msg) {

			Log.e(mTag, msg, tr);

		}

	}


	/** 以级别为 e 的形式输出msg信息,附带时间戳，用于输出一个时间段结束点* @param msg 需要输出的msg */

	public static void elapsed(String msg) {

		long currentTime = System.currentTimeMillis();

		long elapsedTime = currentTime - mTimestamp;

		mTimestamp = currentTime;

		e("[Elapsed：" + elapsedTime + "]" + msg);

	}




} public class SharePrefUtil {

	private static String tag = SharePrefUtil.class.getSimpleName();
	private static SharedPreferences sp;
	private static final String SP_NAME = "config";

	/**
	 * 保存布尔值
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveBoolean(Context context, String key, boolean value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putBoolean(key, value).commit();
	}

	/**
	 * 保存字符串
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveString(Context context, String key, String value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putString(key, value).commit();

	}

	public static void clear(Context context) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().clear().commit();
	}

	/**
	 * 保存long型
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveLong(Context context, String key, long value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putLong(key, value).commit();
	}

	public static void saveStringSet(Context context, String key,
			Set<String> value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putStringSet(key, value).commit();
	}

	public static Set<String> getStringSet(Context context, String key,
			Set<String> defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getStringSet(key, defValue);
	}

	/**
	 * 保存int型
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveInt(Context context, String key, int value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putInt(key, value).commit();
	}

	/**
	 * 保存float型
	 * 
	 * @param context
	 * @param key
	 * @param value
	 */
	public static void saveFloat(Context context, String key, float value) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		sp.edit().putFloat(key, value).commit();
	}

	/**
	 * 获取字符值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static String getString(Context context, String key, String defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getString(key, defValue);
	}

	/**
	 * 获取int值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static int getInt(Context context, String key, int defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getInt(key, defValue);
	}

	/**
	 * 获取long值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static long getLong(Context context, String key, long defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getLong(key, defValue);
	}

	/**
	 * 获取float值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static float getFloat(Context context, String key, float defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getFloat(key, defValue);
	}

	/**
	 * 获取布尔值
	 * 
	 * @param context
	 * @param key
	 * @param defValue
	 * @return
	 */
	public static boolean getBoolean(Context context, String key,
			boolean defValue) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		return sp.getBoolean(key, defValue);
	}

	/**
	 * 将对象进行base64编码后保存到SharePref中
	 * 
	 * @param context
	 * @param key
	 * @param object
	 */
	public static void saveObj(Context context, String key, Object object) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			// 将对象的转为base64码
			String objBase64 = new String(Base64.encode(baos.toByteArray(),
					Base64.DEFAULT));

			sp.edit().putString(key, objBase64).commit();
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将SharePref中经过base64编码的对象读取出来
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	public static Object getObj(Context context, String key) {
		if (sp == null)
			sp = context.getSharedPreferences(SP_NAME, 0);
		String objBase64 = sp.getString(key, null);
		if (TextUtils.isEmpty(objBase64))
			return null;

		// 对Base64格式的字符串进行解码
		byte[] base64Bytes = Base64
				.decode(objBase64.getBytes(), Base64.DEFAULT);
		ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);

		ObjectInputStream ois;
		Object obj = null;
		try {
			ois = new ObjectInputStream(bais);
			obj = (Object) ois.readObject();
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

} public class AboutTextView extends LinearLayout {

    private TextView tv_title;
    private TextView tv_content;

    public AboutTextView(Context context) {
        this(context, null);
    }

    public AboutTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.AboutTextView);
        String title = a.getString(R.styleable.AboutTextView_subject);
        String content = a.getString(R.styleable.AboutTextView_content);
        initView(context, title, content);
        a.recycle();
    }

    private void initView(Context context, String title, String content) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_about_item, this);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_content = (TextView) view.findViewById(R.id.tv_content);
        tv_title.setText(title);
        tv_content.setText(content);
    }

    public void setTitle(String title) {
        tv_title.setText(title);
    }

    public void setContent(String content) {
        tv_content.setText(content);
    }

} public class DoubleTextSettingsView extends LinearLayout {

    private CheckBox mCheckBox;

    public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener){
        mCheckBox.setOnCheckedChangeListener(listener);
    }

    public void setChecked(boolean isChecked){
        mCheckBox.setChecked(isChecked);
    }

    public DoubleTextSettingsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.DoubleTextSettingsView);
        String title = a.getString(R.styleable.DoubleTextSettingsView_double_text_setting_subject);
        String content = a.getString(R.styleable.DoubleTextSettingsView_double_text_setting_content);
        initView(context, title,content);
        a.recycle();
    }

    private void initView(Context context, String title,String content) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_double_text_settings_item,this);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
        mCheckBox = (CheckBox) view.findViewById(R.id.mCheckBox);
        tv_title.setText(title);
        tv_content.setText(content);
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mCheckBox.setChecked(!mCheckBox.isChecked());
            }
        });
    }

    public DoubleTextSettingsView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DoubleTextSettingsView(Context context) {
        this(context, null);
    }


} public class SettingsView extends LinearLayout {

    private CheckBox mCheckBox;

    public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener){
        mCheckBox.setOnCheckedChangeListener(listener);
    }

    public void setChecked(boolean isChecked){
        mCheckBox.setChecked(isChecked);
    }

    public SettingsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SettingsView);
        String title = a.getString(R.styleable.SettingsView_setting_subject);
        initView(context, title);
        a.recycle();
    }

    private void initView(Context context, String title) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_settings_item,this);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        mCheckBox = (CheckBox) view.findViewById(R.id.mCheckBox);
        tv_title.setText(title);
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mCheckBox.setChecked(!mCheckBox.isChecked());
            }
        });
    }


    public SettingsView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SettingsView(Context context) {
        this(context, null);
    }




}
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.CompoundButton;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yuqirong.koku.R;
import com.yuqirong.koku.activity.AuthorizeActivity;
import com.yuqirong.koku.activity.PublishActivity;
import com.yuqirong.koku.constant.AppConstant;
import com.yuqirong.koku.receiver.RefreshWeiboTimelineReceiver;
import com.yuqirong.koku.util.CommonUtil;
import com.yuqirong.koku.util.LogUtils;
import com.yuqirong.koku.util.SharePrefUtil;
import com.yuqirong.koku.view.AboutTextView;
import com.yuqirong.koku.view.DoubleTextSettingsView;
import com.yuqirong.koku.view.SettingsView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
package com.yuqirong.koku.fragment;





/**
 * Created by Administrator on 2015/11/4.
 */
public class SettingsFragment extends BaseFragment {

    private SettingsView sv_browser;
    private SettingsView sv_hd_pic;
    private DoubleTextSettingsView dsv_vibrator;