public abstract class BaseRcvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public ItemOnClickListener mItemOnClickListener;

    public interface ItemOnClickListener {
        void onItemClick(View view, int position);
    }

    public void setItemOnClickListener(ItemOnClickListener listener) {
        this.mItemOnClickListener = listener;
    }
} public class RcvHourlyAdapter extends BaseRcvAdapter {

    private static final String TAG = "hourly";
    private ArrayList<ItemHourly> mDataList = new ArrayList<>();

    public RcvHourlyAdapter(ArrayList<ItemHourly> dataList) {
        mDataList = dataList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//        View vItem = View.inflate(parent.getContext(), R.layout.item_rcv_hourly, null);
        View vItem = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_rcv_hourly, parent, false);
//        if (vItem.getLayoutParams ().width == RecyclerView.LayoutParams.MATCH_PARENT)
        vItem.getLayoutParams().width = (parent.getWidth() - 21) / 7;
        return new HourlyViewHolder(vItem);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final HourlyViewHolder viewHolder = (HourlyViewHolder) holder;
        viewHolder.mTvTimeHourly.setText(mDataList.get(position).getTimeHourly());
        viewHolder.mTempHourly.setText(mDataList.get(position).getTempHourly());
        Log.d(TAG, "onBindViewHolder: " + ViewUtil.getHourlyWeatherCode(
                mDataList.get(position).getWeatherCodeHourly()));
        if (mDataList.get(position).getWeatherCodeHourly() != null && !mDataList.get(position).getWeatherCodeHourly().equals("")) {
            viewHolder.mIvWeatherHourly.setImageResource(ViewUtil.getImageResource(mDataList.get(position).getWeatherCodeHourly()));
        }
        if (position == 0) {
            viewHolder.mTvAqiHourly.setText("AQI " + mDataList.get(position).getAqiHourly());
        } else {
            viewHolder.mTvAqiHourly.setText(mDataList.get(position).getAqiHourly());
        }
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    class HourlyViewHolder extends RecyclerView.ViewHolder {

        private TextView mTvTimeHourly;
        private ImageView mIvWeatherHourly;
        private TextView mTempHourly;
        private TextView mTvAqiHourly;

        public HourlyViewHolder(View itemView) {
            super(itemView);
            mTvTimeHourly = (TextView) itemView.findViewById(R.id.tv_time_hourly);
            mIvWeatherHourly = (ImageView) itemView.findViewById(R.id.iv_weather_hourly);
            mTempHourly = (TextView) itemView.findViewById(R.id.tv_temp_hourly);
            mTvAqiHourly = (TextView) itemView.findViewById(R.id.tv_aqi_hourly);
        }
    }
} public class RcvWeeklyAdapter extends BaseRcvAdapter {

    private ArrayList<ItemWeekly> mDataList = new ArrayList<>();

    public RcvWeeklyAdapter(ArrayList<ItemWeekly> dataList) {
        mDataList = dataList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.item_rcv_weekly, null);
        return new WeeklyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final WeeklyViewHolder viewHolder = (WeeklyViewHolder) holder;
        if (position == 0) {
            viewHolder.mTvDayWeekly.setText("今天");
        } else if (position == 1) {
            viewHolder.mTvDayWeekly.setText("明天");
        } else if (position == 2) {
            viewHolder.mTvDayWeekly.setText("后天");
        } else {
            viewHolder.mTvDayWeekly.setText(OtherUtil.getWeekOther(position));
        }

        viewHolder.mTvWeatherWeekly.setText(mDataList.get(position).getWeatherWeekly());
        if (mDataList.get(position).getWeatherCodeWeekly() != null && !mDataList.get(position).getWeatherCodeWeekly().equals("")) {
            viewHolder.mIvWeatherWeekly.setImageResource(ViewUtil.getImageResource(mDataList.get(position).getWeatherCodeWeekly()));
        }
        if (position == 0) {
            viewHolder.mTvAqiWeekly.setText("AQI " + mDataList.get(position).getAqiWeekly());
        } else {
            viewHolder.mTvAqiWeekly.setText(mDataList.get(position).getAqiWeekly());
        }
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    class WeeklyViewHolder extends RecyclerView.ViewHolder {

        private TextView mTvDayWeekly;
        private ImageView mIvWeatherWeekly;
        private TextView mTvWeatherWeekly;
        private TextView mTvAqiWeekly;

        public WeeklyViewHolder(View itemView) {
            super(itemView);
            mTvDayWeekly = (TextView) itemView.findViewById(R.id.tv_day_weekly);
            mIvWeatherWeekly = (ImageView) itemView.findViewById(R.id.iv_weather_weekly);
            mTvWeatherWeekly = (TextView) itemView.findViewById(R.id.tv_weather_weekly);
            mTvAqiWeekly = (TextView) itemView.findViewById(R.id.tv_aqi_weekly);
        }
    }
} public class County {
    private int id;
    private String countyName;
    private String countyCode;
    private String mLongitude;
    private String mLatitude;

    private int cityId;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountyName() {
        return countyName;
    }
    public void setCountyName(String countyName) {
        this.countyName = countyName;
    }
    public String getCountyCode() {
        return countyCode;
    }
    public void setCountyCode(String countyCode) {
        this.countyCode = countyCode;
    }
    public int getCityId() {
        return cityId;
    }
    public void setCityId(int cityId) {
        this.cityId = cityId;
    }

    public String getLongitude() {
        return mLongitude;
    }

    public void setLongitude(String longitude) {
        mLongitude = longitude;
    }

    public String getLatitude() {
        return mLatitude;
    }

    public void setLatitude(String latitude) {
        mLatitude = latitude;
    }
} public class DeerWeatherDB {

    public static final String DB_NAME = "deer_weather";

    public static final int VERSION = 2;
    private static DeerWeatherDB deerWeatherDB;
    private SQLiteDatabase db;


    private DeerWeatherDB(Context context) {
        DeerWeatherOpenHelper dbHelper = new DeerWeatherOpenHelper(context, DB_NAME, null, VERSION);
        db = dbHelper.getWritableDatabase();
    }

    public synchronized static DeerWeatherDB getInstance(Context context) {
        if (deerWeatherDB == null) {
            deerWeatherDB = new DeerWeatherDB(context);
        }
        return deerWeatherDB;
    }

    public void saveProvince(Province province) {
        if (province != null) {
            ContentValues values = new ContentValues();
            values.put("province_name", province.getProvinceName());
            values.put("province_code", province.getProvinceCode());
            db.insert("Province", null, values);
        }
    }

    public List<Province> loadProvinces() {
        List<Province> list = new ArrayList<>();
        Cursor cursor = db.query("Province", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Province province = new Province();
                province.setId(cursor.getInt(cursor.getColumnIndex("id")));
                province.setProvinceName(cursor.getString(cursor
                        .getColumnIndex("province_name")));
                province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code")));
                list.add(province);
            } while (cursor.moveToNext());
        }
        return list;
    }

    public void saveCity(City city) {
        if (city != null) {
            ContentValues values = new ContentValues();
            values.put("city_name", city.getCityName());
            values.put("city_code", city.getCityCode());
            values.put("province_id", city.getProvinceId());
            db.insert("City", null, values);
        }
    }


    public List<City> loadCities(int provinceId) {
        List<City> list = new ArrayList<>();
        Cursor cursor = db.query("City", null, "province_id = ?",
                new String[]{String.valueOf(provinceId)}, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                City city = new City();
                city.setId(cursor.getInt(cursor.getColumnIndex("id")));
                city.setCityName(cursor.getString(cursor
                        .getColumnIndex("city_name")));
                city.setCityCode(cursor.getString(cursor
                        .getColumnIndex("city_code")));
                city.setProvinceId(provinceId);
                list.add(city);
            } while (cursor.moveToNext());
        }
        return list;
    }


    public void saveCounty(County county) {
        if (county != null) {
            ContentValues values = new ContentValues();
            values.put("county_name", county.getCountyName());
            values.put("county_code", county.getCountyCode());
            values.put("city_id", county.getCityId());
            db.insert("County", null, values);
        }
    }

    public List<County> loadCounties(int cityId) {
        List<County> list = new ArrayList<>();
        Cursor cursor = db.query("County", null, "city_id = ?",
                new String[]{String.valueOf(cityId)}, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                County county = new County();
                county.setId(cursor.getInt(cursor.getColumnIndex("id")));
                county.setCountyName(cursor.getString(cursor
                        .getColumnIndex("county_name")));
                county.setCountyCode(cursor.getString(cursor
                        .getColumnIndex("county_code")));
                county.setCityId(cityId);
                list.add(county);
            } while (cursor.moveToNext());
        }
        return list;
    }


    public void saveMyCounty(County mCounty) {
        if (mCounty != null) {
            ContentValues values = new ContentValues();
            values.put("county_name", mCounty.getCountyName());
            values.put("county_code", mCounty.getCountyCode());
            values.put("longitude", mCounty.getLongitude());
            values.put("latitude", mCounty.getLatitude());
            db.insert("MyCounty", null, values);
        }
    }

    public boolean searchMyCounty(County mCounty) {
        Cursor cursor = db.query("MyCounty", null, null, null, null, null, null);
        int flag = 0;
        if (cursor.moveToFirst()) {
            do {
                if (mCounty.getCountyName().equals(cursor.getString(cursor.getColumnIndex("county_name"))))
                    return false;
            } while (cursor.moveToNext());
        }
        return true;
    }

    public List<County> loadMyCounties() {
        List<County> list = new ArrayList<>();
        Cursor cursor = db.query("MyCounty", null, null,
                null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                County county = new County();
                county.setId(cursor.getInt(cursor.getColumnIndex("id")));
                county.setCountyName(cursor.getString(cursor
                        .getColumnIndex("county_name")));
                county.setCountyCode(cursor.getString(cursor
                        .getColumnIndex("county_code")));
                county.setLongitude(cursor.getString(cursor
                        .getColumnIndex("longitude")));
                county.setLatitude(cursor.getString(cursor
                        .getColumnIndex("latitude")));
                list.add(county);
            } while (cursor.moveToNext());
        }
        return list;
    }

    public void deleteMyCounties(String mCountyName) {
        db.delete("MyCounty", "county_name == ?", new String[]{mCountyName});
    }

