public class AccountApp extends Application {
    /** 程序使用的默认帐号 */
    public static String defaultUserName = "";
    /** 全局prefs */
    public SharedPreferences prefs;
    /** 全局editor */
    public SharedPreferences.Editor editor;
    /** 彩蛋prefs */
    public SharedPreferences eggPrefs;
    /** 彩蛋editor */
    public SharedPreferences.Editor eggEditor;

    public static AccountInfoServices aServices = null;
    public static ExpressServices eServices = null;
    /** 色彩主题的名称 */
    public static String colorThemeName;
    /** 上次连接成功的帐户 */
    public static String lastSuccess = "未知";
    /** 当前Application实例 */
    private static AccountApp mInstance;
    public static List<BaseActivity> activityList = new ArrayList<>();
    /** 应用启动后是否已经检测过WiFi */
    public static boolean isWifiChecked = false;
    /** 应用启动后是否已经检查过PUSH */
    public static boolean isPushed = false;
    /** 用户帐户改变 */
    public static OnAccountChange accountChangeCallback;
    /** 用户已获取的彩蛋数量 */
    public static int eggCount = -1;
    /** 用户已获取的彩蛋列表 */
    public static List<Egg> eggList = null;
    /** 用户已获取的彩蛋号码 */
    public static Set<String> eggNums = null;
    /** 是否显示彩蛋收纳盒 */
    public static boolean isEggsBoxShow = false;
    /** 消息推送的ID */
    public static int pushID = 0;
    /** 找到彩蛋的回调接口 */
    public static EggObtainedCallback eggsBoxShowListener;

    @Override
    public void onCreate() {
        super.onCreate();
        // 实例化SharedPreferences
        prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
        editor = prefs.edit();
        eggPrefs = getSharedPreferences(Constants.EGG_PREFS_NAME, MODE_PRIVATE);
        eggEditor = eggPrefs.edit();
        mInstance = this;
        aServices = new AccountInfoServices(this);
        eServices = new ExpressServices(this);
        // 检查工作目录
        checkWorkDir();
        // 友盟场景类型设置接口
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        // 初始化ApplicationToast
        AppToast.init(this);
        // 初始化NoHttp
        NoHttp.initialize(this);
    }

    /** 得到本Application实例 */
    public static AccountApp getInstance() {
        return mInstance;
    }

