public abstract class BaseActivity extends AppCompatActivity implements InitUI, View.OnClickListener{

    /**屏幕的宽度*/
    protected int mScreenWidth;
    /**屏幕高度*/
    protected int mScreenHeight;
    /**屏幕密度*/
    protected float mDensity;

    private Toast mToast;

    public int getmScreenWidth() {
        return mScreenWidth;
    }

    public void setmScreenWidth(int mScreenWidth) {
        this.mScreenWidth = mScreenWidth;
    }

    public int getmScreenHeight() {
        return mScreenHeight;
    }

    public void setmScreenHeight(int mScreenHeight) {
        this.mScreenHeight = mScreenHeight;
    }

    public float getmDensity() {
        return mDensity;
    }

    public void setmDensity(float mDensity) {
        this.mDensity = mDensity;
    }

    private WindowManager mWindowManager = null;
    private View mNightView = null;
    private WindowManager.LayoutParams mNightViewParam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTheme();
        setContentView(getLayoutId());
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        setmScreenWidth(metric.widthPixels);
        setmScreenHeight(metric.heightPixels);
        mDensity = metric.density;
        initData();
        initView();
        initEvent();
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

    }

    /**
     * 这里得到Layout的id
     * @return layout布局的id
     */
    public abstract int getLayoutId();

    protected void startActivity(Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        startActivity(intent);
    }

    protected void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClass(this, cls);
        startActivity(intent);
    }


    public void showToast(String text) {
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(this,text,Toast.LENGTH_SHORT);
        mToast.show();

    }
    @Override
    public void onClick(View v) {
    }

    protected void initNightView(int layoutID) {
        mNightViewParam = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSPARENT);
        if (mNightView == null) {
            mNightView = LayoutInflater.from(this).inflate(layoutID, null);
            mWindowManager.addView(mNightView, mNightViewParam);
        }
    }

    protected void removeNightView(){
        if(mNightView!=null) {
            mWindowManager.removeViewImmediate(mNightView);
            mNightView = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
} public class DisplayUtil {
    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue
     *            （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     *            （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取控件的高度或者宽度  isHeight=true则为测量该控件的高度，isHeight=false则为测量该控件的宽度
     * @param view
     * @param isHeight
     * @return
     */
    public static int getViewHeight(View view, boolean isHeight){
        int result;
        if(view==null)return 0;
        if(isHeight){
            int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            view.measure(h,0);
            result =view.getMeasuredHeight();
        }else{
            int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            view.measure(0,w);
            result =view.getMeasuredWidth();
        }
        return result;
    }
} public class LogUtils {
    public static final int VERBOSE = 1;

    public static final int DEBUG = 2;

    public static final int INFO = 3;

    public static final int WARN = 4;

    public static final int ERROR = 5;

    public static final int NOTHING = 6;

    public static final int LEVEL = NOTHING;

    public static void v(String tag, String msg) {
        if (LEVEL <= VERBOSE) {
            Log.v(tag, msg);
        }
    }

    public static void d(String tag, String msg) {
        if (LEVEL <= DEBUG) {
            Log.d(tag, msg);
        }
    }

    public static void i(String tag, String msg) {
        if (LEVEL <= INFO) {
            Log.i(tag, msg);
        }
    }

    public static void w(String tag, String msg) {
        if (LEVEL <= WARN) {
            Log.w(tag, msg);
        }
    }

    public static void e(String tag, String msg) {
        if (LEVEL <= ERROR) {
            Log.e(tag, msg);
        }
    }


} public class CityManageActivity extends BaseActivity {

    @BindView(R.id.city_toolbar)
    public Toolbar toolbar;


    private CityManagePresenter mPresenter;


    @Override
    public int getLayoutId() {
        return R.layout.activity_city_manage;
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);

        FragmentManager fm = getSupportFragmentManager();
        CityManageFragment fragment = (CityManageFragment) fm.findFragmentById(R.id.fragment_container);
        if (fragment == null) {
            fragment = CityManageFragment.newInstance();
            fm.beginTransaction().add(R.id.fragment_container,fragment).commit();
        }
        mPresenter = new CityManagePresenter(fragment);

    }

    @Override
    public void initView() {
        toolbar.setTitle("城市管理");
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

    }


    @Override
    public void initTheme() {
        if(MyApplication.nightMode()){
            setTheme(R.style.NightTheme);
        }else {
            setTheme(R.style.DayTheme);
        }
    }





    @Override
    public void initEvent() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.add_city:
                        startActivity(CityActivity.class);
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        break;
                }
                return true;
            }
        });

    }


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



    @Override
    protected void onResume() {
        super.onResume();
        if(MyApplication.nightMode2()){
            initNightView(R.layout.night_mode_overlay);
        }else {
            removeNightView();
        }

        mPresenter.start();
    }
} public class LoveAppActivity extends BaseActivity {


    @BindView(R.id.web_view)
    public WebView webView;
    @BindView(R.id.toolbar)
    public Toolbar toolbar;
    @BindView(R.id.progress_bar)
    public ProgressBar progressBar;



    @Override
    public int getLayoutId() {
        return R.layout.activity_love_app;
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);

    }

    @Override
    public void initEvent() {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                progressBar.setProgress(newProgress );
                if(newProgress == 100){
                    progressBar.setVisibility(View.GONE);
                }else{
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress );//设置进度值
                }
            }

        });
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void initView() {
        toolbar.setTitle("喜欢");
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        progressBar.setMax(100);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.loadUrl("https://github.com/byhieg/easyweather");


    }

    @Override
    public void initTheme() {
        if(MyApplication.nightMode()){
            setTheme(R.style.NightTheme);
        }else {
            setTheme(R.style.DayTheme);
        }
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            if(webView.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                webView.goBack();
                return true;
            }else {//当webview处于第一页面时,直接退出程序
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(MyApplication.nightMode2()){
            initNightView(R.layout.night_mode_overlay);
        }else {
            removeNightView();
        }
    }
} public class SlideMenuActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    public Toolbar toolbar;

    private FragmentManager fm;
    public FuturePresenter mPresenter;


    @Override
    public int getLayoutId() {
        return R.layout.activity_laboratory;
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);

        fm = getSupportFragmentManager();
    }
    @Override
    public void initView() {

        int position = getIntent().getIntExtra("itemId", 0);
        switch (position){
            case Constants.FUTURE:
                toolbar.setTitle(R.string.future);
                FutureFragment futureFragment = new FutureFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, futureFragment,FutureFragment.TAG).commit();
                mPresenter = new FuturePresenter(futureFragment);
                break;
            case Constants.SETTING:
                toolbar.setTitle(R.string.setting);
                Fragment fragment = new SettingFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, fragment,SettingFragment.TAG).commit();
                break;
            case Constants.SHARE:
                toolbar.setTitle(R.string.share);
                fragment = new ShareFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, fragment,ShareFragment.TAG).commit();
                break;
            case Constants.HELP:
                toolbar.setTitle(R.string.help);
                fragment = new HelpFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, fragment,HelpFragment.TAG).commit();
                break;
            case Constants.LAB:
                toolbar.setTitle(R.string.laboratory);
                fragment = new LaboratoryFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, fragment, LaboratoryFragment.TAG).commit();
                break;
            case Constants.WIKI:
                toolbar.setTitle(R.string.wiki);
                fragment = new WikiFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, fragment, WikiFragment.TAG).commit();
                break;
            case Constants.ABOUT:
                toolbar.setTitle(R.string.about);
                fragment = new AboutFragment();
                fm.beginTransaction()
                        .add(R.id.fragment, fragment,AboutFragment.TAG).commit();
                break;
        }

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }


    }


    @Override
    public void initEvent() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    public void initTheme() {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }
} public class MyApplication extends Application{

    private static MyApplication mcontext;
    public static DaoMaster daoMaster;
    public static DaoSession daoSession;
    public static LocationClient mLocationClient;


    private static final String cityUrl = "https://free-api.heweather.com/";
    private static final String heweatherKey = "93d476b872724a9681a642dce28c6523";

    public static final String shareFilename1 ="nightMode";
    public static final String shareFilename2 ="nightMode2";
    public static final String logFilename = "log";
    public static final String notificationname = "notification";
    public static final String widgetname = "widget";
    public static final String cachename = "cache";
//    public static RefWatcher mRefWatcher;
    public static boolean isNewDay = false;
    public static final boolean ENCRYPTED = false;

    public static DaoSession getDaoSession() {
        if (daoMaster == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getAppContext(), ENCRYPTED ?
                    "weather-db-encrypted" : "weather-db");
            Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
            daoMaster = new DaoMaster(db);
            daoSession = new DaoMaster(db).newSession();
        }
        return daoMaster.newSession();
    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        TimeMonitorManager.getInstance().resetTimeMonitor(TimeMonitorConfig.TIME_MONITOR_ID_APPLICATION_START);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mcontext = this;
        new Thread(new Runnable() {
            @Override
            public void run() {
                NetService.getInstance().init(cityUrl);
                Logger.addLogAdapter(new AndroidLogAdapter());
            }
        }).start();

//        Stetho.initializeWithDefaults(this);
//        mRefWatcher = LeakCanary.install(mcontext);
        TimeMonitorManager.getInstance().getTimeMonitor(TimeMonitorConfig
                .TIME_MONITOR_ID_APPLICATION_START).recordingTimeTag("ApplicationCreated");

//        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getAppContext(),
//                "weather-db", null);
//        daoMaster = new DaoMaster(helper.getWritableDatabase());


//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(this);
//        crashHandler.sendPreviousReportsToServer();
    }

    public static Context getAppContext() {
        return mcontext;
    }

    public static String getCityUrl() {
        return cityUrl;
    }

    public static String getHeweatherKey() {
        return heweatherKey;
    }


    public static boolean nightMode(){
        SharedPreferences share = mcontext.getSharedPreferences(shareFilename1, MODE_PRIVATE);
        boolean ischecked=share.getBoolean("ischecked",false);
        return ischecked;
    }

    public static boolean nightMode2(){
        SharedPreferences share = mcontext.getSharedPreferences(shareFilename2, MODE_PRIVATE);
        boolean ischecked = share.getBoolean("ischecked",false);
        return ischecked;
    }


    public static boolean log(){
        SharedPreferences share = mcontext.getSharedPreferences(logFilename, MODE_PRIVATE);
        boolean ischecked = share.getBoolean("ischecked",true);
        return ischecked;
    }


    public static boolean notification(){
        SharedPreferences share = mcontext.getSharedPreferences(notificationname, MODE_PRIVATE);
        boolean ischecked = share.getBoolean("ischecked",true);
        return ischecked;
    }

    public static boolean widget(){
        SharedPreferences share = mcontext.getSharedPreferences(widgetname, MODE_PRIVATE);
        boolean ischecked = share.getBoolean("ischecked",true);
        return ischecked;
    }

    public static boolean cache(){
        SharedPreferences share = mcontext.getSharedPreferences(cachename, MODE_PRIVATE);
        boolean ischecked = share.getBoolean("ischecked",true);
        return ischecked;
    }

    public static LocationClient getmLocationClient() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(mcontext);

        }
        return mLocationClient;
    }

    public static boolean isNewDay() {
        return isNewDay;
    }
} public class Constants implements Serializable{


    public static final int FUTURE = 0x0;
    public static final int SETTING = 0x1;
    public static final int SHARE = 0x2;
    public static final int HELP = 0x3;
    public static final int LAB = 0x4;
    public static final int WIKI = 0x5;
    public static final int ABOUT = 0x6;


    //权限的标识
    public static final int PERMISSION = 0x201;


    public static final int NOTIFICATION_ID = 0X301;


    public static final int UPDATE_WEATHER = 0X401;

    public static final int UPDATE_SHOW_CITY = 0x402;






} public class MessageEvent {

    private int message;

    public MessageEvent(int message) {
        this.message = message;
    }

    public int getMessage() {
        return message;
    }

    public void setMessage(int message) {
        this.message = message;
    }
} public static final int UPDATE_SHOW_CITY = 0x402;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocationListener;
import com.orhanobut.logger.Logger;
import com.weather.byhieg.easyweather.base.BaseActivity;
import com.weather.byhieg.easyweather.tools.DisplayUtil;
import com.weather.byhieg.easyweather.tools.LogUtils;
import com.weather.byhieg.easyweather.citymanage.CityManageActivity;
import com.weather.byhieg.easyweather.loveapp.LoveAppActivity;
import com.weather.byhieg.easyweather.slidemenu.SlideMenuActivity;
import com.weather.byhieg.easyweather.MyApplication;
import com.weather.byhieg.easyweather.R;
import com.weather.byhieg.easyweather.tools.Constants;
import com.weather.byhieg.easyweather.tools.MessageEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.weather.byhieg.easyweather.tools.Constants.UPDATE_SHOW_CITY;
package com.weather.byhieg.easyweather.home;







public class MainActivity extends BaseActivity implements ActivityCompat
        .OnRequestPermissionsResultCallback,HomeFragment.Callback {


    @BindView(R.id.toolbar)
    public Toolbar toolbar;
    @BindView(R.id.drawer_layout)
    public DrawerLayout drawerLayout;
    @BindView(R.id.nav_view)
    public NavigationView mNavigationView;

//    public Toolbar toolbar;

    private HomePresenter mHomePresenter;
    private final boolean []isQuit = new boolean[1];

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        ButterKnife.bind(this);
        FragmentManager fm = getSupportFragmentManager();
        HomeFragment homeFragment = (HomeFragment) fm.findFragmentById(R.id.fragment_container);
        if (homeFragment == null) {
            homeFragment = HomeFragment.newInstance();
            fm.beginTransaction().add(R.id.fragment_container,homeFragment).commit();
        }

        mHomePresenter = new HomePresenter(homeFragment);
        BDLocationListener myListener = new MyLocationListener();
        MyApplication.getmLocationClient().registerLocationListener(myListener);