//    public void updateMyCounties(String mCountyName, String longitude, String latitude) {
//        ContentValues values = new ContentValues();
//        values.put("longitude", longitude);
//        values.put("latitude", latitude);
//        db.update("MyCounty", values, "county_name = ?", new String[]{mCountyName});
//    }

    public void saveMyTheme(ItemTheme itemTheme) {
        if (itemTheme != null) {
            ContentValues values = new ContentValues();
            values.put("color_0", itemTheme.getColors().get(0));
            values.put("color_1", itemTheme.getColors().get(1));
            values.put("color_2", itemTheme.getColors().get(2));
            values.put("color_3", itemTheme.getColors().get(3));
            values.put("color_4", itemTheme.getColors().get(4));
            values.put("color_5", itemTheme.getColors().get(5));
            values.put("color_6", itemTheme.getColors().get(6));

            if (itemTheme.getPictureUrls() != null) {
                values.put("picture_url_0", itemTheme.getPictureUrls().get(0));
                values.put("picture_url_1", itemTheme.getPictureUrls().get(1));
                values.put("picture_url_2", itemTheme.getPictureUrls().get(2));
                values.put("picture_url_3", itemTheme.getPictureUrls().get(3));
                values.put("picture_url_4", itemTheme.getPictureUrls().get(4));
                values.put("picture_url_5", itemTheme.getPictureUrls().get(5));
                values.put("picture_url_6", itemTheme.getPictureUrls().get(6));
            }
            db.insert("MyTheme", null, values);
        }
    }

    public List<ItemTheme> loadMyTheme() {
        List<ItemTheme> list = new ArrayList<>();
        Cursor cursor = db.query("MyTheme", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {

                Integer id = cursor.getInt(cursor.getColumnIndex("id"));

                Integer color0 = cursor.getInt(cursor.getColumnIndex("color_0"));
                Integer color1 = cursor.getInt(cursor.getColumnIndex("color_1"));
                Integer color2 = cursor.getInt(cursor.getColumnIndex("color_2"));
                Integer color3 = cursor.getInt(cursor.getColumnIndex("color_3"));
                Integer color4 = cursor.getInt(cursor.getColumnIndex("color_4"));
                Integer color5 = cursor.getInt(cursor.getColumnIndex("color_5"));
                Integer color6 = cursor.getInt(cursor.getColumnIndex("color_6"));
                ArrayList<Integer> colors = new ArrayList<>();
                colors.add(color0);
                colors.add(color1);
                colors.add(color2);
                colors.add(color3);
                colors.add(color4);
                colors.add(color5);
                colors.add(color6);

                String pictureUrl0 = cursor.getString(cursor.getColumnIndex("picture_url_0"));
                String pictureUrl1 = cursor.getString(cursor.getColumnIndex("picture_url_1"));
                String pictureUrl2 = cursor.getString(cursor.getColumnIndex("picture_url_2"));
                String pictureUrl3 = cursor.getString(cursor.getColumnIndex("picture_url_3"));
                String pictureUrl4 = cursor.getString(cursor.getColumnIndex("picture_url_4"));
                String pictureUrl5 = cursor.getString(cursor.getColumnIndex("picture_url_5"));
                String pictureUrl6 = cursor.getString(cursor.getColumnIndex("picture_url_6"));
                ArrayList<String> pictureUrls = new ArrayList<>();
                pictureUrls.add(pictureUrl0);
                pictureUrls.add(pictureUrl1);
                pictureUrls.add(pictureUrl2);
                pictureUrls.add(pictureUrl3);
                pictureUrls.add(pictureUrl4);
                pictureUrls.add(pictureUrl5);
                pictureUrls.add(pictureUrl6);

                ItemTheme itemTheme = new ItemTheme();
                itemTheme.setId(id);
                itemTheme.setColors(colors);
                itemTheme.setPictureUrls(pictureUrls);
                list.add(itemTheme);
            } while (cursor.moveToNext());
        }
        return list;
    }

    public void updateMyTheme(ItemTheme itemTheme) {
        ContentValues values = new ContentValues();
        values.put("color_0", itemTheme.getColors().get(0));
        values.put("color_1", itemTheme.getColors().get(1));
        values.put("color_2", itemTheme.getColors().get(2));
        values.put("color_3", itemTheme.getColors().get(3));
        values.put("color_4", itemTheme.getColors().get(4));
        values.put("color_5", itemTheme.getColors().get(5));
        values.put("color_6", itemTheme.getColors().get(6));

        if (itemTheme.getPictureUrls() != null) {
            values.put("picture_url_0", itemTheme.getPictureUrls().get(0));
            values.put("picture_url_1", itemTheme.getPictureUrls().get(1));
            values.put("picture_url_2", itemTheme.getPictureUrls().get(2));
            values.put("picture_url_3", itemTheme.getPictureUrls().get(3));
            values.put("picture_url_4", itemTheme.getPictureUrls().get(4));
            values.put("picture_url_5", itemTheme.getPictureUrls().get(5));
            values.put("picture_url_6", itemTheme.getPictureUrls().get(6));
        }
        db.update("MyTheme", values, "id = ?", new String[]{String.valueOf(itemTheme.getId())});
    }
} public class ItemHourly {
    private String mDescription;
    private String mTimeHourly;
    private String mWeatherCodeHourly;
    private String mTempHourly;
    private String mAqiHourly;
    private String mPm25Hourly;

    public String getDescription() {
        return mDescription;
    }

    public void setDescription(String description) {
        mDescription = description;
    }

    public String getTimeHourly() {
        return mTimeHourly;
    }

    public void setTimeHourly(String timeHourly) {
        mTimeHourly = timeHourly;
    }

    public String getWeatherCodeHourly() {
        return mWeatherCodeHourly;
    }

    public void setWeatherCodeHourly(String weatherCodeHourly) {
        mWeatherCodeHourly = weatherCodeHourly;
    }

    public String getTempHourly() {
        return mTempHourly;
    }

    public void setTempHourly(String tempHourly) {
        mTempHourly = tempHourly;
    }

    public String getAqiHourly() {
        return mAqiHourly;
    }

    public void setAqiHourly(String aqiHourly) {
        mAqiHourly = aqiHourly;
    }

    public String getPm25Hourly() {
        return mPm25Hourly;
    }

    public void setPm25Hourly(String pm25Hourly) {
        mPm25Hourly = pm25Hourly;
    }
} public class ItemTheme {
    private Integer mId;
    private ArrayList<Integer> mColors;
    private ArrayList<String> mPictureUrls;
    private boolean mSelected = false;

    public Integer getId() {
        return mId;
    }

    public void setId(Integer id) {
        mId = id;
    }

    public ArrayList<Integer> getColors() {
        return mColors;
    }

    public void setColors(ArrayList<Integer> colors) {
        mColors = colors;
    }

    public ArrayList<String> getPictureUrls() {
        return mPictureUrls;
    }

    public void setPictureUrls(ArrayList<String> pictureUrls) {
        mPictureUrls = pictureUrls;
    }

    public boolean isSelected() {
        return mSelected;
    }

    public void setSelected(boolean selected) {
        mSelected = selected;
    }
} public class ItemWeekly {

    private String mDayWeekly;
    private String mWeatherCodeWeekly;
    private String mWeatherWeekly;
    private String mAqiWeekly;
    private String mMaxTempWeekly;
    private String mMinTempWeekly;


    public String getMinTempWeekly() {
        return mMinTempWeekly;
    }

    public void setMinTempWeekly(String minTempWeekly) {
        mMinTempWeekly = minTempWeekly;
    }

    public String getMaxTempWeekly() {
        return mMaxTempWeekly;
    }

    public void setMaxTempWeekly(String maxTempWeekly) {
        mMaxTempWeekly = maxTempWeekly;
    }

    public String getWeatherCodeWeekly() {
        return mWeatherCodeWeekly;
    }

    public void setWeatherCodeWeekly(String weatherCodeWeekly) {
        mWeatherCodeWeekly = weatherCodeWeekly;
    }

    public String getWeatherWeekly() {
        return mWeatherWeekly;
    }

    public void setWeatherWeekly(String weatherWeekly) {
        mWeatherWeekly = weatherWeekly;
    }

    public String getDayWeekly() {
        return mDayWeekly;
    }

    public void setDayWeekly(String dayWeekly) {
        mDayWeekly = dayWeekly;
    }

    public String getAqiWeekly() {
        return mAqiWeekly;
    }

    public void setAqiWeekly(String aqiWeekly) {
        mAqiWeekly = aqiWeekly;
    }
} public class AutoUpdateService extends Service {

    public static final String CHANGE_ACTION = "com.android.CHANGE";
    public static final String CHANGE_TIME_ACTION = "com.android.CHANGE_TIME";
    private static final String TAG = "time_send";

    public AutoUpdateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);

        // 发时钟广播
        int anMinute = 60 * 1000;
        long triggerAtTime2 = SystemClock.elapsedRealtime() + anMinute;
        Intent intent2 = new Intent(CHANGE_TIME_ACTION);
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 0, intent2, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime2, pendingIntent2);
        Log.d(TAG, "onStartCommand: " + "send");

        // 发天气广播
        int anHour = 60 * 60 * 1000;
        long triggerAtTime3 = SystemClock.elapsedRealtime() + anHour;
        Intent intent3 = new Intent(CHANGE_ACTION);
        PendingIntent pendingIntent3 = PendingIntent.getBroadcast(this, 0, intent3, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime3, pendingIntent3);

        return super.onStartCommand(intent, flags, startId);
    }
} public interface HttpCallBackListener {
    void onFinish(String response);
    void onError(Exception e);
} public class HttpUtil {
    public static void sendHttpRequest(final String address, final HttpCallBackListener listener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    //String address2 = URLEncoder.encode(address, "UTF-8");
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    //connection.setRequestProperty("Accept-Language", "zh-CN");
                    //connection.setConnectTimeout(8000);
                    //connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null){
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
} public class JSONUtility {


    private static final String TAG = "hourlyres";

    /**
     * 解析和处理文件中返回的省级数据
     */
    public synchronized static boolean handleProvincesResponse(DeerWeatherDB deerWeatherDB, String response) {
        if (!TextUtils.isEmpty(response)) {
            String[] allProvinces = response.split(",");
            if (allProvinces.length > 0) {
                for (String p : allProvinces) {
                    String[] array = p.split("\\|");
                    Province province = new Province();
                    province.setProvinceCode(array[0]);
                    province.setProvinceName(array[1]);
                    deerWeatherDB.saveProvince(province);
                }
                return true;
            }
        }
        return false;
    }

    public static boolean handleCitiesResponse(DeerWeatherDB deerWeatherDB, String response, int provinceId) {
        if (!TextUtils.isEmpty(response)) {
            String[] allCities = response.split(",");
            if (allCities.length > 0) {
                for (String c : allCities) {
                    String[] array = c.split("\\|");
                    City city = new City();
                    city.setCityCode(array[0]);
                    city.setCityName(array[1]);
                    city.setProvinceId(provinceId);
                    deerWeatherDB.saveCity(city);
                }
                return true;
            }
        }
        return false;
    }


    public static boolean handleCountiesResponse(DeerWeatherDB deerWeatherDB,
                                                 String response, int cityId) {
        if (!TextUtils.isEmpty(response)) {
            String[] allCounties = response.split(",");
            if (allCounties.length > 0) {
                for (String c : allCounties) {
                    String[] array = c.split("\\|");
                    County county = new County();
                    county.setCountyCode(array[0]);
                    county.setCountyName(array[1]);
                    county.setCityId(cityId);
                    deerWeatherDB.saveCounty(county);
                }
                return true;
            }
        }
        return false;
    }


    public static String handleNameByLocation(Context context, String response) {
        try {
            String subResponse = response.substring(29, response.length() - 1);
            JSONObject jsonObject = new JSONObject(subResponse);
            if (jsonObject.get("status").toString().equals("0")) {
                JSONObject addressComponent = jsonObject.getJSONObject("result").getJSONObject("addressComponent");
//                String address = addressComponent.getString("city");
//                if (address.equals("上海市") || address.equals("北京市") || address.equals("天津市") || address.equals("重庆市"))
                String address = addressComponent.getString("district");
                address = address.substring(0, address.length() - 1);
                return address;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析服务器返回的JSON数据，并将解析出的数据存储到本地。
     */
    public static void handleWeatherResponse(Context context, String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            Log.d(TAG, "handleWeatherResponse: " + response);
            JSONArray heWeather = jsonObject.getJSONArray("HeWeather data service 3.0");
            JSONObject heWeatherData = heWeather.getJSONObject(0);
            JSONObject basic = heWeatherData.getJSONObject("basic");
            JSONArray dailyForecast = heWeatherData.getJSONArray("daily_forecast");

            JSONObject now = heWeatherData.getJSONObject("now");

            String nowWeather = now.getJSONObject("cond").getString("txt");
            String nowWeatherCode = now.getJSONObject("cond").getString("code");
            String nowTemp = now.getString("tmp");

            JSONObject todayWeather = dailyForecast.getJSONObject(0);
            String maxTempToday = todayWeather.getJSONObject("tmp").getString("max");
            String minTempToday = todayWeather.getJSONObject("tmp").getString("min");

            String countyCode = basic.getString("id");
            String countyName = basic.getString("city");
            String longitude = basic.getString("lon");
            String latitude = basic.getString("lat");
            String publishTime = basic.getJSONObject("update").getString("loc").substring(11, 16) + "  更新";

            String publishTimeHour = basic.getJSONObject("update").getString("loc").substring(11, 13);
            Log.d(TAG, "handleWeatherResponse: " + Integer.valueOf("01"));
            if (Integer.valueOf(publishTimeHour) > 18 || Integer.valueOf(publishTimeHour) < 6) {
                if (nowWeatherCode.equals("100") || nowWeatherCode.equals("101")) {
                    nowWeatherCode += "_n";
                }
            }

            saveWeatherInfo(context, countyCode, countyName, longitude, latitude, publishTime,
                    nowTemp, nowWeather, nowWeatherCode, maxTempToday, minTempToday);

            JSONObject suggestionJSON = heWeatherData.getJSONObject("suggestion");
            String comfBrf = suggestionJSON.getJSONObject("comf").getString("brf");
            String comfTxt = suggestionJSON.getJSONObject("comf").getString("txt");
            String drsgBrf = suggestionJSON.getJSONObject("drsg").getString("brf");
            String drsgTxt = suggestionJSON.getJSONObject("drsg").getString("txt");
            String fluBre = suggestionJSON.getJSONObject("flu").getString("brf");
            String fluTxt = suggestionJSON.getJSONObject("flu").getString("txt");
            String uvBrf = suggestionJSON.getJSONObject("uv").getString("brf");
            String uvTxt = suggestionJSON.getJSONObject("uv").getString("txt");
            String sportBrf = suggestionJSON.getJSONObject("sport").getString("brf");
            String sportTxt = suggestionJSON.getJSONObject("sport").getString("txt");
            String cwBrf = suggestionJSON.getJSONObject("cw").getString("brf");
            String cwTxt = suggestionJSON.getJSONObject("cw").getString("txt");

            saveSuggestion(context, comfBrf, comfTxt, drsgBrf, drsgTxt,
                    fluBre, fluTxt, uvBrf, uvTxt, sportBrf, sportTxt, cwBrf, cwTxt);

            String str = "--";
            saveAqi(context, str, str, str, str, str, str, str, str);
            if (heWeatherData.getJSONObject("aqi") != null) {
                JSONObject aqiJSON = heWeatherData.getJSONObject("aqi");
                JSONObject aqiContent = aqiJSON.getJSONObject("city");
                String aqi = aqiContent.getString("aqi");
                String qlty = aqiContent.getString("qlty");
                String pm25 = aqiContent.getString("pm25");
                String pm10 = aqiContent.getString("pm10");
                String no2 = aqiContent.getString("no2");
                String so2 = aqiContent.getString("so2");
                String co = aqiContent.getString("co");
                String o3 = aqiContent.getString("o3");
                saveAqi(context, aqi, qlty, pm25, pm10, no2, so2, co, o3);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static void handleWeatherHourly(Context context, String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONObject hourly = jsonObject.getJSONObject("result").getJSONObject("hourly");
            JSONObject daily = jsonObject.getJSONObject("result").getJSONObject("daily");
            JSONArray weatherInfoHourlyJSON = hourly.getJSONArray("skycon");
            JSONArray tempHourlyJSON = hourly.getJSONArray("temperature");
            JSONArray aqiHourlyJSON = hourly.getJSONArray("aqi");
            JSONArray pm25HourlyJSON = hourly.getJSONArray("pm25");
            JSONArray aqiWeeklyJSON = daily.getJSONArray("aqi");
            String description = hourly.getString("description");
            saveDescription(context, description);

            for (int i = 0; i < 24; i++) {
                String timeHourly = weatherInfoHourlyJSON.getJSONObject(i).getString("datetime").substring(11, 16);
                String weatherCodeHourlyRaw = weatherInfoHourlyJSON.getJSONObject(i).getString("value");
                String weatherCodeHourly = ViewUtil.getHourlyWeatherCode(weatherCodeHourlyRaw);
                String tempHourlyRaw = tempHourlyJSON.getJSONObject(i).getString("value");
                String tempHourly = tempHourlyRaw.substring(0, tempHourlyRaw.indexOf('.')) + "°";
                String aqiHourlyRaw = aqiHourlyJSON.getJSONObject(i).getString("value");
                String aqiHourly = aqiHourlyRaw.substring(0, aqiHourlyRaw.indexOf('.'));
                String pm25Hourly = pm25HourlyJSON.getJSONObject(i).getString("value");
                saveWeatherInfoHourly(context, timeHourly, tempHourly, weatherCodeHourly, aqiHourly, pm25Hourly, i);
            }

            for (int i = 0; i < 5; i++) {
                String aqiWeeklyRaw = aqiWeeklyJSON.getJSONObject(i).getString("avg");
                String aqiWeekly = aqiWeeklyRaw.substring(0, aqiWeeklyRaw.indexOf('.'));
                saveAqiWeekly(context, aqiWeekly, i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static void handleWeatherWeekly(Context context, String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray heWeather = jsonObject.getJSONArray("HeWeather data service 3.0");
            JSONObject heWeatherData = heWeather.getJSONObject(0);
            JSONArray dailyForecast = heWeatherData.getJSONArray("daily_forecast");
            int i;
            for (i = 0; i < 7; i++) {
                JSONObject weatherFutureInfo = dailyForecast.getJSONObject(i);
                String minTempWeekly = weatherFutureInfo.getJSONObject("tmp").getString("min") + "°";
                String maxTempWeekly = weatherFutureInfo.getJSONObject("tmp").getString("max") + "°";
                String weatherWeekly = weatherFutureInfo.getJSONObject("cond").getString("txt_d");
                String weatherCodeFuture = weatherFutureInfo.getJSONObject("cond").getString("code_d");
                String dayFuture = weatherFutureInfo.getString("date").substring(5, 7) + "/"
                        + weatherFutureInfo.getString("date").substring(8, 10);
                saveWeatherInfoWeekly(context, minTempWeekly, maxTempWeekly,
                        weatherWeekly, weatherCodeFuture, dayFuture, i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将服务器返回的所有天气信息存储到SharedPreferences文件中。
     */
    public static void saveWeatherInfo(Context context, String countyCode, String countyName,
                                       String longitude, String latitude, String publishTime,
                                       String nowTemp, String nowWeather, String nowWeatherCode, String maxTemp, String minTemp) {

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("county_selected", true);
        editor.putString("county_code", countyCode);
        editor.putString("county_name", countyName);
        editor.putString("longitude", longitude);
        editor.putString("latitude", latitude);
        editor.putString("publish_time", publishTime);
        editor.putString("temp_now", nowTemp);
        editor.putString("weather_now", nowWeather);
        editor.putString("weather_code_now", nowWeatherCode);
        editor.putString("max_temp_today", maxTemp);
        editor.putString("min_temp_today", minTemp);

        editor.apply();
    }


    public static void saveWeatherInfoHourly(Context context, String timeHourly, String tempHourly,
                                             String weatherCodeHourly, String aqiHourly, String pm25Hourly,
                                             int i) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("county_selected", true);
        editor.putString("time_hourly" + i, timeHourly);
        editor.putString("weather_code_hourly" + i, weatherCodeHourly);
        editor.putString("temp_hourly" + i, tempHourly);
        editor.putString("aqi_hourly" + i, aqiHourly);
        editor.putString("pm25_hourly" + i, pm25Hourly);
        editor.apply();
    }

    public static void saveWeatherInfoWeekly(Context context, String minTempWeekly, String maxTempWeekly,
                                             String weatherWeekly, String weatherCodeWeekly, String dayWeekly, int i) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("county_selected", true);
        editor.putString("min_temp_weekly" + i, minTempWeekly);
        editor.putString("max_temp_weekly" + i, maxTempWeekly);
        editor.putString("weather_code_weekly" + i, weatherCodeWeekly);
        editor.putString("weather_weekly" + i, weatherWeekly);
        editor.putString("day_weekly" + i, dayWeekly);
        editor.apply();
    }

    public static void saveDescription(Context context, String description) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putString("description", description);
        editor.apply();
    }

    public static void saveAqiWeekly(Context context, String aqiWeekly, int i) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("county_selected", true);
        editor.putString("aqi_weekly" + i, aqiWeekly);
        editor.apply();
    }

    public static void saveAqi(Context context, String aqi, String qlty, String pm25,
                               String pm10, String no2, String so2, String co, String o3) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("county_selected", true);
        editor.putString("aqi_he", aqi);
        editor.putString("qlty", qlty);
        editor.putString("pm25", pm25);
        editor.putString("pm10", pm10);
        editor.putString("no2", no2);
        editor.putString("so2", so2);
        editor.putString("co", co);
        editor.putString("o3", o3);
        editor.apply();
    }


    public static void saveSuggestion(Context context, String comfB, String comfT, String drsgB, String drsgT,
                                      String fluB, String fluT, String uvB, String uvT,
                                      String sportB, String sprotT, String cwB, String cwT) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("county_selected", true);
        editor.putString("comf_b", comfB);
        editor.putString("comf_t", comfT);
        editor.putString("drsg_b", drsgB);
        editor.putString("drsg_t", drsgT);
        editor.putString("flu_b", fluB);
        editor.putString("flu_t", fluT);
        editor.putString("uv_b", uvB);
        editor.putString("uv_t", uvT);
        editor.putString("sport_b", sportB);
        editor.putString("sport_t", sprotT);
        editor.putString("cw_b", cwB);
        editor.putString("cw_t", cwT);
        editor.apply();
    }
} public class OtherUtil {

    private static final String TAG = "initit";
    private static String mWeek;
    private static String[] mAllWeek = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};

    private static SparseIntArray arrayId2Index = new SparseIntArray() {{
        append(R.id.cv_toolbar, 0);
        append(R.id.cv_temp, 1);
        append(R.id.cv_img_weather_now, 2);
        append(R.id.cv_hourly, 3);
        append(R.id.cv_weekly_info, 4);
        append(R.id.cv_weekly_chart, 5);
        append(R.id.cv_suggestion, 6);
    }};

    public static HashMap<String, String> mMapCode2Weather = new HashMap<String, String>() {
        {
            put("100", "晴");
            put("100_n", "晴");
            put("101", "多云");
            put("101_n", "多云");
            put("104", "阴");
            put("203", "风");
            put("305", "雨");
            put("313", "冻雨");
            put("400", "雪");
            put("501", "雾");
            put("502", "霾");
        }
    };

    public static String getWeatherFromCode(String code) {
        return mMapCode2Weather.get(code);
    }

    public static int getWeekToday() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        String mWeek = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        return Integer.valueOf(mWeek) - 1;
    }

    public static String getWeekOther(int futureDay) {
        return mAllWeek[(getWeekToday() + futureDay) % 7];
    }

    public static void initDatabase(Context context) {
        Log.d(TAG, "initDatabase: ");
        DeerWeatherDB mDeerWeatherDB = DeerWeatherDB.getInstance(context);
        ArrayList<Integer> colors0 = new ArrayList<Integer>() {
            {
                add(Color.argb(255, 57, 223, 255));
                add(Color.argb(255, 72, 207, 255));
                add(Color.argb(255, 87, 191, 255));
                add(Color.argb(255, 102, 175, 255));
                add(Color.argb(255, 117, 159, 255));
                add(Color.argb(255, 132, 143, 255));
                add(Color.argb(255, 147, 127, 255));
            }
        };
        ItemTheme itemTheme0 = new ItemTheme();
        itemTheme0.setColors(colors0);
        mDeerWeatherDB.saveMyTheme(itemTheme0);

        ArrayList<Integer> colors1 = new ArrayList<Integer>() {
            {
                add(-12989793);
                add(-12989793);
                add(-12989793);
                add(-12989793);
                add(-12989793);
                add(-12989793);
                add(-12989793);
            }
        };


        ItemTheme itemTheme1 = new ItemTheme();
        itemTheme1.setColors(colors1);
        mDeerWeatherDB.saveMyTheme(itemTheme1);

        ArrayList<Integer> colors2 = new ArrayList<Integer>() {
            {
                add(-5276452);
                add(-4410691);
                add(-999487);
                add(-7166055);
                add(-4948873);
                add(-6197600);
                add(-10112077);
            }
        };
        ItemTheme itemTheme2 = new ItemTheme();
        itemTheme2.setColors(colors2);
        mDeerWeatherDB.saveMyTheme(itemTheme2);
    }

    public static int getIndexFromId(int id) {
        return arrayId2Index.get(id);
    }

    public static boolean isEmpty(String str) {
        return str == null || str.equals("");
    }

    public static Uri savePic(Bitmap b) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.CHINA);

        File dirDeerWeather = new File(Environment.getExternalStorageDirectory() + "/deerweather");
        // 如果文件不存在，则创建一个新文件
        if (!dirDeerWeather.isDirectory()) {
            try {
                dirDeerWeather.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        File dirShare = new File(Environment.getExternalStorageDirectory() + "/deerweather/share");
        // 如果文件不存在，则创建一个新文件
        if (!dirShare.isDirectory()) {
            try {
                dirShare.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String timeNow = sdf.format(new Date());
        File outfile = new File(Environment.getExternalStorageDirectory() + "/deerweather/share/" + timeNow + ".png");
        // 如果文件不存在，则创建一个新文件
        try {
            if (outfile.exists()) {
                outfile.delete();
            }
            outfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri fUri = Uri.fromFile(outfile);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outfile.getPath());
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fUri;
    }
} public class SharedPreferenceUtil {
    private SharedPreferences mPrefs;
    private SharedPreferences.Editor mEditor;

    public SharedPreferenceUtil(Context context) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        mEditor = mPrefs.edit();
    }

    public void apply() {
        mEditor.apply();
    }

    public void setTempNow(String tempNow) {
        mEditor.putString("temp_now", tempNow);
    }

    public String getTempNow() {
        return mPrefs.getString("temp_now", "--");
    }

    public void setPublishTime(String publishTime) {
        mEditor.putString("publish_time", publishTime);
    }

    public String getPublishTime() {
        return mPrefs.getString("publish_time", "--");
    }

    public void setWeatherCodeNow(String weatherCodeNow) {
        mEditor.putString("weather_code_now", weatherCodeNow);
    }

    public String getWeatherCodeNow() {
        return mPrefs.getString("weather_code_now", "100");
    }

    public void setWeatherNow(String weatherNow) {
        mEditor.putString("weather_now", weatherNow);
    }

    public String getWeatherNow() {
        return mPrefs.getString("weather_now", "--");
    }

    public String getCountyName() {
        return mPrefs.getString("county_name", "--");
    }

    public String getCountyCode() {
        return mPrefs.getString("county_code", "--");
    }

    public String getLongitude() {
        return mPrefs.getString("longitude", "");
    }

    public String getLatitude() {
        return mPrefs.getString("latitude", "");
    }

    public String getMinTempWeekly(int i) {
        return mPrefs.getString("min_temp_weekly" + i, "");
    }

    public String getMaxTempWeekly(int i) {
        return mPrefs.getString("max_temp_weekly" + i, "");
    }

    public String getWeatherWeekly(int i) {
        return mPrefs.getString("weather_weekly" + i, "--");
    }

    public String getWeatherCodeWeekly(int i) {
        return mPrefs.getString("weather_code_weekly" + i, "100");
    }

    public String getMaxTempToday() {
        return mPrefs.getString("max_temp_today", "--");
    }

    public String getMinTempToday() {
        return mPrefs.getString("min_temp_today", "--");
    }

    public String getTimeHourly(int i) {
        return mPrefs.getString("time_hourly" + i, "--");
    }

    public String getWeatherCodeHourly(int i) {
        return mPrefs.getString("weather_code_hourly" + i, "100");
    }

    public String getTempHourly(int i) {
        return mPrefs.getString("temp_hourly" + i, "--");
    }

    public String getAqiHourly(int i) {
        return mPrefs.getString("aqi_hourly" + i, "--");
    }

    public String getPm25Hourly(int i) {
        return mPrefs.getString("pm25_hourly" + i, "--");
    }

    public String getAqiWeekly(int i) {
        return mPrefs.getString("aqi_weekly" + i, "--");
    }

    public void setThemeNow(int themeNow) {
        mEditor.putInt("theme_now", themeNow);
        mEditor.apply();
    }

    public int getThemeNow() {
        return mPrefs.getInt("theme_now", 0);
    }

    public void setWidgetTheme(int themeNow, int appId) {
        mEditor.putInt("widget_theme_" + appId, themeNow);
        mEditor.apply();
    }

    public int getWidgetTheme(int appId) {
        return mPrefs.getInt("widget_theme_" + appId, 0);
    }

    public void setPictureUrl(String url, int i) {
        mEditor.putString("picture" + i, url);
        mEditor.apply();
    }

    public String getPictureUrl(int i) {
        return mPrefs.getString("picture" + i, "");
    }

    public String getAqiNow() {
        if (!mPrefs.getString("aqi_hourly" + 0, "--").equals("--")) {
            return "AQI " + mPrefs.getString("aqi_hourly" + 0, "--") + " >";
        } else {
            return mPrefs.getString("aqi_he" + 0, "--");
        }
    }


    public String getAqiDialog() {
        if (!mPrefs.getString("aqi_hourly" + 0, "--").equals("--")) {
            return mPrefs.getString("aqi_hourly" + 0, "--");
        } else {
            return mPrefs.getString("aqi_he" + 0, "--");
        }
    }


    public String getQlty() {
        return mPrefs.getString("qlty", "--");
    }

    public String getPm25() {
        return mPrefs.getString("pm25", "--");
    }

    public String getPm10() {
        return mPrefs.getString("pm10", "--");
    }

    public String getNo2() {
        return mPrefs.getString("no2", "--");
    }

    public String getSo2() {
        return mPrefs.getString("so2", "--");
    }

    public String getCo() {
        return mPrefs.getString("co", "--");
    }

    public String getO3() {
        return mPrefs.getString("o3", "--");
    }

    public String getComfB() {
        return mPrefs.getString("comf_b", "--");
    }

    public String getComfT() {
        return mPrefs.getString("comf_t", "--");
    }

    public String getDrsgB() {
        return mPrefs.getString("drsg_b", "--");
    }

    public String getDrsgT() {
        return mPrefs.getString("drsg_t", "--");
    }

    public String getFluB() {
        return mPrefs.getString("flu_b", "--");
    }

    public String getfluT() {
        return mPrefs.getString("flu_t", "--");
    }

    public String getUvB() {
        return mPrefs.getString("uv_b", "--");
    }

    public String getUvT() {
        return mPrefs.getString("uv_t", "--");
    }

    public String getSportB() {
        return mPrefs.getString("sport_b", "--");
    }

    public String getSportT() {
        return mPrefs.getString("sport_t", "--");
    }

    public String getCwB() {
        return mPrefs.getString("cw_b", "--");
    }

    public String getCwT() {
        return mPrefs.getString("cw_t", "--");
    }
} public class ViewUtil {
    public static Map<String, Integer> map = new HashMap<String, Integer>() {
        {
            put("cloud_night", R.drawable.cloud_night);
            put("100", R.drawable.sun);
            put("100_n", R.drawable.moon);
            put("101", R.drawable.cloud_day);
            put("101_n", R.drawable.cloud_night);
            put("102", R.drawable.cloud_day);
            put("103", R.drawable.cloud_day);
            put("104", R.drawable.glum);
            put("200", R.drawable.wind);
            put("201", R.drawable.d201);
            put("202", R.drawable.wind);
            put("203", R.drawable.wind);
            put("204", R.drawable.wind);
            put("205", R.drawable.d205);
            put("206", R.drawable.d205);
            put("207", R.drawable.d205);
            put("208", R.drawable.d208);
            put("209", R.drawable.d208);
            put("210", R.drawable.d208);
            put("211", R.drawable.d208);
            put("212", R.drawable.d208);
            put("213", R.drawable.d208);
            put("300", R.drawable.rain_shower);
            put("301", R.drawable.rain_big_shower);
            put("302", R.drawable.thunder);
            put("303", R.drawable.d303);
            put("304", R.drawable.d304);
            put("305", R.drawable.rain);
            put("306", R.drawable.rain_mid);
            put("307", R.drawable.rain_big);
            put("308", R.drawable.d308);
            put("309", R.drawable.d309);
            put("310", R.drawable.d310);
            put("311", R.drawable.d311);
            put("312", R.drawable.d312);
            put("313", R.drawable.d313);
            put("400", R.drawable.d400);
            put("401", R.drawable.d401);
            put("402", R.drawable.d402);
            put("403", R.drawable.d403);
            put("404", R.drawable.d404);
            put("405", R.drawable.d405);
            put("406", R.drawable.d406);
            put("407", R.drawable.d407);
            put("501", R.drawable.fog);
            put("502", R.drawable.mai);
            put("503", R.drawable.d503);
            put("504", R.drawable.d504);
            put("507", R.drawable.d507);
            put("508", R.drawable.d508);
            put("900", R.drawable.d900);
            put("901", R.drawable.d901);
            put("999", R.drawable.d999);
        }
    };

    public static Integer getImageResource(String key) {
        return map.get(key);
    }

    public static Map<String, String> mapHourly = new HashMap<String, String>() {
        {
            put("CLEAR_DAY", "100");
            put("CLEAR_NIGHT", "100_n");
            put("PARTLY_CLOUDY_DAY", "101");
            put("PARTLY_CLOUDY_NIGHT", "101_n");
            put("CLOUDY", "104");
            put("WIND", "203");
            put("RAIN", "305");
            put("SLEET", "313");
            put("SNOW", "400");
            put("FOG", "501");
            put("HAZE", "502");
        }
    };

    public static String getHourlyWeatherCode(String key) {
        return mapHourly.get(key);
    }

    public static int dip2px(Context context, float dpValue) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return (int) (dpValue * dm.density + 0.5f);
    }

    public static float dip2pxfloat(Context context, float dpValue) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dpValue * dm.density;
    }

    public static Bitmap decodeSampledBitmapFromFile(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    private static int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfWidth = width / 2;
            final int halfHeight = height / 2;
            while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    public static Bitmap getBitmapByView(NestedScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取scrollview实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
//            scrollView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"));
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }
} @SuppressLint("NewApi")
public class ColorView extends View {
    private ObjectAnimator ainm1;
    private float progress;
    private int mClickX;
    private int mClickY;
    private int x1;
    private int y1;
    private int director;
    private int mColor;
    private int mColorPre;
    private Paint mPaint;
    private int mDuration = 200;
    private boolean mLongClicked = false;

    private String mPictureUrl;

    public ColorView(Context context) {
        super(context);
    }

    //实现在布局文件中使用
    public ColorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    public void setDuration(int duration) {
        this.mDuration = duration;
    }

    public void setLongClicked(boolean longClicked) {
        this.mLongClicked = longClicked;
    }

    public boolean isLongClicked() {
        return mLongClicked;
    }

    public int getColorPre() {
        return mColorPre;
    }

    public void setColorPre(int colorPre) {
        mColorPre = colorPre;
    }

    public int getClickY() {
        return mClickY;
    }

    public void setClickY(int clickY) {
        mClickY = clickY;
    }

    public int getClickX() {
        return mClickX;
    }

    public void setClickX(int clickX) {
        mClickX = clickX;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(mColor);

        if (mClickY < getHeight() / 2 && mClickX > getWidth() / 2) {
            y1 = getHeight() - mClickY;
            director = (int) Math.sqrt(mClickX * mClickX + y1 * y1);
        }
        if (mClickX < getWidth() / 2 && mClickY > getHeight() / 2) {
            x1 = getWidth() - mClickX;
            director = (int) Math.sqrt(x1 * x1 + mClickY * mClickY);
        }
        if (mClickX < getWidth() / 2 && mClickY < getHeight() / 2) {
            y1 = getHeight() - mClickY;
            x1 = getWidth() - mClickX;
            director = (int) Math.sqrt(x1 * x1 + y1 * y1);
        }
        if (mClickX > getWidth() / 2 && mClickY > getHeight() / 2) {
            director = (int) Math.sqrt(mClickX * mClickX + mClickY * mClickY);
        }
        float r = progress * director;
        //画圆

        canvas.drawCircle(mClickX, mClickY, r, mPaint);
    }

    public void setProgress(float progress) {
        this.progress = progress;
        postInvalidate();
    }

    public void setColor(int color) {
        this.mColor = color;
    }

    public void start(int width, int height) {
        mClickX = width;
        mClickY = height;
        //属性动画
        ainm1 = ObjectAnimator.ofFloat(this, "progress", 0, 1).setDuration(mDuration);
        ainm1.start();
    }
} public class LineGraphicView extends View {
    /**
     * 公共部分
     */
    private static final String TAG = "vvv";

    private static enum Linestyle {
        Line, Curve
    }

    private static enum LineType {
        High, Low
    }

    private Context mContext;
    private Paint mPaint;
    private Resources res;
    private DisplayMetrics dm;

    /**
     * data
     */
    private Linestyle mStyle = Linestyle.Line;

    private int canvasHeight;
    private int canvasWidth;

    private int mChartHeight = 0;
    private int mStartX;
    private int mEndX;
    private boolean isMeasure = true;
    /**
     * Y轴最大值
     */
    private int maxValue;
    private int minValue;

    private int marginTop = 85;
    private int marginBottom = 73;

    /**
     * 曲线上总点数
     */
    private Point[] mPointsHigh;
    private Point[] mPointsLow;
    /**
     * 纵坐标值
     */
    private ArrayList<Integer> yRawDataHigh = new ArrayList<>();
    private ArrayList<Integer> yRawDataLow = new ArrayList<>();
    /**
     * 横坐标值
     */
    private ArrayList<Integer> xList = new ArrayList<Integer>();// 记录每个x的值

    private int mDotTextColor = Color.argb(255, 255, 255, 255);

    public int getDotTextColor() {
        return mDotTextColor;
    }

    public void setDotTextColor(int dotTextColor) {
        mDotTextColor = dotTextColor;
    }

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

    public LineGraphicView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
    }

    public LineGraphicView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();
    }

    private void initView() {
        this.res = mContext.getResources();
        this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (isMeasure) {
            this.canvasHeight = getHeight();
            this.canvasWidth = getWidth();
            if (mChartHeight == 0)
                mChartHeight = canvasHeight - marginTop - marginBottom;
            mStartX = dip2px(28);
            isMeasure = false;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(Color.WHITE);
        // 点的操作设置
        setPoints();

        mPaint.setStrokeWidth(dip2px(1.2f));
        mPaint.setStyle(Paint.Style.STROKE);
        if (mStyle == Linestyle.Curve) {
            drawScrollLine(canvas, mPointsHigh);
            drawScrollLine(canvas, mPointsLow);
        } else {
            drawLine(canvas, mPointsHigh);
            drawLine(canvas, mPointsLow);
        }

        drawTextOnLine(canvas);
    }

    private void drawText(String text, int x, int y, Canvas canvas) {
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setTextSize(dip2px(12));
        p.setColor(mDotTextColor);
        p.setTextAlign(Paint.Align.LEFT);
        canvas.drawText(text, x, y, p);
    }

    private void setPoints() {
        mPointsHigh = new Point[yRawDataHigh.size()];
        for (int i = 0; i < yRawDataHigh.size(); i++) {
            xList.add(mStartX + (canvasWidth - mStartX * 2) / (yRawDataHigh.size() - 1) * i);
            int pointY = mChartHeight - (int) (mChartHeight * (yRawDataHigh.get(i) - minValue) / (maxValue - minValue)) + marginTop;
            mPointsHigh[i] = new Point(xList.get(i), pointY);
        }
        mPointsLow = new Point[yRawDataLow.size()];
        for (int i = 0; i < yRawDataLow.size(); i++) {
            xList.add(mStartX + (canvasWidth - mStartX * 2) / (yRawDataLow.size() - 1) * i);
            int pointY = mChartHeight - (int) (mChartHeight * (yRawDataLow.get(i) - minValue) / (maxValue - minValue)) + marginTop;
            mPointsLow[i] = new Point(xList.get(i), pointY);
        }
    }


    private void drawLine(Canvas canvas, Point[] points) {
        Point startp = new Point();
        Point endp = new Point();
        for (int i = 0; i < points.length - 1; i++) {
            startp = points[i];
            endp = points[i + 1];
            canvas.drawLine(startp.x, startp.y, endp.x, endp.y, mPaint);
        }
    }


    private void drawScrollLine(Canvas canvas, Point[] points) {
        Point startp = new Point();
        Point endp = new Point();
        for (int i = 0; i < points.length - 1; i++) {
            startp = points[i];
            endp = points[i + 1];
            int wt = (startp.x + endp.x) / 2;
            Point p3 = new Point();
            Point p4 = new Point();
            p3.y = startp.y;
            p3.x = wt;
            p4.y = endp.y;
            p4.x = wt;

            Path path = new Path();
            path.moveTo(startp.x, startp.y);
            path.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
            canvas.drawPath(path, mPaint);
        }
    }

    private void drawTextOnLine(Canvas canvas) {
        for (int i = 0; i < mPointsHigh.length; i++) {
            drawText(
                    String.valueOf(yRawDataHigh.get(i)) + "°",
                    mPointsHigh[i].x - dip2px(8), mPointsHigh[i].y - dip2px(10),
                    canvas);
        }
        for (int i = 0; i < mPointsLow.length; i++) {
            drawText(
                    String.valueOf(yRawDataLow.get(i)) + "°",
                    mPointsLow[i].x - dip2px(8), mPointsLow[i].y + dip2px(16),
                    canvas);
        }
    }

    public void setData(ArrayList<Integer> yRawDataHigh, ArrayList<Integer> yRawDataLow, int maxValue, int minValue) {
        this.mPointsHigh = new Point[yRawDataHigh.size()];
        this.yRawDataHigh = yRawDataHigh;
        this.mPointsLow = new Point[yRawDataLow.size()];
        this.yRawDataLow = yRawDataLow;
        this.maxValue = maxValue;
        this.minValue = minValue;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(float dpValue) {
        return (int) (dpValue * dm.density + 0.5f);
    }

} public class MyLinearLayout extends LinearLayout {

    private boolean needDispatch = true;

    public MyLinearLayout(Context context) {
        super(context);
    }

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void setNeedDispatch(boolean needDispatch) {
        this.needDispatch = needDispatch;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!needDispatch){
                    return false;
                }
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }
} public class MyPopWindow extends PopupWindow {
    private RecyclerView mRcvTheme;
    private View mPopView;
    private ImageView mIvCancel;
    private ArrayList<ItemTheme> mDataList = new ArrayList<>();
    private RcvThemeAdapter mAdapter;

    public MyPopWindow(Context context, ArrayList<ItemTheme> itemThemes,
                       View.OnClickListener onClickListener, BaseRcvAdapter.ItemOnClickListener itemOnClickListener) {
        super(context);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);

        //设置SelectPicPopupWindow弹出窗体的背景
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        this.setBackgroundDrawable(dw);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mPopView = inflater.inflate(R.layout.layout_pop, null);
//        mPopView.getBackground().setAlpha(230);
        this.setContentView(mPopView);
        mRcvTheme = (RecyclerView) mPopView.findViewById(R.id.rcv_theme);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRcvTheme.setLayoutManager(linearLayoutManager);
        mDataList = itemThemes;
        mAdapter = new RcvThemeAdapter(mDataList);
        mAdapter.setItemOnClickListener(itemOnClickListener);
        mRcvTheme.setAdapter(mAdapter);
        mRcvTheme.setItemAnimator(null);

        mIvCancel = (ImageView) mPopView.findViewById(R.id.iv_cancel);
        mIvCancel.setOnClickListener(onClickListener);

        RotateAnimation rotateAnimation = new RotateAnimation(0, 540, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(1000);
        mIvCancel.setAnimation(rotateAnimation);

//        设置点击下面就退出
//        this.setFocusable(false);
//        this.setOutsideTouchable(true);

        this.setAnimationStyle(R.style.PopAnimation);
    }

    public void showDismissAnimation() {
        RotateAnimation rotateAnimation = new RotateAnimation(0, -540, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(1000);
        mIvCancel.startAnimation(rotateAnimation);
    }


    public void showStartAnimation() {
        RotateAnimation rotateAnimation = new RotateAnimation(0, 540, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(900);
        mIvCancel.startAnimation(rotateAnimation);
    }

    public void scrollToSelected() {
        mRcvTheme.scrollToPosition(mAdapter.getLastSelected());
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }
} public class MyRecyclerView extends RecyclerView {

    private static final String TAG = "touch";
    private boolean needDispatch = true;

    public MyRecyclerView(Context context) {
        super(context);
    }

    public MyRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public boolean isNeedDispatch() {
        return needDispatch;
    }

    public void setNeedDispatch(boolean needDispatch) {
        this.needDispatch = needDispatch;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
//        Log.d(TAG, "dispatchTouchEvent: ");
//        int x = (int) event.getX();
//        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!needDispatch){
                    return false;
                }
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }
}
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.deerweather.app.R;
import com.deerweather.app.adapter.BaseRcvAdapter;
import com.deerweather.app.adapter.RcvHourlyAdapter;
import com.deerweather.app.adapter.RcvWeeklyAdapter;
import com.deerweather.app.model.County;
import com.deerweather.app.model.DeerWeatherDB;
import com.deerweather.app.model.ItemHourly;
import com.deerweather.app.model.ItemTheme;
import com.deerweather.app.model.ItemWeekly;
import com.deerweather.app.service.AutoUpdateService;
import com.deerweather.app.util.HttpCallBackListener;
import com.deerweather.app.util.HttpUtil;
import com.deerweather.app.util.JSONUtility;
import com.deerweather.app.util.OtherUtil;
import com.deerweather.app.util.SharedPreferenceUtil;
import com.deerweather.app.util.ViewUtil;
import com.deerweather.app.view.ColorView;
import com.deerweather.app.view.LineGraphicView;
import com.deerweather.app.view.MyLinearLayout;
import com.deerweather.app.view.MyPopWindow;
import com.deerweather.app.view.MyRecyclerView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
package com.deerweather.app.activity;




public class WeatherActivity extends AppCompatActivity implements
        SwipeRefreshLayout.OnRefreshListener, View.OnTouchListener,
        View.OnLongClickListener, View.OnClickListener {

    private static final String TAG = "touch_";
    public static final int TAKE_PHOTO = 111;
    public static final int CROP_PHOTO = 112;
    public static final int ACCESS_FINE_LOCATION_REQUEST_CODE = 100;
    private static final int CHOOSE_COUNTY = 113;
    private Uri mImageUri;

    private NestedScrollView mNsvMain;
    private SwipeRefreshLayout mSwipeRefresh;

    private DrawerLayout mDrawer;
    private NavigationView mNavigationView;
    private Toolbar mToolbar;

    private DeerWeatherDB mDeerWeatherDB;
    private List<County> mCounty = new ArrayList<>();
    private List<String> mSavedCountyName = new ArrayList<>();

    private TextView mTvNowTemp;
    private TextView mTvNowAqi;
    private TextView mTvPublishTime;
    private ImageView mIvNowWeatherImg;
    private TextView mTvNowWeather;

    private MyRecyclerView mRcvHourly;
    private ArrayList<ItemHourly> mHourlyDataList = new ArrayList<>();
    private RcvHourlyAdapter mHourlyAdapter;

    private MyRecyclerView mRcvWeekly;
    private ArrayList<ItemWeekly> mWeeklyDataList = new ArrayList<>();
    private RcvWeeklyAdapter mWeeklyAdapter;

    private LineGraphicView mLineWeekly;
    private ArrayList<Integer> mLineDataHigh = new ArrayList<>();
    private ArrayList<Integer> mLineDataLow = new ArrayList<>();

    private static final int LONG_DURATION = 1500;
    private static final int SHORT_DURATION = 200;

    private View mViewToolbarExtend;
    private ColorView mCvToolbar;
    private ColorView mCvTemp;
    private ColorView mCvImg;
    private ColorView mCvHourly;
    private ColorView mCvWeeklyInfo;
    private ColorView mCvWeeklyChart;
    private ColorView mCvSuggestion;
    private ArrayList<ColorView> mCvAll = new ArrayList<>();

    private TextView mTvComf;
    private TextView mTvDrsg;
    private TextView mTvFlu;
    private TextView mTvUv;
    private TextView mTvSport;
    private TextView mTvCw;
    private MyLinearLayout mLlComf;
    private MyLinearLayout mLlDrsg;
    private MyLinearLayout mLlFlu;
    private MyLinearLayout mLlUv;
    private MyLinearLayout mLlSport;
    private MyLinearLayout mLlCw;

    public static final int MODE_NORMAL = 1;
    public static final int MODE_UPDATE = 7;
    public static final int MODE_CREATE = 8;
    private int mModeType = MODE_NORMAL;
    public static final int MODE_CHANGE_NORMAL = 0;
    public static final int MODE_CHANGE_SINGLE = 2;
    public static final int MODE_CHANGE_ALL_DIFFERENT = 3;
    public static final int MODE_CHANGE_ALL_SAME = 4;
    public static final int MODE_CHANGE_ALL_GRADUAL = 5;
    public static final int MODE_CHANGE_PICTURE = 6;
    private int mChangeModeType = MODE_CHANGE_NORMAL;

    public static final int MENU_NORMAL = 11;
    public static final int MENU_CHANGE = 12;
    private int mMenuType = MENU_NORMAL;

    public static final int SHOW_LOCAL = 21;
    public static final int SHOW_WITH_HOURLY_QUERY = 22;
    private int mShowType = SHOW_LOCAL;

    private MyPopWindow mPopWindow;

    private boolean mFlagThemeChanged = false;

    ArrayList<ItemTheme> mItemThemes = new ArrayList<>();
    private int mThemeNow;
    private int mClickedId;
    private boolean mFlagFirst = true;

    private SharedPreferenceUtil mPrefs;