    /**
     * 检查工作目录和下载目录是否存在，不存在则创建
     */
    private void checkWorkDir() {
        File dir = new File(Constants.WORK_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 得到对话框构建器实例
     * @param context
     * You need to use your Activity as the Context for the Dialog not the Application.
     * @return
     */
    public static AlertDialog.Builder getAlertDialogBuilder(Activity context) {
        return new AlertDialog.Builder(context);
    }

    /**
     * 获取当前版本号
     *
     * @return
     */
    public int getVersionCode() {
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo;
        int versionCode = 0;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionCode = packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本名称
     *
     * @return 版本名称
     */
    public String getVersionName() {
        String packageName = getPackageName();
        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(packageName, 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重新创建所有Activity
     */
    public static void recreateActivity() {
        for (int i = 0; i < activityList.size(); i++) {
            activityList.get(i).recreate();
        }
    }

    /**
     * 触发彩蛋
     * @param activity
     */
    public void triggerEgg(Activity activity, int eggNum) {
        String[] num = {"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩"};
        if (eggNums.contains(String.valueOf(eggNum))) {
            return;
        }
        Egg egg = EggUtils.getEggByNum(eggNum);
        AlertDialog.Builder builder = getAlertDialogBuilder(activity);
        View dialogView = activity.getLayoutInflater().inflate(R.layout.dialog_egg, null);
        TextView tvEggTitle = (TextView) dialogView.findViewById(R.id.tvEggTitle);
        ImageView ivEggImg = (ImageView) dialogView.findViewById(R.id.ivEggImg);
        TextView tvEggMsg = (TextView) dialogView.findViewById(R.id.tvEggMsg);
        Button btnEggOK = (Button) dialogView.findViewById(R.id.btnEggOK);
        builder.setView(dialogView);
        final AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        tvEggTitle.setText("捡到彩蛋 " + num[eggNum - 1]);
        ivEggImg.setImageResource(egg.getEggDrawable());
        tvEggMsg.setText(egg.getEggMsg());
        btnEggOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

        if (!isEggsBoxShow) {
            if (eggsBoxShowListener != null) {
                eggsBoxShowListener.ShowEggsBox();
            }
            eggEditor.putBoolean(Constants.EGG_BOX, true).commit();
        }
        eggCount++;
        eggList.add(egg);
        eggNums.add(String.valueOf(eggNum));
        eggEditor.remove(Constants.EGG_SET).commit();
        eggEditor.putStringSet(Constants.EGG_SET, eggNums).commit();
    }
}
 public interface OnCheckUpdateCallback {
    /**
     * 有更新
     * @param msg 更新信息
     */
    void onUpdate(UpdateMsg msg);

    /**
     * 无更新
     */
    void onNoUpdate();

    /**
     * 检查更新失败
     */
    void onNull();
}
 public interface PushCallback {
    /** 新消息 */
    void newPush(RecentPost post);
}
 public class NewVersionDialog extends Dialog {
    private Activity context;
    private UpdateMsg updateMsg;
    private Button btnCancel, btnUpdate;
    private String downloadUrl;

    public NewVersionDialog(Activity context, UpdateMsg updateMsg) {
        super(context);
        this.context = context;
        this.updateMsg = updateMsg;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  // 取消默认标题栏
        View contentView = View.inflate(context, R.layout.dialog_new_version, null);
        ((TextView) contentView.findViewById(R.id.tvVersionName)).setText(updateMsg.getVersionName());
        ((TextView) contentView.findViewById(R.id.tvSize)).setText(updateMsg.getSize());
        ((TextView) contentView.findViewById(R.id.tvUpdateDate)).setText(updateMsg.getUpdateDate());
        ((TextView) contentView.findViewById(R.id.tvUpdateLog)).setText(updateMsg.getUpdateLog());

        downloadUrl = updateMsg.getDownloadUrl();
        btnCancel = (Button) contentView.findViewById(R.id.btnCancel);
        btnUpdate = (Button) contentView.findViewById(R.id.btnUpdate);
        setContentView(contentView);
        setListener();
    }

    private void setListener() {
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                AppToast.showToast("正在下载新版本安装包。");
                ApkDownloader apkDownloader = new ApkDownloader();
                apkDownloader.downloadFile(context, downloadUrl);
            }
        });
    }
}
 public class ExtFragment extends Fragment implements View.OnClickListener, EggObtainedCallback {
    private View view;
    private FrameLayout flAddAccount, flDelAccounts, flQueryInfo, flBrowserLogin;
    private FrameLayout flIPTV, flNavigator, flRecentPosts, flExpress, flSchoolCalendar;
    private FrameLayout flColorTheme, flAppFAQ, flCheckUpdate, flAbout;
    private FrameLayout flEggBox;
    private TextView tvThemeName, tvVersion;
    private ProgressDialog progressDialog;
    private static final String IPGW_URL = "https://ipgw.neu.edu.cn/";

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

    private void initView() {
        flAddAccount = (FrameLayout) view.findViewById(R.id.flAddAccount);
        flDelAccounts = (FrameLayout) view.findViewById(R.id.flDelAccounts);
        flQueryInfo = (FrameLayout) view.findViewById(R.id.flQueryInfo);
        flBrowserLogin = (FrameLayout) view.findViewById(R.id.flBrowserLogin);
        flIPTV = (FrameLayout) view.findViewById(R.id.flIPTV);
        flNavigator = (FrameLayout) view.findViewById(R.id.flNavigator);
        flRecentPosts = (FrameLayout) view.findViewById(R.id.flRecentPosts);
        flExpress = (FrameLayout) view.findViewById(R.id.flExpress);
        flSchoolCalendar = (FrameLayout) view.findViewById(R.id.flSchoolCalendar);
        flColorTheme = (FrameLayout) view.findViewById(R.id.flColorTheme);
        flAppFAQ = (FrameLayout) view.findViewById(R.id.flAppFAQ);
        flCheckUpdate = (FrameLayout) view.findViewById(R.id.flCheckUpdate);
        flAbout = (FrameLayout) view.findViewById(R.id.flAbout);
        flEggBox = (FrameLayout) view.findViewById(R.id.flEggBox);
        tvThemeName = (TextView) view.findViewById(R.id.tvThemeName);
        tvVersion = (TextView) view.findViewById(R.id.tvVersion);

        progressDialog = new ProgressDialog(getActivity(), "信息查询中...");
    }

    private void setListener() {
        flAddAccount.setOnClickListener(this);
        flDelAccounts.setOnClickListener(this);
        flQueryInfo.setOnClickListener(this);
        flBrowserLogin.setOnClickListener(this);
        flIPTV.setOnClickListener(this);
        flNavigator.setOnClickListener(this);
        flRecentPosts.setOnClickListener(this);
        flExpress.setOnClickListener(this);
        flSchoolCalendar.setOnClickListener(this);
        flColorTheme.setOnClickListener(this);
        flAppFAQ.setOnClickListener(this);
        flCheckUpdate.setOnClickListener(this);
        flAbout.setOnClickListener(this);
        flEggBox.setOnClickListener(this);
        AccountApp.eggsBoxShowListener = this;
    }

    @Override
    public void onResume() {
        super.onResume();
        tvThemeName.setText(AccountApp.colorThemeName);
        // 确定是否显示彩蛋收纳盒
        if (AccountApp.isEggsBoxShow) {
            flEggBox.setVisibility(View.VISIBLE);
        } else {
            flEggBox.setVisibility(View.GONE);
        }
        // 设置版本名称
        tvVersion.setText(AccountApp.getInstance().getVersionName());
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.flAddAccount:
                // 添加帐号
                intent.setClass(getActivity(), AccountActivity.class);
                startActivity(intent);
                break;
            case R.id.flDelAccounts:
                // 删除已保存的帐号
                AlertDialog.Builder builder = AccountApp.getAlertDialogBuilder(getActivity());
                View dialogView = LayoutInflater.from(getActivity())
                    .inflate(R.layout.dialog_del_accounts, null);
                builder.setView(dialogView);
                final AlertDialog dialog = builder.create();
                Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
                Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                btnOK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AccountApp.aServices.deleteAccountInfo();
                        AppToast.showToast(R.string.delete_account_successfully);
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.flQueryInfo:
                // 查询在线信息
                // 友盟统计：查询流量
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.QUERY_FLOW);
                queryOnlineInfo();
                break;
            case R.id.flBrowserLogin:
                // 从浏览器登录
                // 友盟统计：从浏览器登录
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.IPGW_BROSWER);
                try {
                    Uri uri = Uri.parse(IPGW_URL);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(uri);
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    AppToast.showToast("您没有安装浏览器。");
                }
                break;
            case R.id.flIPTV:
                // 网络电视
                // 友盟统计：看电视
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.WATCH_TV);
                // 检查设备是否连接到WiFi
                try {
                    if (!NetWorkUtils.isWifiByType(getActivity())) {
                        AppToast.showToast("设备未接入WiFi。");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                intent.setClass(getActivity(), NeuHdtvListActivity.class);
                startActivity(intent);
                break;
            case R.id.flNavigator:
                // 网址导航
                // 友盟统计：网址导航
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.NEU_NAVIGATOR);
                websiteNavigator();
                break;
            case R.id.flRecentPosts:
                // 最新网络中心黑板报
                // 友盟统计：最新网络中心黑板报
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.RECENT_POSTS);
                if (NetWorkUtils.isConnectedByState(getActivity())) {
                    intent.setClass(getActivity(), RecentPostsActivity.class);
                    startActivity(intent);
                } else {
                    // 未连接到网络
                    AppToast.showToast(R.string.network_unavailable);
                }
                break;
            case R.id.flExpress:
                // 快递查询
                // 友盟统计：快递查询
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.EXPRESS_QUERY);
                intent.setClass(getActivity(), ExpressActivity.class);
                startActivity(intent);
                break;
            case R.id.flSchoolCalendar:
                // 查看校历
                // 友盟统计：查看校历
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.SCHOOL_CALENDER);
                if (NetWorkUtils.isConnectedByState(getActivity())) {
                    intent.setClass(getActivity(), CalendarActivity.class);
                    startActivity(intent);
                } else {
                    AppToast.showToast(R.string.network_unavailable);
                }
                break;
            case R.id.flColorTheme:
                // 色彩主题
                // 友盟统计：色彩主题
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.COLOR_THEME);
                intent.setClass(getActivity(), ColorThemeActivity.class);
                startActivity(intent);
                break;
            case R.id.flAppFAQ:
                // 应用通知
                // 友盟统计：应用通知
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.APP_FAQ);
                if (NetWorkUtils.isConnectedByState(getActivity())) {
                    intent.setClass(getActivity(), AppFAQActivity.class);
                    startActivity(intent);
                } else {
                    // 未连接到网络
                    AppToast.showToast(R.string.network_unavailable);
                }
                break;
            case R.id.flCheckUpdate:
                // 检查更新
                // 友盟统计：检查更新
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.CHECK_UPDATE);
                MainActivity activity = (MainActivity) getActivity();
                if (activity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    activity.writeExternalStorage();
                } else {
                    activity.requestPermissions(BaseActivity.WRITE_EXTERNAL_STORAGE_CODE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                break;
            case R.id.flAbout:
                // 关于
                // 友盟统计：关于
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.ABOUT_IPGW);
                intent.setClass(getActivity(), AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.flEggBox:
                // 彩蛋收纳盒
                // 友盟统计：彩蛋收纳盒
                MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.EGG_BOX);
                intent.setClass(getActivity(), EggActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 网址导航
     */
    private void websiteNavigator() {
        AlertDialog.Builder builder = AccountApp.getAlertDialogBuilder(getActivity());
        View dialogView = LayoutInflater.from(getActivity())
            .inflate(R.layout.dialog_website_navigator, null);
        builder.setView(dialogView);
        final AlertDialog dialog = builder.create();
        ListView lvWebsite = (ListView) dialogView.findViewById(R.id.lvWebsite);
        lvWebsite.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.item_simple_list,
            getResources().getStringArray(R.array.website_navigator)));

        lvWebsite.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String url = "";
                switch (position) {
                    case 0:
                        url = "http://www.neu.edu.cn/";
                        break;
                    case 1:
                        url = "http://www.neu.edu.cn/info_calender.html";
                        break;
                    case 2:
                        url = "http://bb.neu.edu.cn/";
                        break;
                    case 3:
                        url = "http://aao.neu.edu.cn/";
                        break;
                    case 4:
                        url = "http://202.118.8.4/index.html";
                        break;
                    case 5:
                        url = "http://ecard.neu.edu.cn/";
                        break;
                    case 6:
                        url = "http://stu.neu.edu.cn/";
                        break;
                    case 7:
                        url = "http://www.neupioneer.com/index.html";
                        break;
                    case 8:
                        url = "http://ipgw.neu.edu.cn:8800/";
                        break;
                    case 9:
                        url = "http://hdtv.neu6.edu.cn/";
                        break;
                    default:
                        break;
                }
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                ComponentName componentName = intent.resolveActivity(getActivity().getPackageManager());
                if (componentName != null) {
                    startActivity(intent);
                } else {
                    AppToast.showToast("您没有安装浏览器。");
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 查询在线信息
     */
    private void queryOnlineInfo() {
        progressDialog.show();
        GetOnlineInfoTask task = new GetOnlineInfoTask(new OnlineInfoCallback() {
            @Override
            public void onlineInfo(String[] info) {
                if (isAdded()) {    // 防止Fragment not attached to Activity
                    progressDialog.dismiss();
                    AlertDialog.Builder builder = AccountApp.getAlertDialogBuilder(getActivity());
                    View dialogView = LayoutInflater.from(getActivity())
                        .inflate(R.layout.dialog_online_info, null);
                    builder.setView(dialogView);
                    final AlertDialog dialog3 = builder.create();
                    TextView tvCurrentAccount = (TextView) dialogView.findViewById(R.id.tvCurrentAccount);
                    TextView tvOnlineInfo = (TextView) dialogView.findViewById(R.id.tvOnlineInfo);
                    Button btnOK3 = (Button) dialogView.findViewById(R.id.btnOK);
                    tvCurrentAccount.setText("帐户：" + AccountApp.lastSuccess);
                    final String infoText = getActivity().getString(R.string.online_info_statement) +
                        "\n\n已用流量：" + info[0] + "\n已用时长：" + info[1] +
                        "\n帐户余额：" + info[2] + "\n当前地址：" + info[3];
                    tvOnlineInfo.setText(infoText);
                    btnOK3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog3.dismiss();
                        }
                    });
                    tvOnlineInfo.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            // 复制在线信息，并触发彩蛋
                            ClipboardManager cmbName = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                            ClipData clipDataName = ClipData.newPlainText(null, infoText);
                            cmbName.setPrimaryClip(clipDataName);
                            AppToast.showToast("信息已复制。");
                            AccountApp.getInstance().triggerEgg(getActivity(), 2);
                            return true;
                        }
                    });
                    dialog3.show();
                }
            }

            @Override
            public void occurException(int type) {
                if (isAdded()) {    // 防止Fragment not attached to Activity
                    AlertDialog.Builder builder;    // Dialog Builder
                    View dialogView;    // 自定义的Dialog视图
                    switch (type) {
                        case OnlineInfoCallback.FLOW_ERROR:
                            progressDialog.dismiss();
                            builder = AccountApp.getAlertDialogBuilder(getActivity());
                            dialogView = LayoutInflater.from(getActivity())
                                .inflate(R.layout.dialog_account_invalid, null);
                            builder.setView(dialogView);
                            final AlertDialog dialog1 = builder.create();
                            Button btnOK1 = (Button) dialogView.findViewById(R.id.btnOK);
                            btnOK1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog1.dismiss();
                                }
                            });
                            dialog1.show();
                            break;
                        case OnlineInfoCallback.FLOW_NULL:
                            progressDialog.dismiss();
                            builder = AccountApp.getAlertDialogBuilder(getActivity());
                            dialogView = LayoutInflater.from(getActivity())
                                .inflate(R.layout.dialog_account_invalid, null);
                            builder.setView(dialogView);
                            final AlertDialog dialog2 = builder.create();
                            Button btnOK2 = (Button) dialogView.findViewById(R.id.btnOK);
                            btnOK2.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog2.dismiss();
                                }
                            });
                            dialog2.show();
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        task.execute();
    }

    @Override
    public void ShowEggsBox() {
        AccountApp.isEggsBoxShow = true;
        flEggBox.setVisibility(View.VISIBLE);
    }
}
 public class GWFragment extends Fragment implements OnAccountChange {
    private EditText etUserName, etPassword;
    private TextView tvState, tvReason, tvIp, tvBalance, tvUsedFlow, tvUsedTime;
    private Button btnLogout, btnConnectPC, btnConnect, btnDisconnectAll;
    private Button btnMoreUsers;
    private AccountInfo accountInfo;
    private UserListDialog dialog = null;
    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_gw, container, false);
        initView();
        setListener();
        setData(savedInstanceState);
        return view;
    }

    private void initView() {
        etUserName = (EditText) view.findViewById(R.id.etUsername);
        etPassword = (EditText) view.findViewById(R.id.etPassword);
        btnLogout = (Button) view.findViewById(R.id.btnLogout);
        btnConnectPC = (Button) view.findViewById(R.id.btnConnectPC);
        btnConnect = (Button) view.findViewById(R.id.btnConnect);
        btnDisconnectAll = (Button) view.findViewById(R.id.btnDisconnectAll);
        btnMoreUsers = (Button) view.findViewById(R.id.btnMoreUsers);
        tvState = (TextView) view.findViewById(R.id.tvState);
        tvReason = (TextView) view.findViewById(R.id.tvReason);
        tvIp = (TextView) view.findViewById(R.id.tvIp);
        tvBalance = (TextView) view.findViewById(R.id.tvBalance);
        tvUsedFlow = (TextView) view.findViewById(R.id.tvUsedFlow);
        tvUsedTime = (TextView) view.findViewById(R.id.tvUsedTime);
    }


    private void setListener() {
        btnConnect.setFocusable(true);
        btnConnect.requestFocus();
        btnConnect.setOnClickListener(new ConnectListener());
        btnConnectPC.setOnClickListener(new ConnectPCListener());
        btnLogout.setOnClickListener(new LogoutListener());
        btnDisconnectAll.setOnClickListener(new DisconnectAllListener());
        // 选择用户帐户
        btnMoreUsers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new UserListDialog(getActivity(), GWFragment.this);
                dialog.show();
            }
        });

        AccountApp.accountChangeCallback = this;    // 注册用户帐户改变监听器

        // 长按用户名输入框可以设置默认账户
        etUserName.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 设置当前帐号为默认帐号
                final String userName = etUserName.getText().toString();
                final String password = etPassword.getText().toString();

                if (null != AccountApp.aServices.getAccountInfoByUserName(userName)) {
                    // 说明数据库中已有该账户，则直接设置默认帐号
                    final AlertDialog.Builder builder = AccountApp.getAlertDialogBuilder(getActivity());
                    View dialogView = LayoutInflater.from(getActivity())
                            .inflate(R.layout.dialog_default_account, null);
                    builder.setView(dialogView);
                    final AlertDialog dialog = builder.create();
                    TextView tvDefaultAccountMsg = (TextView) dialogView.findViewById(R.id.tvDefaultAccountMsg);
                    Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
                    Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
                    tvDefaultAccountMsg.setText(getActivity().getString(R.string.set_current_account_default, userName));
                    btnCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    btnOK.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AccountApp.defaultUserName = userName;
                            AccountApp.getInstance().editor.putString(Constants.DEFAULT_ACCOUNT, userName).apply();
                            AccountApp.aServices.updatePassword(userName, password);   // 更新数据库
                            AppToast.showToast(R.string.account_ready);
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                } else if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
                    // 账户或者密码为空
                    AppToast.showToast(R.string.userName_or_psw_is_null);
                } else {
                    // 说明数据库中没有该账户
                    // 将该账户添加到数据库中，再设置默认帐号
                    AlertDialog.Builder builder = AccountApp.getAlertDialogBuilder(getActivity());
                    View dialogView = LayoutInflater.from(getActivity())
                            .inflate(R.layout.dialog_default_account, null);
                    builder.setView(dialogView);
                    final AlertDialog dialog = builder.create();
                    TextView tvDefaultAccountMsg = (TextView) dialogView.findViewById(R.id.tvDefaultAccountMsg);
                    Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
                    Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
                    tvDefaultAccountMsg.setText(getActivity().getString(R.string.save_and_set_default, userName));
                    btnCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    btnOK.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AccountApp.aServices.insertAccountInfo(new AccountInfo(userName, password, Constants.INSIDE_CHINA));
                            AccountApp.defaultUserName = userName;
                            AccountApp.getInstance().editor.putString(Constants.DEFAULT_ACCOUNT, userName).apply();
                            AppToast.showToast(R.string.account_ready);
                            dialog.dismiss();
                        }
                    });

                    dialog.show();
                }
                return false;
            }
        });
    }

    /**
     * 读取上次保存的状态或重新初始化
     *
     * @param data
     */
    public void setData(Bundle data) {
        if (data != null && data.size() > 0) {
            etUserName.setText(data.getString("etUsername"));
            etPassword.setText(data.getString("etPassword"));
            tvState.setText(data.getString("tvState"));
            tvReason.setText(data.getString("tvReason"));
            tvBalance.setText(data.getString("tvBalance"));
            tvUsedFlow.setText(data.getString("tvUsedFlow"));
            tvUsedTime.setText(data.getString("tvUsedTime"));
            tvIp.setText(data.getString("tvIp"));
        } else {
            init();
        }
    }

    /**
     * 保存当前Fragment状态
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("etUsername", etUserName.getText().toString());
        outState.putString("etPassword", etPassword.getText().toString());
        outState.putString("tvState", tvState.getText().toString());
        outState.putString("tvReason", tvReason.getText().toString());
        outState.putString("tvBalance", tvBalance.getText().toString());
        outState.putString("tvUsedFlow", tvUsedFlow.getText().toString());
        outState.putString("tvUsedTime", tvUsedTime.getText().toString());
        outState.putString("tvIp", tvIp.getText().toString());
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 更新视图
            updateOnlineInfo();
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        updateOnlineInfo();
        // 注册一个接收器，在服务结束时接收更新
        IntentFilter filter = new IntentFilter(IpgwService.ACTION_IPGW);
        getActivity().registerReceiver(mReceiver, filter);

    }

    @Override
    public void onPause() {
        super.onPause();
        // 解除接收器的注册
        getActivity().unregisterReceiver(mReceiver);
    }

    /**
     * 更新在线信息显示
     */
    private void updateOnlineInfo() {
        OnlineInfo onlineInfo = IpgwService.getsInfo();
        tvState.setText(onlineInfo.getState());
        tvReason.setText(onlineInfo.getReason());
        tvIp.setText(onlineInfo.getIp());
        tvUsedTime.setText(onlineInfo.getUsedTime());
        tvUsedFlow.setText(onlineInfo.getUsedFlow());
        tvBalance.setText(onlineInfo.getBalance());
    }

    /**
     * 初始化两个EditText中的内容
     */
    private void init() {
        accountInfo = AccountApp.aServices.getAccountInfoByUserName(AccountApp.defaultUserName);
        if (accountInfo != null) {
            etUserName.setText(AccountApp.defaultUserName);
            etUserName.setSelection(AccountApp.defaultUserName.length());
            etPassword.setText(accountInfo.getPsw());
        }
    }

    private void ReSetMsg() {
        tvState.setText("");
        tvReason.setText("");
        tvBalance.setText("");
        tvUsedFlow.setText("");
        tvUsedTime.setText("");
        tvIp.setText("");
    }

    /**
     * 更改帐户
     *
     * @param accountInfo 新账户
     */
    @Override
    public void onNewAccount(AccountInfo accountInfo) {
        etUserName.setText(accountInfo.getUserName());
        etUserName.setSelection(accountInfo.getUserName().length());
        etPassword.setText(accountInfo.getPsw());
    }

    /**
     * 连接网络按钮的事件监听
     */
    private class ConnectListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // 重置提示信息
            ReSetMsg();
            String[] usernamePsw = getUsernamePsw();
            if (usernamePsw[0].equals("") || usernamePsw[1].equals("")) {
                tvState.setText(getString(R.string.msg_state_n));
                tvReason.setText(getString(R.string.msg_reason_1));
                return;
            }

            //连接网络
            if (NetWorkUtils.isConnectedByState(getActivity())) {    // 网络状态可用
                // 执行连网操作
                executeOperation(IPGWOperation.CONNECT, usernamePsw[0], usernamePsw[1]);
            } else {
                pleaseCheckNetworkTip();
            }
            //获取在线信息
            getOnlineInfo();
            // 友盟统计：连接网络
            MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.CONNECT_CLICK);
        }
    }

    /**
     * 模拟PC端连接网络按钮的事件监听
     */
    private class ConnectPCListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // 重置提示信息
            ReSetMsg();
            String[] usernamePsw = getUsernamePsw();
            if (usernamePsw[0].equals("") || usernamePsw[1].equals("")) {
                tvState.setText(getString(R.string.msg_state_n));
                tvReason.setText(getString(R.string.msg_reason_1));
                return;
            }
            //连接网络
            if (NetWorkUtils.isConnectedByState(getActivity())) {    // 网络状态可用
                // 执行连网操作
                executeOperation(IPGWOperation.CONNECT_PC, usernamePsw[0], usernamePsw[1]);
            } else {
                pleaseCheckNetworkTip();
            }
            //获取在线信息
            getOnlineInfo();
            // 友盟统计：连接网络
            MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.CONNECT_CLICK);
        }
    }

    /**
     * 注销登录按钮的事件监听
     */
    private class LogoutListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // 友盟统计：断开网络
            MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.DISCONNECT_CLICK);
            // 重置提示信息
            ReSetMsg();
            String[] usernamePsw = getUsernamePsw();
            if (usernamePsw[0].equals("") || usernamePsw[1].equals("")) {
                tvState.setText(getString(R.string.msg_state_unknown));
                tvReason.setText(getString(R.string.msg_reason_1));
                return;
            }
            // 执行断网操作
            if (NetWorkUtils.isConnectedByState(getActivity())) {    // 网络状态可用
                executeOperation(IPGWOperation.DISCONNECT, usernamePsw[0], usernamePsw[1]);
            } else {
                pleaseCheckNetworkTip();
            }
        }
    }

    /**
     * 断开全部连接按钮的事件监听
     */
    private class DisconnectAllListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // 友盟统计：断开网络
            MobclickAgent.onEvent(getActivity(), Constants.UmengStatistics.DISCONNECT_CLICK);
            // 重置提示信息
            ReSetMsg();
            String[] usernamePsw = getUsernamePsw();
            if (usernamePsw[0].equals("") || usernamePsw[1].equals("")) {
                tvState.setText(getString(R.string.msg_state_n));
                tvReason.setText(getString(R.string.msg_reason_1));
                return;
            }
            // 执行断网操作
            if (NetWorkUtils.isConnectedByState(getActivity())) {    // 网络状态可用
                executeOperation(IPGWOperation.DISCONNECT_ALL, usernamePsw[0], usernamePsw[1]);
            } else {
                pleaseCheckNetworkTip();
            }
        }
    }

    /**
     * 获取在线信息
     */
    private void getOnlineInfo() {
        if (NetWorkUtils.isConnectedByState(getActivity())) {        // 网络状态可用
            GetOnlineInfoTask task = new GetOnlineInfoTask(new OnlineInfoCallback() {
                @Override
                public void onlineInfo(String[] info) {
                    if (isAdded()) {    // 防止Fragment not attached to Activity
                       /*
                        已用流量：173.03M
                        已用时长：10:18:43
                        帐户余额：45.00
                        IP地址：58.154.209.141
                        */
                        tvUsedFlow.setText(info[0]);
                        tvUsedTime.setText(info[1]);
                        tvBalance.setText(info[2]);
                        tvIp.setText(info[3]);
                        String ip = info[3].replace("当前地址：", "");
                        AccountApp.getInstance().editor.putString(Constants.IP_ADDRESS, ip).apply();
                        // 修改连接状态显示
                        tvState.setText(getString(R.string.msg_state_y));
                        tvReason.setText("");
                        // 保存连接成功的帐号
                        AccountApp.lastSuccess = etUserName.getText().toString();
                        // 已用时长超700小时可获得彩蛋
                        try {
                            if (Integer.parseInt(info[1].split(":")[0]) >= 700) {
                                AccountApp.getInstance().triggerEgg(getActivity(), 6);
                            }
                        } catch (Exception e) {
                            // 异常，多数为NumberFormatException
                        }
                    }
                }

                @Override
                public void occurException(int type) {
                    if (isAdded()) {    // 防止Fragment not attached to Activity
                        switch (type) {
                            case OnlineInfoCallback.FLOW_ERROR:
                                tvUsedFlow.setText(R.string.msg_yiyongll_null);
                                tvUsedTime.setText(getString(R.string.msg_yiyongsc_null));
                                tvBalance.setText(getString(R.string.msg_yue_null));
                                tvIp.setText(getString(R.string.msg_address_null));
                                break;
                            case OnlineInfoCallback.FLOW_NULL:
                                tvUsedFlow.setText(getString(R.string.msg_yiyongll_null));
                                tvUsedTime.setText(getString(R.string.msg_yiyongsc_null));
                                tvBalance.setText(getString(R.string.msg_yue_null));
                                tvIp.setText(getString(R.string.msg_address_null));
                                break;
                            default:
                                break;
                        }
                    }
                }
            });
            task.execute();
        }
    }

    /**
     * 执行操作，得到连网和断网信息
     *
     * @param operation 操作类型
     */
    public void executeOperation(final int operation, final String username, String password) {
        tvState.setText(getString(R.string.requesting));

        GwOperationTask task = new GwOperationTask(operation, new GwStateCallback() {
            @Override
            public void postGwState(int state) {
                if (isAdded()) {    // 防止Fragment not attached to Activity
                    String[] disconnectInfo;
                    String[] connectInfo;
                    switch (state) {
                        case 1:
                            // Authentication failed 验证失败
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_2));
                            break;
                        case 2:
                            // 无法登录
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_3));
                            break;
                        case 3:
                            // You are already online
                            tvState.setText(getString(R.string.msg_state_unknown));
                            tvReason.setText(getString(R.string.msg_reason_8));
                            break;
                        case 4:
                            // 密码错误
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_4));
                            break;
                        case 5:     // 网络已断开
                        case 7:     // 注销成功
                            disconnectInfo = IPGWOperation.getInformation(operation);
                            tvState.setText(disconnectInfo[1]);
                            tvReason.setText(disconnectInfo[2]);
                            break;
                        case 6:     // 网络已连接
                        case 11:    // 客户端已连接
                            connectInfo = IPGWOperation.getInformation(operation);
                            tvState.setText(connectInfo[1]);
                            tvReason.setText(connectInfo[2]);
                            // 保存连接成功的帐号
                            AccountApp.lastSuccess = username;
                            // 检查推送
                            ((MainActivity) getActivity()).checkPush();
                            break;
                        case 8:
                            // 无法连接到IPGW网关
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_7));
                            break;
                        case 9:
                            // 内部服务器错误
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_6));
                            break;
                        case 12:
                            // 您似乎未曾连接到网络
                            tvState.setText(getString(R.string.msg_state_dis_already));
                            tvReason.setText("");
                            break;
                        case 13:
                            // 用户不存在
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_10));
                            break;
                        case 14:
                            // 用户已欠费
                            tvState.setText(getString(R.string.msg_state_n));
                            tvReason.setText(getString(R.string.msg_reason_11));
                            break;
                        case 10:
                        case -1:
                        case -2:
                            // 请检查网络设置
                            pleaseCheckNetworkTip();
                        default:
                            break;
                    }
                }
            }
        });
        task.execute(username, password);
    }

    /**
     * 获取用户名和密码输入框的内容
     *
     * @return
     */
    private String[] getUsernamePsw() {
        String username = etUserName.getText().toString();
        String password = etPassword.getText().toString();
        return new String[]{username, password};
    }

    /**
     * 未接入校园网，显示提示信息
     */
    private void pleaseCheckNetworkTip() {
        tvState.setText(getString(R.string.msg_state_n));
        tvReason.setText(getString(R.string.msg_reason_5));
    }
}
 public class RecentPost {
    /** 黑板报标题 */
    private String title;
    /** 发布日期 */
    private String date;
    /** 黑板报内容 */
    private String content;
    /** 详情网址 */
    private String url;
    /** PUSH的序号 */
    private int id;

    public RecentPost(String title, String date, String content, String url) {
        this.title = title;
        this.date = date;
        this.content = content;
        this.url = url;
    }

    public RecentPost(String title, String date, String content, String url, int id) {
        this.title = title;
        this.date = date;
        this.content = content;
        this.url = url;
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDate() {
        return date;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
 public class UpdateMsg {
    /** 状态码 */
    private int code;
    /** 应用名称 */
    private String name;
    /** 应用版本号 */
    private int version;
    /** 版本名称 */
    private String versionName;
    /** 安装包大小 */
    private String size;
    /** 更新日期 */
    private String updateDate;
    /** 平台（Android、IOS） */
    private String platform;
    /** 更新日志 */
    private String updateLog;
    /** 安装包渠道 */
    private String channel;
    /** 安装包下载链接 */
    private String downloadUrl;

    public UpdateMsg() {
    }

    public UpdateMsg(int code, String name, int version, String versionName, String size, String updateDate, String platform, String updateLog, String channel, String downloadUrl) {
        this.code = code;
        this.name = name;
        this.version = version;
        this.versionName = versionName;
        this.size = size;
        this.updateDate = updateDate;
        this.platform = platform;
        this.updateLog = updateLog;
        this.channel = channel;
        this.downloadUrl = downloadUrl;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(String updateDate) {
        this.updateDate = updateDate;
    }

    public String getPlatform() {
        return platform;
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }

    public String getUpdateLog() {
        return updateLog;
    }

    public void setUpdateLog(String updateLog) {
        this.updateLog = updateLog;
    }

    public String getChannel() {
        return channel;
    }

    public void setChannel(String channel) {
        this.channel = channel;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }
}
 public class CheckUpdateTask extends AsyncTask<Void, Void, Void> {
    private static final String PATH = "http://duduhuo.cc/ddh/check_update.php?appname=ipgwlt";
    private static final String ENCODING = "UTF-8";
    private static final int NO_UPDATE = 0x0000;
    private static final int UPDATE = 0x0001;
    private static final int NULL = 0x0002;
    private OnCheckUpdateCallback callback;
    private UpdateMsg updateMsg;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == NO_UPDATE) {
                if (callback != null) {
                    callback.onNoUpdate();
                }
            } else if (msg.what == UPDATE) {
                if (callback != null) {
                    callback.onUpdate(updateMsg);
                }
            } else if (msg.what == NULL) {
                if (callback != null) {
                    callback.onNull();
                }
            }
            return false;
        }
    });
    public CheckUpdateTask(OnCheckUpdateCallback callback) {
        this.callback = callback;
    }
    @Override
    protected Void doInBackground(Void... params) {
        String html = "";
        Request<String> request = NoHttp.createStringRequest(PATH, RequestMethod.GET);
        // 调用同步请求，直接拿到请求结果。
        Response<String> response = NoHttp.startRequestSync(request);
        if (response.isSucceed()) {
            html = response.get();
        }
        try {
            if ("null".equals(html) || "".equals(html)) {
                mHandler.sendEmptyMessage(NULL);
            } else {
                JSONObject json = new JSONObject(html);
                // 获取服务器上的版本号
                int serverVersion = json.getInt("version");
                // 获取本地版本号
                int localVersion = AccountApp.getInstance().getVersionCode();
                // 比较版本号
                if (serverVersion > localVersion) {
                    // 有新版本
                    updateMsg = new UpdateMsg();
                    int code = json.getInt("code");
                    String name = json.getString("name");
                    String versionName = json.getString("versionName");
                    String size = json.getString("size");
                    String updateDate = json.getString("updateDate");
                    String platform = json.getString("platform");
                    String updateLog = json.getString("updateLog");
                    String channel = json.getString("channel");
                    String downloadUrl = json.getString("downloadUrl");
                    updateMsg.setCode(code);
                    updateMsg.setName(name);
                    updateMsg.setVersion(serverVersion);
                    updateMsg.setVersionName(versionName);
                    updateMsg.setSize(size);
                    updateMsg.setUpdateDate(updateDate);
                    updateMsg.setPlatform(platform);
                    updateMsg.setUpdateLog(updateLog);
                    updateMsg.setChannel(channel);
                    updateMsg.setDownloadUrl(downloadUrl);
                    mHandler.sendEmptyMessage(UPDATE);
                } else {
                    // 本地已是最新版本
                    mHandler.sendEmptyMessage(NO_UPDATE);
                }
            }
        } catch (Exception e) {
            mHandler.sendEmptyMessage(NULL);
            e.printStackTrace();
        }
        return null;
    }
}
 public class ReceivePushTask extends AsyncTask<Void, Void, RecentPost> {
    private PushCallback callback;
    private static final String PATH = "http://duduhuo.cc/ddh/ipgw/push.json";

    public ReceivePushTask(PushCallback callback) {
        this.callback = callback;
    }

    @Override
    protected RecentPost doInBackground(Void... params) {
        String jsonStr = "";
        Request<String> request = NoHttp.createStringRequest(PATH, RequestMethod.GET);
        // 调用同步请求，直接拿到请求结果。
        Response<String> response = NoHttp.startRequestSync(request);
        if (response.isSucceed()) {
            jsonStr = response.get();
        }
        try {
            if (!"".equals(jsonStr)) {
                JSONObject json = new JSONObject(jsonStr);
                int id = json.getInt("id");
                // 每条信息只推送一遍
                if (id > AccountApp.pushID) {
                    String title = json.getString("title");
                    String date = json.getString("date");
                    String content = json.getString("content");
                    String url = json.getString("url");
                    return new RecentPost(title, date, content, url, id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(RecentPost post) {
        super.onPostExecute(post);
        if (callback != null && post != null) {
            callback.newPush(post);
        }
    }
} public interface Constants {
    String INSIDE_CHINA = "2";
    /** Activity传递的Intent数据的key */
    String PROGRAM = "program";
    /** Sharedpreferences的名字 */
    String PREFS_NAME = "spc";
    /** 存储彩蛋信息的Sharedpreferences的名字 */
    String EGG_PREFS_NAME = "egg";
    /** Sharedpreferences储存的版本号 */
    String VERSION = "VERSION_CODE";
    /** Sharedpreferences储存的默认帐号 */
    String DEFAULT_ACCOUNT = "DEFAULT_ACCOUNT";
    /** Sharedpreferences储存的临时语言 */
    String TEMP_LANGUAGE = "TEMP_LANGUAGE";
    /** Sharedpreferences储存的默认语言 */
    String DEFAULT_LANGUAGE = "DEFAULT_LANGUAGE";
    /** Sharedpreferences储存的连接IP地址 */
    String IP_ADDRESS = "IP_ADDRESS";
    /** Sharedpreferences储存的色彩主题 */
    String COLOR_THEME = "COLOR_THEME";
    /** Sharedpreferences储存的已接收到的推送的id */
    String PUSH_ID = "PUSH_ID";
    /** Sharedpreferences储存的彩蛋集合 */
    String EGG_SET = "eggset";
    /** Sharedpreferences储存的彩蛋收纳盒是否显示 */
    String EGG_BOX = "eggbox";

    String IPGW_DIR = "neuipgw";
    /**
     * 工作目录
     */
    String WORK_DIR = Environment.getExternalStorageDirectory() + File.separator + IPGW_DIR;
    /**
     * ResultCode：选择快递
     */
    int SHIPPER_RESULT = 1;
    /**
     * 友盟统计相关常量
     */
    interface UmengStatistics {
        /** 连接网络 */
        String CONNECT_CLICK = "connect_click";
        /** 断开网络 */
        String DISCONNECT_CLICK = "disconnect_click";
        /** 查询流量信息 */
        String QUERY_FLOW = "query_flow";
        /** 从浏览器登录 */
        String IPGW_BROSWER = "ipgw_broswer";
        /** 关于IPGW */
        String ABOUT_IPGW = "about_ipgw";
        /** 分享IPGW */
        String SHARE_IPGW = "share_ipgw";
        /** 桌面小工具 */
        String IPGW_TOOL = "ipgw_tool";
        /** 网址导航 */
        String NEU_NAVIGATOR = "neu_navigator";
        /** 用户反馈 */
        String USER_FEEDBACK = "user_feedback";
        /** 看电视 */
        String WATCH_TV = "watch_tv";
        /** 查看校历 */
        String SCHOOL_CALENDER = "school_calender";
        /** 关于作者 */
        String ABOUT_AUTHOR = "about_author";
        /** 色彩主题 */
        String COLOR_THEME = "color_theme";
        /** 检查更新 */
        String CHECK_UPDATE = "check_update";
        /** 彩蛋收纳盒 */
        String EGG_BOX = "egg_box";
        /** 最新网络中心黑板报 */
        String RECENT_POSTS = "recent_posts";
        /** 应用通知 */
        String APP_FAQ = "app_faq";
        /** 快递查询 */
        String EXPRESS_QUERY = "express_query";
        /** 彩蛋 */
        String EGG = "egg";
    }

}
 public class DensityUtil {
    private static int[] deviceWidthHeight = new int[2];
    public static int[] getDeviceInfo(Context context) {
        if ((deviceWidthHeight[0] == 0) && (deviceWidthHeight[1] == 0)) {
            DisplayMetrics metrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay()
                    .getMetrics(metrics);

            deviceWidthHeight[0] = metrics.widthPixels;
            deviceWidthHeight[1] = metrics.heightPixels;
        }
        return deviceWidthHeight;
    }
    /**
     *
     * @param context 上下文
     * @param dpValue dp数值
     * @return dp to  px
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);

    }
    /**
     * 获取屏幕尺寸
     */
    @SuppressWarnings("deprecation")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static Point getScreenSize(Context context){
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2){
            return new Point(display.getWidth(), display.getHeight());
        }else{
            Point point = new Point();
            display.getSize(point);
            return point;
        }
    }
    /**
     *
     * @param context    上下文
     * @param pxValue  px的数值
     * @return  px to dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);

    }
}
 public class NetWorkUtils {
    /** 网络类型 - 无连接 */
    private static final int NETWORK_TYPE_NO_CONNECTION = -1231545315;

    private static final String NETWORK_TYPE_WIFI = "wifi";
    private static final String NETWORK_TYPE_3G = "eg";
    private static final String NETWORK_TYPE_2G = "2g";
    private static final String NETWORK_TYPE_WAP = "wap";
    private static final String NETWORK_TYPE_UNKNOWN = "unknown";
    private static final String NETWORK_TYPE_DISCONNECT = "disconnect";


    /**
     * Get network type
     *
     * @param context context
     * @return 网络状态
     */
    public static int getNetworkType(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager == null
                ? null
                : connectivityManager.getActiveNetworkInfo();
        return networkInfo == null ? -1 : networkInfo.getType();
    }


    /**
     * Get network type name
     *
     * @param context context
     * @return NetworkTypeName
     */
    public static String getNetworkTypeName(Context context) {
        ConnectivityManager manager
                = (ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo;
        String type = NETWORK_TYPE_DISCONNECT;
        if (manager == null ||
                (networkInfo = manager.getActiveNetworkInfo()) == null) {
            return type;
        }

        if (networkInfo.isConnected()) {
            String typeName = networkInfo.getTypeName();
            if ("WIFI".equalsIgnoreCase(typeName)) {
                type = NETWORK_TYPE_WIFI;
            }
            else if ("MOBILE".equalsIgnoreCase(typeName)) {
                String proxyHost = android.net.Proxy.getDefaultHost();
                type = TextUtils.isEmpty(proxyHost)
                        ? (isFastMobileNetwork(context)
                        ? NETWORK_TYPE_3G
                        : NETWORK_TYPE_2G)
                        : NETWORK_TYPE_WAP;
            }
            else {
                type = NETWORK_TYPE_UNKNOWN;
            }
        }
        return type;
    }


    /**
     * Whether is fast mobile network
     *
     * @param context context
     * @return FastMobileNetwork
     */
    private static boolean isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager
                = (TelephonyManager) context.getSystemService(
                Context.TELEPHONY_SERVICE);
        if (telephonyManager == null) {
            return false;
        }

        switch (telephonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false;
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false;
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false;
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true;
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true;
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false;
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true;
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true;
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true;
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true;
            case TelephonyManager.NETWORK_TYPE_EHRPD:
                return true;
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                return true;
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return true;
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return false;
            case TelephonyManager.NETWORK_TYPE_LTE:
                return true;
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                return false;
            default:
                return false;
        }
    }


    /**
     * 获取当前网络的状态
     *
     * @param context 上下文
     * @return 当前网络的状态。具体类型可参照NetworkInfo.State.CONNECTED、NetworkInfo.State.CONNECTED.DISCONNECTED等字段。当前没有网络连接时返回null
     */
    public static NetworkInfo.State getCurrentNetworkState(Context context) {
        NetworkInfo networkInfo
                = ((ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return networkInfo != null ? networkInfo.getState() : null;
    }


    /**
     * 获取当前网络的类型
     *
     * @param context 上下文
     * @return 当前网络的类型。具体类型可参照ConnectivityManager中的TYPE_BLUETOOTH、TYPE_MOBILE、TYPE_WIFI等字段。当前没有网络连接时返回NetworkUtils.NETWORK_TYPE_NO_CONNECTION
     */
    public static int getCurrentNetworkType(Context context) {
        NetworkInfo networkInfo
                = ((ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return networkInfo != null
                ? networkInfo.getType()
                : NETWORK_TYPE_NO_CONNECTION;
    }


    /**
     * 获取当前网络的具体类型
     *
     * @param context 上下文
     * @return 当前网络的具体类型。具体类型可参照TelephonyManager中的NETWORK_TYPE_1xRTT、NETWORK_TYPE_CDMA等字段。当前没有网络连接时返回NetworkUtils.NETWORK_TYPE_NO_CONNECTION
     */
    public static int getCurrentNetworkSubtype(Context context) {
        NetworkInfo networkInfo
                = ((ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return networkInfo != null
                ? networkInfo.getSubtype()
                : NETWORK_TYPE_NO_CONNECTION;
    }


    /**
     * 判断当前网络是否已经连接
     *
     * @param context 上下文
     * @return 当前网络是否已经连接。false：尚未连接
     */
    public static boolean isConnectedByState(Context context) {
        return getCurrentNetworkState(context) == NetworkInfo.State.CONNECTED;
    }


    /**
     * 判断当前网络是否正在连接
     *
     * @param context 上下文
     * @return 当前网络是否正在连接
     */
    public static boolean isConnectingByState(Context context) {
        return getCurrentNetworkState(context) == NetworkInfo.State.CONNECTING;
    }


    /**
     * 判断当前网络是否已经断开
     *
     * @param context 上下文
     * @return 当前网络是否已经断开
     */
    public static boolean isDisconnectedByState(Context context) {
        return getCurrentNetworkState(context) ==
                NetworkInfo.State.DISCONNECTED;
    }


    /**
     * 判断当前网络是否正在断开
     *
     * @param context 上下文
     * @return 当前网络是否正在断开
     */
    public static boolean isDisconnectingByState(Context context) {
        return getCurrentNetworkState(context) ==
                NetworkInfo.State.DISCONNECTING;
    }


    /**
     * 判断当前网络是否已经暂停
     *
     * @param context 上下文
     * @return 当前网络是否已经暂停
     */
    public static boolean isSuspendedByState(Context context) {
        return getCurrentNetworkState(context) == NetworkInfo.State.SUSPENDED;
    }


    /**
     * 判断当前网络是否处于未知状态中
     *
     * @param context 上下文
     * @return 当前网络是否处于未知状态中
     */
    public static boolean isUnknownByState(Context context) {
        return getCurrentNetworkState(context) == NetworkInfo.State.UNKNOWN;
    }


    /**
     * 判断当前网络的类型是否是蓝牙
     *
     * @param context 上下文
     * @return 当前网络的类型是否是蓝牙。false：当前没有网络连接或者网络类型不是蓝牙
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static boolean isBluetoothByType(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
            return false;
        }
        else {
            return getCurrentNetworkType(context) ==
                    ConnectivityManager.TYPE_BLUETOOTH;
        }
    }


    /**
     * 判断当前网络的类型是否是虚拟网络
     *
     * @param context 上下文
     * @return 当前网络的类型是否是虚拟网络。false：当前没有网络连接或者网络类型不是虚拟网络
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static boolean isDummyByType(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
            return false;
        }
        else {
            return getCurrentNetworkType(context) ==
                    ConnectivityManager.TYPE_DUMMY;
        }
    }


    /**
     * 判断当前网络的类型是否是ETHERNET
     *
     * @param context 上下文
     * @return 当前网络的类型是否是ETHERNET。false：当前没有网络连接或者网络类型不是ETHERNET
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static boolean isEthernetByType(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
            return false;
        }
        else {
            return getCurrentNetworkType(context) ==
                    ConnectivityManager.TYPE_ETHERNET;
        }
    }


    /**
     * 判断当前网络的类型是否是移动网络
     *
     * @param context 上下文
     * @return 当前网络的类型是否是移动网络。false：当前没有网络连接或者网络类型不是移动网络
     */
    public static boolean isMobileByType(Context context) {
        return getCurrentNetworkType(context) ==
                ConnectivityManager.TYPE_MOBILE;
    }


    /**
     * 判断当前网络的类型是否是MobileDun
     *
     * @param context 上下文
     * @return 当前网络的类型是否是MobileDun。false：当前没有网络连接或者网络类型不是MobileDun
     */
    public static boolean isMobileDunByType(Context context) {
        return getCurrentNetworkType(context) ==
                ConnectivityManager.TYPE_MOBILE_DUN;
    }


    /**
     * 判断当前网络的类型是否是MobileHipri
     *
     * @param context 上下文
     * @return 当前网络的类型是否是MobileHipri。false：当前没有网络连接或者网络类型不是MobileHipri
     */
    public static boolean isMobileHipriByType(Context context) {
        return getCurrentNetworkType(context) ==
                ConnectivityManager.TYPE_MOBILE_HIPRI;
    }


    /**
     * 判断当前网络的类型是否是MobileMms
     *
     * @param context 上下文
     * @return 当前网络的类型是否是MobileMms。false：当前没有网络连接或者网络类型不是MobileMms
     */
    public static boolean isMobileMmsByType(Context context) {
        return getCurrentNetworkType(context) ==
                ConnectivityManager.TYPE_MOBILE_MMS;
    }


    /**
     * 判断当前网络的类型是否是MobileSupl
     *
     * @param context 上下文
     * @return 当前网络的类型是否是MobileSupl。false：当前没有网络连接或者网络类型不是MobileSupl
     */
    public static boolean isMobileSuplByType(Context context) {
        return getCurrentNetworkType(context) ==
                ConnectivityManager.TYPE_MOBILE_SUPL;
    }


    /**
     * 判断当前网络的类型是否是Wifi
     *
     * @param context 上下文
     * @return 当前网络的类型是否是Wifi。false：当前没有网络连接或者网络类型不是wifi
     */
    public static boolean isWifiByType(Context context) {
        return getCurrentNetworkType(context) == ConnectivityManager.TYPE_WIFI;
    }


    /**
     * 判断当前网络的类型是否是Wimax
     *
     * @param context 上下文
     * @return 当前网络的类型是否是Wimax。false：当前没有网络连接或者网络类型不是Wimax
     */
    public static boolean isWimaxByType(Context context) {
        return getCurrentNetworkType(context) == ConnectivityManager.TYPE_WIMAX;
    }


    /**
     * 判断当前网络的具体类型是否是1XRTT
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是1XRTT。false：当前没有网络连接或者具体类型不是1XRTT
     */
    public static boolean is1XRTTBySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_1xRTT;
    }


    /**
     * 判断当前网络的具体类型是否是CDMA（Either IS95A or IS95B）
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是CDMA。false：当前没有网络连接或者具体类型不是CDMA
     */
    public static boolean isCDMABySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_CDMA;
    }


    /**
     * 判断当前网络的具体类型是否是EDGE
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是EDGE。false：当前没有网络连接或者具体类型不是EDGE
     */
    public static boolean isEDGEBySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_EDGE;
    }


    /**
     * 判断当前网络的具体类型是否是EHRPD
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是EHRPD。false：当前没有网络连接或者具体类型不是EHRPD
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean isEHRPDBySubtype(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return false;
        }
        else {
            return getCurrentNetworkSubtype(context) ==
                    TelephonyManager.NETWORK_TYPE_EHRPD;
        }
    }


    /**
     * 判断当前网络的具体类型是否是EVDO_0
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是EVDO_0。false：当前没有网络连接或者具体类型不是EVDO_0
     */
    public static boolean isEVDO_0BySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_EVDO_0;
    }


    /**
     * 判断当前网络的具体类型是否是EVDO_A
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是EVDO_A。false：当前没有网络连接或者具体类型不是EVDO_A
     */
    public static boolean isEVDO_ABySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_EVDO_A;
    }


    /**
     * 判断当前网络的具体类型是否是EDGE
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是EVDO_B。false：当前没有网络连接或者具体类型不是EVDO_B
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static boolean isEVDO_BBySubtype(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        else {
            return getCurrentNetworkSubtype(context) ==
                    TelephonyManager.NETWORK_TYPE_EVDO_B;
        }
    }


    /**
     * 判断当前网络的具体类型是否是GPRS
     * EVDO_Bam context 上下文
     *
     * @return false：当前网络的具体类型是否是GPRS。false：当前没有网络连接或者具体类型不是GPRS
     */
    public static boolean isGPRSBySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_GPRS;
    }


    /**
     * 判断当前网络的具体类型是否是HSDPA
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是HSDPA。false：当前没有网络连接或者具体类型不是HSDPA
     */
    public static boolean isHSDPABySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_HSDPA;
    }


    /**
     * 判断当前网络的具体类型是否是HSPA
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是HSPA。false：当前没有网络连接或者具体类型不是HSPA
     */
    public static boolean isHSPABySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_HSPA;
    }


    /**
     * 判断当前网络的具体类型是否是HSPAP
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是HSPAP。false：当前没有网络连接或者具体类型不是HSPAP
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static boolean isHSPAPBySubtype(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
            return false;
        }
        else {
            return getCurrentNetworkSubtype(context) ==
                    TelephonyManager.NETWORK_TYPE_HSPAP;
        }
    }


    /**
     * 判断当前网络的具体类型是否是HSUPA
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是HSUPA。false：当前没有网络连接或者具体类型不是HSUPA
     */
    public static boolean isHSUPABySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_HSUPA;
    }


    /**
     * 判断当前网络的具体类型是否是IDEN
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是IDEN。false：当前没有网络连接或者具体类型不是IDEN
     */
    public static boolean isIDENBySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_IDEN;
    }


    /**
     * 判断当前网络的具体类型是否是LTE
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是LTE。false：当前没有网络连接或者具体类型不是LTE
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean isLTEBySubtype(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return false;
        }
        else {
            return getCurrentNetworkSubtype(context) ==
                    TelephonyManager.NETWORK_TYPE_LTE;
        }
    }


    /**
     * 判断当前网络的具体类型是否是UMTS
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是UMTS。false：当前没有网络连接或者具体类型不是UMTS
     */
    public static boolean isUMTSBySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_UMTS;
    }


    /**
     * 判断当前网络的具体类型是否是UNKNOWN
     *
     * @param context 上下文
     * @return false：当前网络的具体类型是否是UNKNOWN。false：当前没有网络连接或者具体类型不是UNKNOWN
     */
    public static boolean isUNKNOWNBySubtype(Context context) {
        return getCurrentNetworkSubtype(context) ==
                TelephonyManager.NETWORK_TYPE_UNKNOWN;
    }


    /**
     * 判断当前网络是否是中国移动2G网络
     *
     * @param context 上下文
     * @return false：不是中国移动2G网络或者当前没有网络连接
     */
    public static boolean isChinaMobile2G(Context context) {
        return isEDGEBySubtype(context);
    }


    /**
     * 判断当前网络是否是中国联通2G网络
     *
     * @param context 上下文
     * @return false：不是中国联通2G网络或者当前没有网络连接
     */
    public static boolean isChinaUnicom2G(Context context) {
        return isGPRSBySubtype(context);
    }


    /**
     * 判断当前网络是否是中国联通3G网络
     *
     * @param context 上下文
     * @return false：不是中国联通3G网络或者当前没有网络连接
     */
    public static boolean isChinaUnicom3G(Context context) {
        return isHSDPABySubtype(context) || isUMTSBySubtype(context);
    }


    /**
     * 判断当前网络是否是中国电信2G网络
     *
     * @param context 上下文
     * @return false：不是中国电信2G网络或者当前没有网络连接
     */
    public static boolean isChinaTelecom2G(Context context) {
        return isCDMABySubtype(context);
    }


    /**
     * 判断当前网络是否是中国电信3G网络
     *
     * @param context 上下文
     * @return false：不是中国电信3G网络或者当前没有网络连接
     */
    public static boolean isChinaTelecom3G(Context context) {
        return isEVDO_0BySubtype(context) || isEVDO_ABySubtype(context) ||
                isEVDO_BBySubtype(context);
    }


    /**
     * 获取Wifi的状态，需要ACCESS_WIFI_STATE权限
     *
     * @param context 上下文
     * @return 取值为WifiManager中的WIFI_STATE_ENABLED、WIFI_STATE_ENABLING、WIFI_STATE_DISABLED、WIFI_STATE_DISABLING、WIFI_STATE_UNKNOWN之一
     * @throws Exception 没有找到wifi设备
     */
    public static int getWifiState(Context context) throws Exception {
        WifiManager wifiManager = ((WifiManager) context.getSystemService(
                Context.WIFI_SERVICE));
        if (wifiManager != null) {
            return wifiManager.getWifiState();
        }
        else {
            throw new Exception("wifi device not found!");
        }
    }


    /**
     * 判断Wifi是否打开，需要ACCESS_WIFI_STATE权限
     *
     * @param context 上下文
     * @return true：打开；false：关闭
     */
    public static boolean isWifiOpen(Context context) throws Exception {
        int wifiState = getWifiState(context);
        return wifiState == WifiManager.WIFI_STATE_ENABLED ||
                wifiState == WifiManager.WIFI_STATE_ENABLING
                ? true
                : false;
    }


    /**
     * 设置Wifi，需要CHANGE_WIFI_STATE权限
     *
     * @param context 上下文
     * @param enable wifi状态
     * @return 设置是否成功
     */
    public static boolean setWifi(Context context, boolean enable)
            throws Exception {
        //如果当前wifi的状态和要设置的状态不一样
        if (isWifiOpen(context) != enable) {
            ((WifiManager) context.getSystemService(
                    Context.WIFI_SERVICE)).setWifiEnabled(enable);
        }
        return true;
    }


    /**
     * 判断移动网络是否打开，需要ACCESS_NETWORK_STATE权限
     *
     * @param context 上下文
     * @return true：打开；false：关闭
     */
    public static boolean isMobileNetworkOpen(Context context) {
        return (((ConnectivityManager) context.getSystemService(
                Context.CONNECTIVITY_SERVICE)).getNetworkInfo(
                ConnectivityManager.TYPE_MOBILE)).isConnected();
    }


    /**
     * 获取本机IP地址
     *
     * @return null：没有网络连接
     */
    public static String getIpAddress() {
        try {
            NetworkInterface nerworkInterface;
            InetAddress inetAddress;
            for (Enumeration<NetworkInterface> en
                 = NetworkInterface.getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                nerworkInterface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr
                     = nerworkInterface.getInetAddresses();
                     enumIpAddr.hasMoreElements(); ) {
                    inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
            return null;
        } catch (SocketException ex) {
            ex.printStackTrace();
            return null;
        }
    }
} public class IPGWOperation {

    private static String msg1 = "";
    private static String msg2 = "";
    private static String msg3 = "";
    private static String msg4 = "";
    private static String msg5 = "";
    private static String msg6 = "";
    private static String msg7 = "";
    private static String msg8 = "";
    private static String msg9 = "";
    private static String msg11 = "";
    private static String msg12 = "";
    private static String msg13 = "";
    private static String msg14 = "";

    /**
     * 连接状态信息数组
     */
    private static String[] information = new String[3];
    /**
     * 操作类型，1:连接网络
     */
    public static final int CONNECT = 0x00000001;
    /**
     * 操作类型，3:模拟主机端连接网络
     */
    public static final int CONNECT_PC = 0x00000003;
    /**
     * 操作类型，2:注销连接
     */
    public static final int DISCONNECT = 0x00000002;
    /**
     * 操作类型，0:断开全部连接
     */
    public static final int DISCONNECT_ALL = 0x00000000;

    /**
     * 将服务器返回的数据进行正则匹配
     *
     * @param uid      用户名
     * @param password 密码
     * @return 状态码：		<br />
     * 1：Authentication failed		<br />
     * 2：无法登录				<br />
     * 3：You are already online	<br />
     * 4：密码错误				<br />
     * 5：网络已断开 			<br />
     * 6：网络已连接			<br />
     * 7：注销成功				<br />
     * 8：无法连接到IPGW网关		<br />
     * 9：内部服务器错误			<br />
     * 10：未知的主机异常			<br />
     * 11：phone连接成功			<br />
     * 12：您似乎未曾连接到网络	<br />
     * 13：用户不存在			<br />
     * 14：已欠费	            <br />
     * -1：操作不合法！			<br />
     * -2：操作失败！			<br />
     */
    public static int getConnectState(String uid, String password) {
        String html;
        try {
            html = Connect.connect(uid, password);
        } catch (UnknownHostException e) {
            System.out.println("未知的主机异常");
            return 10;
        }
        if ("".equals(html)) {
            System.out.println("操作失败！");
            return -2;
        }
//        System.out.println(html);
        return getOperatingState(html);
    }

    /**
     * 取消所有请求
     */
    public static void cancel() {
        Connect.cancel();
        ConnectPC.cancel();
        Disconnect.cancel();
        DisconnectAll.cancel();
    }

    /**
     * 模拟主机端连接网络
     *
     * @param uid      用户名
     * @param password 密码
     * @return 状态码
     */
    public static int getConnectPCState(String uid, String password) {
        String html;
        try {
            html = ConnectPC.connectPC(uid, password);
        } catch (UnknownHostException e) {
            System.out.println("未知的主机异常");
            return 10;
        }
        if ("".equals(html)) {
            System.out.println("操作失败！");
            return -2;
        }
        System.out.println(html);
        return getOperatingState(html);
    }

    /**
     * @param uid      用户名
     * @param password 密码
     * @return
     */
    public static int getDisconnectAllState(String uid, String password) {
        String html;
        try {
            html = DisconnectAll.disconnectAll(uid, password);
        } catch (UnknownHostException e) {
            System.out.println("未知的主机异常");
            return 10;
        }
        if ("".equals(html)) {
            System.out.println("操作失败！");
            return -2;
        }
        return getOperatingState(html);
    }

    /**
     * 得到注销连接状态码
     *
     * @param ip 连接到的IP地址
     * @return
     */
    public static int getDisconnectState(String ip) {
        String html;
        try {
            html = Disconnect.disconnect(ip);
        } catch (UnknownHostException e) {
            System.out.println("未知的主机异常");
            return 10;
        }
        if ("".equals(html)) {
            System.out.println("操作失败！");
            return -2;
        }
        return getOperatingState(html);
    }

    /**
     * 得到操作状态码
     *
     * @param html 服务器返回的网页源代码
     * @return 操作状态码
     */
    private static int getOperatingState(String html) {
//        System.out.println("网页代码：" + html);
        // 加工后的结果
        String info = "";
        // 连接状态
        int state = 0;
        String regex1 = "Authentication failed";
        String regex2 = "无法登录";
        String regex3 = "You are already online";
        String regex4 = "密码错误";
        String regex5 = "网络已断开";
        String regex6 = "网络已连接";
        String regex7 = "注销成功";
        String regex8 = "找不到网页";
        String regex9 = "Internal Server Error";
        String regex11 = "weui_btn_warn\" value=\"注销\"";
        String regex12 = "您似乎未曾连接到网络";
        String regex13 = "用户不存在";
        String regex14 = "已欠费";

        //将规则封装成对象
        Pattern p1 = Pattern.compile(regex1);
        Pattern p2 = Pattern.compile(regex2);
        Pattern p3 = Pattern.compile(regex3);
        Pattern p4 = Pattern.compile(regex4);
        Pattern p5 = Pattern.compile(regex5);
        Pattern p6 = Pattern.compile(regex6);
        Pattern p7 = Pattern.compile(regex7);
        Pattern p8 = Pattern.compile(regex8);
        Pattern p9 = Pattern.compile(regex9);
        Pattern p11 = Pattern.compile(regex11);
        Pattern p12 = Pattern.compile(regex12);
        Pattern p13 = Pattern.compile(regex13);
        Pattern p14 = Pattern.compile(regex14);

        //让正则对象和要作用的字符串相关联，获取匹配器对象
        Matcher m1 = p1.matcher(html);
        Matcher m2 = p2.matcher(html);
        Matcher m3 = p3.matcher(html);
        Matcher m4 = p4.matcher(html);
        Matcher m5 = p5.matcher(html);
        Matcher m6 = p6.matcher(html);
        Matcher m7 = p7.matcher(html);
        Matcher m8 = p8.matcher(html);
        Matcher m9 = p9.matcher(html);
        Matcher m11 = p11.matcher(html);
        Matcher m12 = p12.matcher(html);
        Matcher m13 = p13.matcher(html);
        Matcher m14 = p14.matcher(html);

        //将规则作用到字符串上，并进行符合规则的子串查找
        if (m1.find()) {
            msg1 = "验证失败";
            state = 1;
        } else if (m2.find()) {
            msg2 = "无法登录";
            state = 2;
        } else if (m3.find()) {
            msg3 = "已经在线了";
            state = 3;
        } else if (m4.find()) {
            msg4 = "密码错误";
            state = 4;
        } else if (m5.find()) {
            msg5 = "网络已断开";
            state = 5;
        } else if (m7.find()) {
            msg7 = "注销成功";
            state = 7;
        } else if (m8.find()) {
            msg8 = "无法连接到IPGW网关";
            state = 8;
        } else if (m9.find()) {
            msg9 = "内部服务器错误";
            state = 9;
        } else if (m11.find()) {
            msg11 = "连接成功";
            state = 11;
        } else if (m13.find()) {
            msg13 = "用户不存在";
            state = 13;
        } else if (m14.find()) {
            msg14 = "已欠费";
            state = 14;
        }
        if (m6.find()) {
            msg6 = "网络已连接";
            state = 6;
        }
        if (m12.find()) {
            msg12 = "您似乎未曾连接到网络";
            state = 12;
        }
        if (!msg6.equals("")) {
            msg5 = "";
        }
        info = msg1 + msg2 + msg3 + msg4 + msg5 + msg6 + msg7 + msg8 + msg9 + msg11 + msg12 + msg13 + msg14;
        if (info.equals("")) {
            state = 10;
        }
        return state;
    }

    /**
     * 得到连接状态信息
     *
     * @param operation 操作类型（连接或者断开）
     * @return 状态信息的字符串数组，长度为3
     */
    public static String[] getInformation(int operation) {
        if (operation == CONNECT || operation == CONNECT_PC) {
            information[0] = "";
            information[1] = "网络已连接";
            information[2] = "";
        } else if (operation == DISCONNECT) {
            information[0] = "";
            information[1] = "注销成功";
            information[2] = "";
        } else if (operation == DISCONNECT_ALL) {
            information[0] = "";
            information[1] = "网络已断开";
            information[2] = "";
        } else {
            return null;
        }
        return information;
    }
}

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.liying.ipgw.R;
import com.liying.ipgw.application.AccountApp;
import com.liying.ipgw.callback.OnCheckUpdateCallback;
import com.liying.ipgw.callback.PushCallback;
import com.liying.ipgw.dialog.NewVersionDialog;
import com.liying.ipgw.fragment.ExtFragment;
import com.liying.ipgw.fragment.GWFragment;
import com.liying.ipgw.model.RecentPost;
import com.liying.ipgw.model.UpdateMsg;
import com.liying.ipgw.task.CheckUpdateTask;
import com.liying.ipgw.task.ReceivePushTask;
import com.liying.ipgw.utils.Constants;
import com.liying.ipgw.utils.DensityUtil;
import com.liying.ipgw.utils.NetWorkUtils;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import org.sufficientlysecure.htmltextview.HtmlTextView;
import cc.duduhuo.applicationtoast.AppToast;
import lxy.liying.ipgw.post.IPGWOperation;

