public class BaseApplication extends Application {

    public static Context mAppContext = null;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();
        FIR.init(this);
    }

    public static Context getAppContext() {
        return mAppContext;
    }

} public class BusProvider {
    private volatile static Bus bus = null;

    private BusProvider() {
    }

    public static Bus getInstance() {
        if (bus == null) {
            synchronized (BusProvider.class) {
                bus = new Bus();
            }
        }
        return bus;
    }
} public class HttpMethods {

    public static final String BASE_URL = "https://api.heweather.com/x3/";
    public static final String KEY = "08ee8103cc4d44a99ee8d0dc0dacd014";
    public static final String API_TOKEN = "9636021009f8a18fe1449dc7499ff2b4";
    public static final String HUANGLI_KEY = "743692bc90246c4f89643e9026c6f707";
    public static final String CONSTELLATION_KEY = "6289d3f06cf2ee32c16f80a83885b8d1";

    private static HttpMethods sHttpMethods;
    private Context mContext;
    private Retrofit mRetrofit;
    private Api mApi;

    // Interceptor
    private static final Interceptor INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            if (NetUtils.isConnected(BaseApplication.getAppContext())) {
                int maxAge = 60;
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28;
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
        }
    };

    // Cache
    private static File cacheFile = new File(BaseApplication.getAppContext().getCacheDir(), "weatherCache");
    private static int cacheSize = 10 * 1024 * 1024;
    private static Cache cache = new Cache(cacheFile, cacheSize);

    // OkHttp
    private static OkHttpClient sClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(INTERCEPTOR)
            .addInterceptor(INTERCEPTOR)
            .cache(cache)
            .build();

    // 构造方法私有化
    private HttpMethods() {
        // Retrofit
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(sClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        mApi = mRetrofit.create(Api.class);
    }

    // 获取 HttpMethods 的单例
    public synchronized static HttpMethods getInstance() {
        if(sHttpMethods == null) {
            sHttpMethods = new HttpMethods();
        }
        return sHttpMethods;
    }

    // 获取天气数据
    public Observable<WeatherBean> getWeatherData(String cityName) {
        return mApi.getWeatherData(cityName, KEY);
    }

    // 获取天气数据
    public void getWeatherData(Subscriber<WeatherBean> subscriber, String city) {
        mApi.getWeatherData(city, KEY)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    // 获取版本号
    public void getVersionData(Subscriber<VersionBean> subscriber) {
        mApi.getVersionData(API_TOKEN)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    // 获取黄历数据
    public void getHuangLiData(Subscriber<HuangLiBean> subscriber) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        mApi.getHuangLiData(year + "-" + month + "-" + day, HUANGLI_KEY)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    // 获取星座数据
    public void getConstellation(Subscriber<ConstellationBean> subscriber, String consName, String type) {
        mApi.getConstellation(consName, type, CONSTELLATION_KEY)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }
} public class ConstellationBean {

    /**
     * date : 20160602
     * name : 射手座
     * QFriend : 射手座
     * all : 40%
     * color : 白色
     * datetime : 2016年06月02日
     * health : 75%
     * love : 20%
     * money : 40%
     * number : 5
     * summary : 你在人际，情感和家庭方面容易产生一些混乱的感受，比如不知如何增进彼此的感情，或者打理好自己的私生活和居家状态。但好在你的个人发展还算不错，不如聚焦于自己该完成的事情吧。
     * work : 20%
     * resultcode : 200
     * error_code : 0
     */

    @SerializedName("date")
    private int date;
    @SerializedName("name")
    private String name;
    @SerializedName("QFriend")
    private String QFriend;
    @SerializedName("all")
    private String all;
    @SerializedName("color")
    private String color;
    @SerializedName("datetime")
    private String datetime;
    @SerializedName("health")
    private String health;
    @SerializedName("love")
    private String love;
    @SerializedName("money")
    private String money;
    @SerializedName("number")
    private int number;
    @SerializedName("summary")
    private String summary;
    @SerializedName("work")
    private String work;
    @SerializedName("resultcode")
    private String resultcode;
    @SerializedName("error_code")
    private int errorCode;

    public int getDate() {
        return date;
    }

    public void setDate(int date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getQFriend() {
        return QFriend;
    }

    public void setQFriend(String QFriend) {
        this.QFriend = QFriend;
    }

    public String getAll() {
        return all;
    }

    public void setAll(String all) {
        this.all = all;
    }

    public String getColor() {
        return color;
    }

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

    public String getDatetime() {
        return datetime;
    }

    public void setDatetime(String datetime) {
        this.datetime = datetime;
    }

    public String getHealth() {
        return health;
    }

    public void setHealth(String health) {
        this.health = health;
    }

    public String getLove() {
        return love;
    }

    public void setLove(String love) {
        this.love = love;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getWork() {
        return work;
    }

    public void setWork(String work) {
        this.work = work;
    }

    public String getResultcode() {
        return resultcode;
    }

    public void setResultcode(String resultcode) {
        this.resultcode = resultcode;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
} public class HuangLiBean {

    /**
     * reason : successed
     * result : {"id":"2280","yangli":"2016-06-01","yinli":"丙申(猴)年四月廿六","wuxing":"大溪水 收执位","chongsha":"冲猴(戊申)煞北","baiji":"甲不开仓财物耗散 寅不祭祀神鬼不尝","jishen":"月空 母仓 敬安 五合 鸣犬","yi":"栽种 捕捉 畋猎 馀事勿取","xiongshen":"劫煞 月害 土府 八专 天牢","ji":"开市 动土 祭祀 斋醮 安葬 探病"}
     * error_code : 0
     */

    @SerializedName("reason")
    private String reason;
    /**
     * id : 2280
     * yangli : 2016-06-01
     * yinli : 丙申(猴)年四月廿六
     * wuxing : 大溪水 收执位
     * chongsha : 冲猴(戊申)煞北
     * baiji : 甲不开仓财物耗散 寅不祭祀神鬼不尝
     * jishen : 月空 母仓 敬安 五合 鸣犬
     * yi : 栽种 捕捉 畋猎 馀事勿取
     * xiongshen : 劫煞 月害 土府 八专 天牢
     * ji : 开市 动土 祭祀 斋醮 安葬 探病
     */

    @SerializedName("result")
    private ResultBean result;
    @SerializedName("error_code")
    private int errorCode;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public ResultBean getResult() {
        return result;
    }

    public void setResult(ResultBean result) {
        this.result = result;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public static class ResultBean {
        @SerializedName("id")
        private String id;
        @SerializedName("yangli")
        private String yangli;
        @SerializedName("yinli")
        private String yinli;
        @SerializedName("wuxing")
        private String wuxing;
        @SerializedName("chongsha")
        private String chongsha;
        @SerializedName("baiji")
        private String baiji;
        @SerializedName("jishen")
        private String jishen;
        @SerializedName("yi")
        private String yi;
        @SerializedName("xiongshen")
        private String xiongshen;
        @SerializedName("ji")
        private String ji;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getYangli() {
            return yangli;
        }

        public void setYangli(String yangli) {
            this.yangli = yangli;
        }

        public String getYinli() {
            return yinli;
        }

        public void setYinli(String yinli) {
            this.yinli = yinli;
        }

        public String getWuxing() {
            return wuxing;
        }

        public void setWuxing(String wuxing) {
            this.wuxing = wuxing;
        }

        public String getChongsha() {
            return chongsha;
        }

        public void setChongsha(String chongsha) {
            this.chongsha = chongsha;
        }

        public String getBaiji() {
            return baiji;
        }

        public void setBaiji(String baiji) {
            this.baiji = baiji;
        }

        public String getJishen() {
            return jishen;
        }

        public void setJishen(String jishen) {
            this.jishen = jishen;
        }

        public String getYi() {
            return yi;
        }

        public void setYi(String yi) {
            this.yi = yi;
        }

        public String getXiongshen() {
            return xiongshen;
        }

        public void setXiongshen(String xiongshen) {
            this.xiongshen = xiongshen;
        }

        public String getJi() {
            return ji;
        }

        public void setJi(String ji) {
            this.ji = ji;
        }
    }
} public class AutoUpdateService extends Service{

    private CompositeSubscription mCompositeSubscription;
    private Subscription mSubscription;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mCompositeSubscription = new CompositeSubscription();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        synchronized (this) {
            mCompositeSubscription.remove(mSubscription);
            Log.d("AutoUpdateService", "work?");
            if(SettingUtils.getInstance().getIsAutoUpdate()) {
                Log.d("AutoUpdateService", "what?");
                if(SettingUtils.getInstance().getAutoUpdate() != 0) {
                    Log.d("AutoUpdateService", "really work?");
                    mSubscription = Observable.interval(SettingUtils.getInstance().getAutoUpdate(), TimeUnit.HOURS)
                            .subscribe(new Action1<Long>() {
                                @Override
                                public void call(Long aLong) {
                                    Log.d("AutoUpdateService", "work!");
                                    getWeather();
                                }
                            });
                    mCompositeSubscription.add(mSubscription);
                }
            }
        }
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 获取天气数据
     */
    public void getWeather() {
        SharedPreferences prefs = getSharedPreferences("show_city_prefs", MODE_PRIVATE);
        String cityName = prefs.getString("show_city", "");
        if(!cityName.equals("")) {
            HttpMethods.getInstance().getWeatherData(new Subscriber<WeatherBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    Log.d("AutoUpdateService", e.getMessage());
                }

                @Override
                public void onNext(WeatherBean weatherBean) {
                    BusProvider.getInstance().post(weatherBean);
                }
            }, cityName);
        }
    }

    /**
     * 通知栏天气
     */
    public void showNotification(WeatherBean weatherBean) {
        Intent intent = new Intent(AutoUpdateService.this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(AutoUpdateService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(AutoUpdateService.this);
        Notification notification = builder.setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(weatherBean.getHeWeatherDataService().get(0).getBasic().getCity())
                .setContentText(String.format("%s  体感温度: %s ℃  PM2.5: %s",
                        weatherBean.getHeWeatherDataService().get(0).getNow().getCond().getTxt(),
                        weatherBean.getHeWeatherDataService().get(0).getNow().getFl(),
                        weatherBean.getHeWeatherDataService().get(0).getAqi().getCity().getPm25()))
                .build();
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, notification);
    }


} public class MainFragmentAdapter extends FragmentStatePagerAdapter {

    private List<String> mStrings;
    private List<Fragment> mFragments;

    public MainFragmentAdapter(FragmentManager fragmentManager, List<String> strings, List<Fragment> fragments) {
        super(fragmentManager);
        mStrings = strings;
        mFragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mStrings.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

} public class BasicFragment extends Fragment{

    private View view;

    private RecyclerView mBasicRecyclerView;
    private BasicRvAdapter mBasicRvAdapter;
    private WeatherBean mWeatherData;
    private HuangLiBean mHuangLiData;
    private ConstellationBean mConstellationData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_basic, container, false);

        // 获取控件的引用
        mBasicRecyclerView = (RecyclerView) view.findViewById(R.id.main_basic_rv);

        // RecyclerView
        mBasicRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    // 获取从 MainActivity 传来的 WeatherBean 数据，并给 RecyclerView 设置 Adapter
    public void setWeatherData(WeatherBean weatherData, HuangLiBean huangLiData, ConstellationBean constellationData) {
        mWeatherData = weatherData;
        mBasicRvAdapter = new BasicRvAdapter(getContext(), mWeatherData, huangLiData, constellationData);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(mBasicRvAdapter);
        scaleAdapter.setFirstOnly(false);
        mBasicRecyclerView.setAdapter(scaleAdapter);
    }

} public class ForecastFragment extends Fragment {

    private View view;

    private RecyclerView mMoreRecyclerView;
    private ForecastRvAdapter mForecastRvAdapter;

    private WeatherBean mWeatherData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

        // 获取控件的引用
        mMoreRecyclerView = (RecyclerView) view.findViewById(R.id.main_forecast_rv);

        // RecyclerView
        mMoreRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void setWeatherData(WeatherBean weatherData) {
        mWeatherData = weatherData;
        mForecastRvAdapter = new ForecastRvAdapter(getContext(), mWeatherData);
        ScaleInAnimationAdapter scaleAdapter= new ScaleInAnimationAdapter(mForecastRvAdapter);
        scaleAdapter.setFirstOnly(false);
        mMoreRecyclerView.setAdapter(scaleAdapter);
    }
} public class PrefsUtils {

    /**
     * 保存定位城市
     */
    public static void saveLocationCity(Context context, String cityName) {
        SharedPreferences.Editor editor = context.getSharedPreferences("location_city_prefs", Context.MODE_PRIVATE).edit();
        editor.putString("location_city", cityName).commit();
    }

    /**
     * 获取已保存的定位城市
     */
    public static String getLocationCity(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("location_city_prefs", Context.MODE_PRIVATE);
        return prefs.getString("location_city", "");
    }

    /**
     * 保存首页要展示的城市到 Prefs
     * @param cityName
     */
    public static void saveShowCityToPrefs(Context context, String cityName) {
        SharedPreferences.Editor editor = context.getSharedPreferences("show_city_prefs", Context.MODE_PRIVATE).edit();
        editor.putString("show_city", cityName);
        editor.commit();
    }

    /**
     * 获取已保存的首页展示的城市
     * @return
     */
    public static String getShowCityFromPrefs(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("show_city_prefs", Context.MODE_PRIVATE);
        return prefs.getString("show_city", "");
    }

    /**
     * 把 WeatherList 对象转换成 JSON 形式的字符串，并存进 SharedPreferences
     */
    public static void saveShowWeatherToPrefs(final Context context, WeatherBean weatherBean) {
        Observable.just(weatherBean)
                .map(new Func1<WeatherBean, Integer>() {
                    @Override
                    public Integer call(WeatherBean weatherBeans) {
                        SharedPreferences.Editor editor = context.getSharedPreferences("show_weather_prefs", Context.MODE_PRIVATE).edit();
                        String str = "";
                        Gson gson = new Gson();
                        str = gson.toJson(weatherBeans);
                        editor.putString("show_weather", str);
                        editor.commit();
                        return 0;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("PrefsUtils", e.getMessage());
                    }

                    @Override
                    public void onNext(Integer integer) {

                    }
                });

    }

    /**
     * 从 SharedPreferences 读取字符串，并把字符串解析成 WeatherList 对象
     */
    public static WeatherBean getShowWeatherFromPrefs(Context context) {
        WeatherBean weatherBean = null;
        SharedPreferences prefs = context.getSharedPreferences("show_weather_prefs", Context.MODE_PRIVATE);
        String str = prefs.getString("show_weather", "");
        if(str != null) {
            Gson gson = new Gson();
            weatherBean = gson.fromJson(str, new TypeToken<WeatherBean>(){}.getType());
        }
        return weatherBean;
    }
} public class ScreenShotUtils {

    public static final String IMG_PATH = Environment.getExternalStorageDirectory() + "/only_weather/";

    /**
     * 进行截取屏幕
     * @param activity
     * @return bitmap
     */
    public static Bitmap takeScreenShot(Activity activity)
    {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();
        // 去掉标题栏
        Bitmap b = Bitmap.createBitmap(bitmap, 0,
                statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }


    /**
     * 保存图片到sdcard中
     * @param bitmap
     */
    private static boolean savePic(Bitmap bitmap,String strName)
    {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(strName);
            if(fos != null) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 10, fos);
                fos.flush();
                fos.close();
                return true;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 截图
     * @param activity
     * @return 截图并且保存sdcard成功返回true，否则返回false
     */
    public static String shot(Activity activity)
    {
        String imgPath = IMG_PATH + System.currentTimeMillis() + "share.png";
        Log.d("ScreenShot", "shot_1");
        ScreenShotUtils.savePic(takeScreenShot(activity), imgPath);
        Log.d("ScreenShot", "shot_2");
        return imgPath;
    }
} public class SettingUtils {

    private static SettingUtils mSettingUtils;
    private SharedPreferences mPrefs;

    // 私有化构造方法
    private SettingUtils() {
        mPrefs = BaseApplication.getAppContext().getSharedPreferences("setting", Context.MODE_PRIVATE);
    }

    // 获取单例
    public static SettingUtils getInstance() {
        if(mSettingUtils == null) {
            mSettingUtils = new SettingUtils();
        }
        return mSettingUtils;
    }

    // 是否自动更新
    public void setIsAutoUpdate(boolean b) {
        mPrefs.edit().putBoolean("is_auto_update", b).apply();
    }
    public boolean getIsAutoUpdate() {
        return mPrefs.getBoolean("is_auto_update", true);
    }

    // 自动更新频率
    public void setAutoUpdate(int i) {
        mPrefs.edit().putInt("auto_update", i).apply();
    }
    public int getAutoUpdate() {
        return mPrefs.getInt("auto_update", 0);
    }

    // 通知栏天气
    public void setIsShowNotification(boolean b) {
        mPrefs.edit().putBoolean("is_show_notification", b).apply();
    }
    public boolean getIsShowNotification() {
        return mPrefs.getBoolean("is_show_notification", true);
    }

    // 是否显示黄历卡片
    public void setIsShowHuangLi(boolean b) {
        mPrefs.edit().putBoolean("is_show_huang_li", b).apply();
    }
    public boolean getIsShowHuangLi() {
        return mPrefs.getBoolean("is_show_huang_li", false);
    }

    // 是否显示星座卡片
    public void setIsShowCons(boolean b) {
        mPrefs.edit().putBoolean("is_show_cons", b).apply();
    }
    public boolean getIsShowCons() {
        return mPrefs.getBoolean("is_show_cons", false);
    }

    // 选择星座
    public void setSelectedCons(String s) {
        mPrefs.edit().putString("selected_cons", s).apply();
    }
    public String getSelectedCons() {
        return mPrefs.getString("selected_cons", "白羊座");
    }
} public class Utils {

    // 日期转星期
    public static String dateToWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        String week = "";
        dayForWeek = c.get(Calendar.DAY_OF_WEEK);
        switch (dayForWeek) {
            case 1:
                week = "周日";
                break;
            case 2:
                week = "周一";
                break;
            case 3:
                week = "周二";
                break;
            case 4:
                week = "周三";
                break;
            case 5:
                week = "周四";
                break;
            case 6:
                week = "周五";
                break;
            case 7:
                week = "周六";
                break;
        }
        return week;
    }

    // 通过星座名，返回星座图片 id
    public static int getConsImg(String consName) {
        switch (consName) {
            case "白羊座":
                return R.drawable.ic_bai_yang;
            case "金牛座":
                return R.drawable.ic_jin_niu;
            case "双子座":
                return R.drawable.ic_shuang_zi;
            case "巨蟹座":
                return R.drawable.ic_ju_xie;
            case "狮子座":
                return R.drawable.ic_shi_zi;
            case "处女座":
                return R.drawable.ic_chu_nv;
            case "天秤座":
                return R.drawable.ic_tian_ping;
            case "天蝎座":
                return R.drawable.ic_tian_xie;
            case "射手座":
                return R.drawable.ic_sagittarius;
            case "摩羯座":
                return R.drawable.ic_mo_jie;
            case "水瓶座":
                return R.drawable.ic_shui_ping;
            case "双鱼座":
                return R.drawable.ic_shuang_yu;
            default:
                return 0;

        }
    }

    // 正则表达式匹配百分数中的数字，例如：从 “75%” 中提取 “75”，并返回对应的星数
    public static float getRatingFromPercent(String percent) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(percent);
        if (m.find()) {
            return Float.valueOf(m.group()) / 20f;
        }
        return 2.5f;
    }

    // 正则表达式过滤高德地图定位获取的城市中的“市”，例如：从“广州市”中去掉“市”
    public static String getCityNameFromAMap(String cityName) {
        Pattern p = Pattern.compile("[\u5e02]");
        Matcher m = p.matcher(cityName);
        if (m.find()) {
            return m.replaceAll("");
        }
        return cityName;
    }
} public class VersionUtils {

    // 获取当前的版本号
    public static String getCurVersion(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "找不到版本号";
        }
    }

    // 比较版本号
    public static void checkVersion(final Context context) {
        HttpMethods.getInstance().getVersionData(new Subscriber<VersionBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(BaseApplication.getAppContext(),
                                "出现问题了(╯﹏╰)",
                                Toast.LENGTH_SHORT)
                        .show();
            }

            @Override
            public void onNext(VersionBean versionBean) {
                String newVersion = versionBean.getVersionShort();
                if (versionBean.getVersionShort().compareTo(getCurVersion(context)) > 0) {
                    showNewVersion(context, versionBean);
                } else {
                    Toast.makeText(BaseApplication.getAppContext(),
                                    "已经是最新版本",
                                    Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
    }

    // 比较版本号，但如果已经是最新版本，则无反馈 Toast
    public static void checkVersionNo(final Context context) {
        HttpMethods.getInstance().getVersionData(new Subscriber<VersionBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(VersionBean versionBean) {
                String newVersion = versionBean.getVersionShort();
                if (versionBean.getVersionShort().compareTo(getCurVersion(context)) > 0) {
                    showNewVersion(context, versionBean);
                }
            }
        });
    }

    // 展示新版本的相关信息
    public static void showNewVersion(final Context context, final VersionBean versionBean) {
        DecimalFormat decimalFormat = new DecimalFormat(".0");
        new AlertDialog.Builder(context)
                .setTitle("发现新版本")
                .setMessage("最新版本: " + versionBean.getVersionShort() + "\n" +
                        "新版本大小: " + versionBean.getBinary().getFsize() / 1024 / 1024 + " M\n\n" +
                        versionBean.getChangelog())
                .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = Uri.parse(versionBean.getUpdateUrl());
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(uri);
                        context.startActivity(intent);
            }
        })
                .setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }
}
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.nineoldandroids.animation.Animator;
import com.squareup.otto.Subscribe;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import me.codpoe.onlyweather.R;
import me.codpoe.onlyweather.base.BaseApplication;
import me.codpoe.onlyweather.base.BusProvider;
import me.codpoe.onlyweather.httpUtil.HttpMethods;
import me.codpoe.onlyweather.model.entity.ConstellationBean;
import me.codpoe.onlyweather.model.entity.HuangLiBean;
import me.codpoe.onlyweather.model.entity.WeatherBean;
import me.codpoe.onlyweather.service.AutoUpdateService;
import me.codpoe.onlyweather.ui.adapter.MainFragmentAdapter;
import me.codpoe.onlyweather.ui.fragment.BasicFragment;
import me.codpoe.onlyweather.ui.fragment.ForecastFragment;
import me.codpoe.onlyweather.util.PrefsUtils;
import me.codpoe.onlyweather.util.ScreenShotUtils;
import me.codpoe.onlyweather.util.SettingUtils;
import me.codpoe.onlyweather.util.Utils;
import me.codpoe.onlyweather.util.VersionUtils;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
package me.codpoe.onlyweather.ui.activity;





/**
 * Created by Codpoe on 2016/5/11.
 */
public class MainActivity extends AppCompatActivity
        implements View.OnClickListener,
        ViewPager.OnTouchListener,
        Toolbar.OnMenuItemClickListener,
        AMapLocationListener{

    private DrawerLayout mMainDrawerLayout;
    private SwipeRefreshLayout mRefreshLayout;
    private CoordinatorLayout mCoordinatorLayout;
    private NavigationView mNavigationView;
    private CollapsingToolbarLayout mMainCollapsingToolbarLayout;
    private AppBarLayout mAppBarLayout;
    private Toolbar mMainToolbar;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private ImageView mMainImg;
    private TextView mMainTmpText;
    private TextView mMainCondText;
    private FloatingActionButton mFloatingBtn;
    private TabLayout mMainTabLayout;
    private ViewPager mMainViewPager;
    private ProgressDialog mProgressDialog;

    private List<String> tabList;
    private List<Fragment> fragmentList;
    private BasicFragment mBasicFragment;
    private ForecastFragment mForecastFragment;
    private MainFragmentAdapter mMainFragmentAdapter;

    // 数据相关
    private WeatherBean mWeatherData;
    private HuangLiBean mHuangLiData;
    private ConstellationBean mConstellationData;

    // 高德地图定位服务
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    // 再按一次退出
    private boolean mIsExit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取引用
        findViews();

        // Otto
        BusProvider.getInstance().register(this);

        startService(new Intent(BaseApplication.getAppContext(), AutoUpdateService.class));