package com.liying.ipgw.activity;





public class MainActivity extends BaseActivity implements PushCallback {
    private IndicatorViewPager indicatorViewPager;
    private LayoutInflater inflate;
    private ImageButton ibInfo;
    private ViewPager viewPager;
    private Indicator indicator;
    private String[] tabName = {"网关", "扩展"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AccountApp.activityList.add(this);
        initView();
        setListener();
    }

    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.fragment_tabmain_viewPager);
        indicator = (Indicator) findViewById(R.id.fragment_tabmain_indicator);
        ibInfo = (ImageButton) findViewById(R.id.ibInfo);
        if (!AccountApp.isWifiChecked) {
            // 检查设备是否连接到WiFi
            try {
                if (!NetWorkUtils.isWifiByType(this)) {
                    AppToast.showToast("设备未接入WiFi。");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            AccountApp.isWifiChecked = true;
        }
        // 检查推送
        checkPush();
    }

    private void setListener() {
        ibInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AppDeclareActivity.class);
                if (indicator.getCurrentItem() == 0) {
                    intent.putExtra("back", tabName[0]);
                } else if (indicator.getCurrentItem() == 1) {
                    intent.putExtra("back", tabName[1]);
                }
                startActivity(intent);
            }
        });

        TypedArray ta = obtainStyledAttributes(new int[]{R.attr.main_color, R.attr.sub_color});
        int selectColor = ta.getColor(0, Color.BLACK);
        int unSelectColor = ta.getColor(1, Color.GRAY);
        ta.recycle();

        indicator.setScrollBar(new ColorBar(getApplicationContext(),
                selectColor, DensityUtil.dip2px(this, 2)));
        indicator.setOnTransitionListener(new OnTransitionTextListener().setColor(selectColor, unSelectColor));
        viewPager.setOffscreenPageLimit(2);

        indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
        inflate = LayoutInflater.from(getApplicationContext());
        indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
    }

    private class MyAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {

        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public int getCount() {
            return tabName.length;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = inflate.inflate(R.layout.tab_top, container, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(tabName[position]);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {
            if (position == 0) {
                // 网关
                return new GWFragment();
            } else if (position == 1) {
                // 扩展
                return new ExtFragment();
            }
            return null;
        }
    }

    @Override
    public void writeExternalStorage() {
        AppToast.showToast("正在检查更新……");
        if (!NetWorkUtils.isConnectedByState(this)) {
            AppToast.showToast(R.string.network_unavailable);
            return;
        }
        CheckUpdateTask task = new CheckUpdateTask(new OnCheckUpdateCallback() {
            @Override
            public void onUpdate(UpdateMsg msg) {

                NewVersionDialog dialog = new NewVersionDialog(MainActivity.this, msg);
