diff --git a/src/main/.DS_Store b/src/main/.DS_Store new file mode 100644 index 0000000..04cdb0d Binary files /dev/null and b/src/main/.DS_Store differ diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml new file mode 100644 index 0000000..ffdf74e --- /dev/null +++ b/src/main/AndroidManifest.xml @@ -0,0 +1,313 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/assets/.DS_Store b/src/main/assets/.DS_Store new file mode 100644 index 0000000..715bb07 Binary files /dev/null and b/src/main/assets/.DS_Store differ diff --git a/src/main/assets/appConfig.json b/src/main/assets/appConfig.json new file mode 100644 index 0000000..939c4c7 --- /dev/null +++ b/src/main/assets/appConfig.json @@ -0,0 +1,56 @@ +{ + "appInfo": { + "cloudService": { + "api": "api.gizwits.com:80", + "site": "site.gizwits.com:80" + }, + "gizwitsInfo": { + "appId": "30fe77f49f4c4b50a3affd72aa221da1", + "appSecret": "162abf698315470da96673397cd567be" + }, + "productInfo": [{ + "productKey": "d58cf41924734241ac775eedef11dbce", + "productSecret": "4092fdf9dd6e4c4286010dffcfe4118e" + }], + "tencentInfo": { + "appId": "your_tencent_app_id" + }, + "weChatInfo": { + "appId": "your_wechat_app_id", + "appSecret": "your_wechat_app_secret" + }, + "pushInfo": { + "jpushAppKey": "your_jpush_app_key", + "bpushAppKey": "your_bpush_app_key" + } + }, + "templateSelect": { + "deviceList": { + "unbindDevice": true, + "displayMac": true + } + }, + "functionConfig": { + "bindDevice_qrcode": true, + "deviceOnboarding": { + "config_softap": true, + "config_airlink": true, + "wifiModuleType": [] + }, + "login_anonymous": true, + "login_qq": false, + "login_weChat": false, + "register_phoneUser": true, + "resetPassword_phoneUser": true, + "personalCenter_changePassword": true, + "push_baidu": false, + "push_jiguang": false + }, + "viewConfig": { + "viewColor": { + "background": "FBDA51", + "contrast": "333333" + }, + "statusBarStyle": "default" + } +} \ No newline at end of file diff --git a/src/main/assets/image/CC3200.png b/src/main/assets/image/CC3200.png new file mode 100644 index 0000000..8c80735 Binary files /dev/null and b/src/main/assets/image/CC3200.png differ diff --git a/src/main/assets/image/EMW3162.png b/src/main/assets/image/EMW3162.png new file mode 100644 index 0000000..90a5da2 Binary files /dev/null and b/src/main/assets/image/EMW3162.png differ diff --git a/src/main/assets/image/ESP-07S.png b/src/main/assets/image/ESP-07S.png new file mode 100644 index 0000000..c16003e Binary files /dev/null and b/src/main/assets/image/ESP-07S.png differ diff --git a/src/main/assets/image/ESP-12F.png b/src/main/assets/image/ESP-12F.png new file mode 100644 index 0000000..f58fe7c Binary files /dev/null and b/src/main/assets/image/ESP-12F.png differ diff --git a/src/main/assets/image/ESP-12S.png b/src/main/assets/image/ESP-12S.png new file mode 100644 index 0000000..cebc30a Binary files /dev/null and b/src/main/assets/image/ESP-12S.png differ diff --git a/src/main/assets/image/GCA4004.png b/src/main/assets/image/GCA4004.png new file mode 100644 index 0000000..c31a58a Binary files /dev/null and b/src/main/assets/image/GCA4004.png differ diff --git a/src/main/assets/image/HF-LPB100.png b/src/main/assets/image/HF-LPB100.png new file mode 100644 index 0000000..a8f14e9 Binary files /dev/null and b/src/main/assets/image/HF-LPB100.png differ diff --git a/src/main/assets/image/HF-LPB120.png b/src/main/assets/image/HF-LPB120.png new file mode 100644 index 0000000..44159e9 Binary files /dev/null and b/src/main/assets/image/HF-LPB120.png differ diff --git a/src/main/assets/image/HF-LPT120.png b/src/main/assets/image/HF-LPT120.png new file mode 100644 index 0000000..a765ae1 Binary files /dev/null and b/src/main/assets/image/HF-LPT120.png differ diff --git a/src/main/assets/image/HF-LPT220.png b/src/main/assets/image/HF-LPT220.png new file mode 100644 index 0000000..9ff7ddf Binary files /dev/null and b/src/main/assets/image/HF-LPT220.png differ diff --git a/src/main/assets/image/QCA4004.png b/src/main/assets/image/QCA4004.png new file mode 100644 index 0000000..c31a58a Binary files /dev/null and b/src/main/assets/image/QCA4004.png differ diff --git a/src/main/assets/image/RTL8711AM.png b/src/main/assets/image/RTL8711AM.png new file mode 100644 index 0000000..5fd18a9 Binary files /dev/null and b/src/main/assets/image/RTL8711AM.png differ diff --git a/src/main/assets/image/TLN13P01.png b/src/main/assets/image/TLN13P01.png new file mode 100644 index 0000000..fd20abe Binary files /dev/null and b/src/main/assets/image/TLN13P01.png differ diff --git a/src/main/assets/moduleTypeInfo.html b/src/main/assets/moduleTypeInfo.html new file mode 100644 index 0000000..42e5729 --- /dev/null +++ b/src/main/assets/moduleTypeInfo.html @@ -0,0 +1,220 @@ + + + + + 模组类型选择技巧 + + + +

模组类型选择技巧

+
+

模组常见类型

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
品牌型号图片
乐鑫(ESP-8266) + + + + + + + + + + +
ESP-07S
ESP-12S
ESP-12F
+
+ + + + + + + + + + +
+ +
+ +
+ +
+
庆科 + + + + +
EMW3162
+
+ + + + +
+ +
+
汉枫 + + + + + + + + + + + + + +
HF-LPB100
HF-LPB120
HF-LPT120
HF-LPT220
+
+ + + + + + + + + + + + + +
+ +
+ +
+ +
+ +
+
瑞昱Realtek + + + + +
RTL8711AM
+
+ + + + +
+ +
+
联盛德 + + + + +
TLN13SP01
+
+ + + + +
+ +
+
高通 + + + + +
QCA4004
+
+ + + + +
+ +
+
TI + + + + +
CC3200
+
+ + + + +
+ +
+
+ 我们将会持续更新,为您带来更多的帮助参考信息。 +
+ + \ No newline at end of file diff --git a/src/main/assets/moduleTypeInfoEnglish.html b/src/main/assets/moduleTypeInfoEnglish.html new file mode 100644 index 0000000..826017f --- /dev/null +++ b/src/main/assets/moduleTypeInfoEnglish.html @@ -0,0 +1,220 @@ + + + + + Module Type Choose Tips + + + +

Module Type Choose Tips

+
+

Module Type

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BrandTypePicture
ESP(ESP-8266) + + + + + + + + + + +
ESP-07S
ESP-12S
ESP-12F
+
+ + + + + + + + + + +
+ +
+ +
+ +
+
MXCHIP + + + + +
EMW3162
+
+ + + + +
+ +
+
HF + + + + + + + + + + + + + +
HF-LPB100
HF-LPB120
HF-LPT120
HF-LPT220
+
+ + + + + + + + + + + + + +
+ +
+ +
+ +
+ +
+
RTK(Realtek) + + + + +
RTL8711AM
+
+ + + + +
+ +
+
WM + + + + +
TLN13SP01
+
+ + + + +
+ +
+
QCA + + + + +
QCA4004
+
+ + + + +
+ +
+
TI + + + + +
CC3200
+
+ + + + +
+ +
+
+ The content will be update continually, please follow it. +
+ + \ No newline at end of file diff --git a/src/main/java/.DS_Store b/src/main/java/.DS_Store new file mode 100644 index 0000000..88674d3 Binary files /dev/null and b/src/main/java/.DS_Store differ diff --git a/src/main/java/com/.DS_Store b/src/main/java/com/.DS_Store new file mode 100644 index 0000000..0adfb8d Binary files /dev/null and b/src/main/java/com/.DS_Store differ diff --git a/src/main/java/com/gizwits/.DS_Store b/src/main/java/com/gizwits/.DS_Store new file mode 100644 index 0000000..05f86ef Binary files /dev/null and b/src/main/java/com/gizwits/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/.DS_Store b/src/main/java/com/gizwits/opensource/.DS_Store new file mode 100644 index 0000000..151aec8 Binary files /dev/null and b/src/main/java/com/gizwits/opensource/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/.DS_Store new file mode 100644 index 0000000..2cec6f4 Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosBaseActivity.java b/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosBaseActivity.java new file mode 100644 index 0000000..1ddc9ff --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosBaseActivity.java @@ -0,0 +1,1077 @@ +package com.gizwits.opensource.appkit.CommonModule; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.ActivityInfo; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.os.Handler; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.style.ForegroundColorSpan; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.Window; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.opensource.appkit.utils.ToolUtils; +import java.util.ArrayList; +import java.util.List; + +public class GosBaseActivity extends AppCompatActivity { + + /** + * 设备热点默认密码 + */ + public static String SoftAP_PSW = "123456789"; + + /** + * 设备热点默认前缀 + */ + public static String SoftAP_Start = "XPG-GAgent"; + + /** + * 存储器默认名称 + */ + public static final String SPF_Name = "set"; + + /** + * Toast time + */ + public int toastTime = 2000; + + /** + * 存储器 + */ + public SharedPreferences spf; + + /** + * 等待框 + */ + public ProgressDialog progressDialog; + + /** + * 标题栏 + */ +// public ActionBar actionBar; + + public Toolbar mToolbar; + + /** + * 实现WXEntryActivity与GosUserLoginActivity共用 + */ + public static Handler baseHandler; + + public static boolean isclean = false; + public TextView tvTitle; + + public void setBaseHandler(Handler basehandler) { + if (null != basehandler) { + baseHandler = basehandler; + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + /** + * 设置为竖屏 + */ + if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } + spf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE); + // 初始化 + setProgressDialog(); + } + + /** + * 添加ProductKeys + * + * @param productkeys + * @return + */ + public List addProductKey(String[] productkeys) { + List productkeysList = new ArrayList(); + for (String productkey : productkeys) { + productkeysList.add(productkey); + } + + return productkeysList; + } + + /** + * 设置setToolBar(工具方法*开发用*) + * + * @param Title + */ + public void setToolBar(boolean isIcon, int Title) { + mToolbar = (Toolbar) findViewById(R.id.toolbar); + mToolbar.setTitle(""); + setSupportActionBar(mToolbar); + tvTitle = (TextView) findViewById(R.id.tvTitle); + // 工具栏的背景颜色 + mToolbar.setBackgroundColor(GosDeploy.appConfig_Background()); + SpannableString ssTitle = new SpannableString(this.getString(Title)); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvTitle.setText(ssTitle); + if (isIcon) { + mToolbar.setNavigationIcon(ToolUtils.editIcon(getResources(), R.drawable.common_page_back_button)); + } else { + mToolbar.setNavigationIcon(null); + } + } + + /** + * 设置setToolBar(工具方法*开发用*) + * + * @param isLeft + * @param Title + */ + public void setToolBar(boolean isLeft, String Title) { + mToolbar = (Toolbar) findViewById(R.id.toolbar); + mToolbar.setTitle(""); + setSupportActionBar(mToolbar); + tvTitle = (TextView) findViewById(R.id.tvTitle); + // 工具栏的背景颜色 + mToolbar.setBackgroundColor(GosDeploy.appConfig_Background()); + SpannableString ssTitle = new SpannableString(Title); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvTitle.setText(ssTitle); + if (isLeft) { + mToolbar.setNavigationIcon(ToolUtils.editIcon(getResources(), R.drawable.common_page_back_button)); + } else { + mToolbar.setNavigationIcon(null); + } + } + + +// /** +// * 设置ActionBar(工具方法*开发用*) +// * +// * @param HBE +// * @param DSHE +// * @param Title +// */ +// public void setActionBar(Boolean HBE, Boolean DSHE, int Title) { +// SpannableString ssTitle = new SpannableString(this.getString(Title)); +// ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), +// Spannable.SPAN_INCLUSIVE_EXCLUSIVE); +// actionBar = getSupportActionBar();// 初始化ActionBar +// Log.e("TAG", "setActionBar=========: " + actionBar); +// if (actionBar != null) { +// actionBar.setBackgroundDrawable(new ColorDrawable(GosDeploy.appConfig_Background())); +// actionBar.setHomeButtonEnabled(HBE); +//// actionBar.setIcon(R.drawable.back_bt_); +// // 设置返回按钮的颜色 +// actionBar.setIcon(ToolUtils.editIcon(getResources(), R.drawable.back_bt_)); +// actionBar.setTitle(ssTitle); +// actionBar.setDisplayShowHomeEnabled(DSHE); +// } +// +// } +// +// +// /** +// * 设置ActionBar(工具方法*GosAirlinkChooseDeviceWorkWiFiActivity.java中使用*) +// * +// * @param HBE +// * @param DSHE 使左上角图标是否显示 +// * @param Title +// */ +// public void setActionBar(Boolean HBE, Boolean DSHE, CharSequence Title) { +// SpannableString ssTitle = new SpannableString(Title); +// ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), +// Spannable.SPAN_INCLUSIVE_EXCLUSIVE); +// actionBar = getSupportActionBar();// 初始化ActionBar +// if (actionBar != null) { +// actionBar.setBackgroundDrawable(new ColorDrawable(GosDeploy.appConfig_Background())); +// actionBar.setHomeButtonEnabled(HBE); +// // 从资源文件中获取图片 +// actionBar.setIcon(ToolUtils.editIcon(getResources(), R.drawable.back_bt_)); +// actionBar.setTitle(ssTitle); +// actionBar.setDisplayShowHomeEnabled(DSHE); +// } +// } + + /** + * 设置ProgressDialog + */ + public void setProgressDialog() { + progressDialog = new ProgressDialog(this); + String loadingText = getString(R.string.loadingtext); + progressDialog.setMessage(loadingText); + progressDialog.setCanceledOnTouchOutside(false); + } + + /** + * 设置ProgressDialog + * + * @param Message + * @param Cancelable + * @param CanceledOnTouchOutside + */ + public void setProgressDialog(String Message, boolean Cancelable, boolean CanceledOnTouchOutside) { + progressDialog = new ProgressDialog(this); + progressDialog.setMessage(Message); + progressDialog.setCancelable(Cancelable); + progressDialog.setCanceledOnTouchOutside(CanceledOnTouchOutside); + } + + /** + * 检查网络连通性(工具方法) + * + * @param context + * @return + */ + public boolean checkNetwork(Context context) { + ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo net = conn.getActiveNetworkInfo(); + if (net != null && net.isConnected()) { + return true; + } + return false; + } + + /** + * 验证手机格式.(工具方法) + */ + // public boolean isMobileNO(String mobiles) { + // /* + // * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 + // * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) + // * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 + // */ + // String telRegex = "[1][3578]\\d{9}";// + // "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 + // if (TextUtils.isEmpty(mobiles)) + // return false; + // else + // return !mobiles.matches(telRegex); + // } + public String toastError(GizWifiErrorCode errorCode) { + String errorString = (String) getText(R.string.UNKNOWN_ERROR); + switch (errorCode) { + case GIZ_SDK_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_SUCCESS); + break; + case GIZ_SDK_PARAM_FORM_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PARAM_FORM_INVALID); + break; + case GIZ_SDK_CLIENT_NOT_AUTHEN: + errorString = (String) getText(R.string.GIZ_SDK_CLIENT_NOT_AUTHEN); + break; + case GIZ_SDK_CLIENT_VERSION_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_CLIENT_VERSION_INVALID); + break; + case GIZ_SDK_UDP_PORT_BIND_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_UDP_PORT_BIND_FAILED); + break; + case GIZ_SDK_DAEMON_EXCEPTION: + errorString = (String) getText(R.string.GIZ_SDK_DAEMON_EXCEPTION); + break; + case GIZ_SDK_PARAM_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PARAM_INVALID); + break; + case GIZ_SDK_APPID_LENGTH_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_APPID_LENGTH_ERROR); + break; + case GIZ_SDK_LOG_PATH_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_LOG_PATH_INVALID); + break; + case GIZ_SDK_LOG_LEVEL_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_LOG_LEVEL_INVALID); + break; + case GIZ_SDK_UID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_UID_INVALID); + break; + case GIZ_SDK_TOKEN_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_TOKEN_INVALID); + break; + case GIZ_SDK_USER_NOT_LOGIN: + errorString = (String) getText(R.string.GIZ_SDK_USER_NOT_LOGIN); + break; + case GIZ_SDK_APPID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_APPID_INVALID); + break; + case GIZ_SDK_APP_SECRET_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_APP_SECRET_INVALID); + break; + case GIZ_SDK_PRODUCT_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCT_KEY_INVALID); + break; + case GIZ_SDK_PRODUCT_SECRET_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCT_SECRET_INVALID); + break; + case GIZ_SDK_DEVICE_NOT_IN_LAN: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_IN_LAN); + break; + case GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIAL_LIST: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIAL_LIST); + break; + case GIZ_SDK_PRODUCTKEY_NOT_RELATED_WITH_APPID: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCTKEY_NOT_RELATED_WITH_APPID); + break; + case GIZ_SDK_NO_AVAILABLE_DEVICE: + errorString = (String) getText(R.string.GIZ_SDK_NO_AVAILABLE_DEVICE); + break; + case GIZ_SDK_DEVICE_CONFIG_SEND_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SEND_FAILED); + break; + case GIZ_SDK_DEVICE_CONFIG_IS_RUNNING: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING); + break; + case GIZ_SDK_DEVICE_CONFIG_TIMEOUT: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_TIMEOUT); + break; + case GIZ_SDK_DEVICE_DID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_DID_INVALID); + break; + case GIZ_SDK_DEVICE_MAC_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_MAC_INVALID); + break; + case GIZ_SDK_SUBDEVICE_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_SUBDEVICE_INVALID); + break; + case GIZ_SDK_DEVICE_PASSCODE_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_PASSCODE_INVALID); + break; + case GIZ_SDK_DEVICE_NOT_CENTERCONTROL: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_CENTERCONTROL); + break; + case GIZ_SDK_DEVICE_NOT_SUBSCRIBED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_SUBSCRIBED); + break; + case GIZ_SDK_DEVICE_NO_RESPONSE: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NO_RESPONSE); + break; + case GIZ_SDK_DEVICE_NOT_READY: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_READY); + break; + case GIZ_SDK_DEVICE_NOT_BINDED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_BINDED); + break; + case GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND); + break; +// case GIZ_SDK_DEVICE_CONTROL_FAILED: +// errorString= (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_FAILED); +// break; + case GIZ_SDK_DEVICE_GET_STATUS_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_GET_STATUS_FAILED); + break; + case GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR); + break; + case GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE); + break; + case GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND); + break; + case GIZ_SDK_BIND_DEVICE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_BIND_DEVICE_FAILED); + break; + case GIZ_SDK_UNBIND_DEVICE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_UNBIND_DEVICE_FAILED); + break; + case GIZ_SDK_DNS_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DNS_FAILED); + break; + case GIZ_SDK_M2M_CONNECTION_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_M2M_CONNECTION_SUCCESS); + break; + case GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED); + break; + case GIZ_SDK_CONNECTION_TIMEOUT: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_TIMEOUT); + break; + case GIZ_SDK_CONNECTION_REFUSED: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_REFUSED); + break; + case GIZ_SDK_CONNECTION_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_ERROR); + break; + case GIZ_SDK_CONNECTION_CLOSED: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_CLOSED); + break; + case GIZ_SDK_SSL_HANDSHAKE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SSL_HANDSHAKE_FAILED); + break; + case GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED); + break; + case GIZ_SDK_INTERNET_NOT_REACHABLE: + errorString = (String) getText(R.string.GIZ_SDK_INTERNET_NOT_REACHABLE); + break; + case GIZ_SDK_M2M_CONNECTION_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_M2M_CONNECTION_FAILED); + break; + case GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API); + break; + case GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR); + break; + case GIZ_SDK_HTTP_ANSWER_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_PARAM_ERROR); + break; + case GIZ_SDK_HTTP_SERVER_NO_ANSWER: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NO_ANSWER); + break; + case GIZ_SDK_HTTP_REQUEST_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_REQUEST_FAILED); + break; + case GIZ_SDK_OTHERWISE: + errorString = (String) getText(R.string.GIZ_SDK_OTHERWISE); + break; + case GIZ_SDK_MEMORY_MALLOC_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_MEMORY_MALLOC_FAILED); + break; + case GIZ_SDK_THREAD_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_THREAD_CREATE_FAILED); + break; + case GIZ_SDK_JSON_OBJECT_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_JSON_OBJECT_CREATE_FAILED); + break; + case GIZ_SDK_JSON_PARSE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_JSON_PARSE_FAILED); + break; + case GIZ_SDK_SCHEDULER_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_CREATE_FAILED); + break; + case GIZ_SDK_SCHEDULER_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_DELETE_FAILED); + break; + case GIZ_SDK_SCHEDULER_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_EDIT_FAILED); + break; + case GIZ_SDK_SCHEDULER_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCHEDULER_TASK_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_TASK_EDIT_FAILED); + break; + case GIZ_SDK_SCHEDULER_TASK_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_TASK_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCHEDULER_ID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_ID_INVALID); + break; + case GIZ_SDK_SCHEDULER_ENABLE_DISABLE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_ENABLE_DISABLE_FAILED); + break; + case GIZ_SDK_SCHEDULER_STATUS_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_STATUS_UPDATE_FAILED); + break; + case GIZ_SDK_GROUP_ID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_ID_INVALID); + break; + case GIZ_SDK_GROUP_FAILED_DELETE_DEVICE: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_DELETE_DEVICE); + break; + case GIZ_SDK_GROUP_FAILED_ADD_DEVICE: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_ADD_DEVICE); + break; + case GIZ_SDK_GROUP_PRODUCTKEY_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_PRODUCTKEY_INVALID); + break; + case GIZ_SDK_GROUP_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_CREATE_FAILED); + break; + case GIZ_SDK_GROUP_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_DELETE_DEVICE); + break; + case GIZ_SDK_GROUP_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_EDIT_FAILED); + break; + case GIZ_SDK_GROUP_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_GET_DEVICE_FAILED); + break; + case GIZ_SDK_SCENE_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_CREATE_FAILED); + break; + case GIZ_SDK_SCENE_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_DELETE_FAILED); + break; + case GIZ_SDK_SCENE_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_EDIT_FAILED); + break; + case GIZ_SDK_SCENE_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCENE_ITEM_LIST_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_ITEM_LIST_EDIT_FAILED); + break; + case GIZ_SDK_SCENE_ITEM_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_ITEM_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCENE_ID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_ID_INVALID); + break; + case GIZ_SDK_SCENE_RUN_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_RUN_FAILED); + break; + case GIZ_SDK_SCENE_STATUS_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_STATUS_UPDATE_FAILED); + break; + case GIZ_SDK_JOINT_ACTION_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_JOINT_ACTION_CREATE_FAILED); + break; + case GIZ_SDK_JOINT_ACTION_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_JOINT_ACTION_DELETE_FAILED); + break; + case GIZ_SDK_JOINT_ACTION_VER_UNSUPPORTED: + errorString = (String) getText(R.string.GIZ_SDK_JOINT_ACTION_VER_UNSUPPORTED); + break; +// case GIZ_SDK_JOINT_ACTION_INVALID_CONDITION_TYPE: +// errorString = (String) getText(R.string.GIZ_SDK_JOINT_ACTION_INVALID_CONDITION_TYPE); +// break; +// case GIZ_SDK_JOINT_ACTION_INVALID_RESULT_EVENT_TYPE: +// errorString = (String) getText(R.string.GIZ_SDK_JOINT_ACTION_INVALID_RESULT_EVENT_TYPE); +// break; + case GIZ_SDK_DATAPOINT_NOT_DOWNLOAD: + errorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_NOT_DOWNLOAD); + break; + case GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE: + errorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE); + break; + case GIZ_SDK_DATAPOINT_PARSE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_PARSE_FAILED); + break; + // case GIZ_SDK_NOT_INITIALIZED: + // errorString= (String) getText(R.string.GIZ_SDK_SDK_NOT_INITIALIZED); + // break; + case GIZ_SDK_APK_CONTEXT_IS_NULL: + errorString = (String) getText(R.string.GIZ_SDK_APK_CONTEXT_IS_NULL); + break; + case GIZ_SDK_APK_PERMISSION_NOT_SET: + errorString = (String) getText(R.string.GIZ_SDK_APK_PERMISSION_NOT_SET); + break; + case GIZ_SDK_CHMOD_DAEMON_REFUSED: + errorString = (String) getText(R.string.GIZ_SDK_CHMOD_DAEMON_REFUSED); + break; + case GIZ_SDK_EXEC_DAEMON_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_EXEC_DAEMON_FAILED); + break; + case GIZ_SDK_EXEC_CATCH_EXCEPTION: + errorString = (String) getText(R.string.GIZ_SDK_EXEC_CATCH_EXCEPTION); + break; + case GIZ_SDK_APPID_IS_EMPTY: + errorString = (String) getText(R.string.GIZ_SDK_APPID_IS_EMPTY); + break; + case GIZ_SDK_UNSUPPORTED_API: + errorString = (String) getText(R.string.GIZ_SDK_UNSUPPORTED_API); + break; + case GIZ_SDK_REQUEST_TIMEOUT: + errorString = (String) getText(R.string.GIZ_SDK_REQUEST_TIMEOUT); + break; + case GIZ_SDK_DAEMON_VERSION_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DAEMON_VERSION_INVALID); + break; + case GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID: + errorString = (String) getText(R.string.GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID); + break; + case GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED); + break; + case GIZ_SDK_NOT_IN_SOFTAPMODE: + errorString = (String) getText(R.string.GIZ_SDK_NOT_IN_SOFTAPMODE); + break; +// case GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE: +// errorString= (String)getText(R.string.GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE); +// break; + case GIZ_SDK_RAW_DATA_TRANSMIT: + errorString = (String) getText(R.string.GIZ_SDK_RAW_DATA_TRANSMIT); + break; + case GIZ_SDK_PRODUCT_IS_DOWNLOADING: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCT_IS_DOWNLOADING); + break; + case GIZ_SDK_START_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_START_SUCCESS); + break; + case GIZ_SDK_NEED_UPDATE_TO_LATEST: + errorString = (String) getText(R.string.GIZ_SDK_NEED_UPDATE_TO_LATEST); + break; + case GIZ_SDK_ONBOARDING_STOPPED: + errorString = (String) getText(R.string.GIZ_SDK_ONBOARDING_STOPPED); + break; + case GIZ_SDK_ONBOARDING_WIFI_IS_5G: + errorString = (String) getText(R.string.GIZ_SDK_ONBOARDING_WIFI_IS_5G); + break; + case GIZ_SDK_OTA_FIRMWARE_IS_LATEST: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_IS_LATEST); + break; + case GIZ_SDK_OTA_FIRMWARE_CHECK_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_CHECK_UPDATE_FAILED); + break; + case GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_OK: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_OK); + break; + case GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_FAILED); + break; + case GIZ_SDK_OTA_DEVICE_BUSY_IN_UPGRADE: + errorString = (String) getText(R.string.GIZ_SDK_OTA_DEVICE_BUSY_IN_UPGRADE); + break; + case GIZ_SDK_OTA_PUSH_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_PUSH_FAILED); + break; + case GIZ_SDK_OTA_FIRMWARE_VERSION_TOO_LOW: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_VERSION_TOO_LOW); + break; + case GIZ_SDK_OTA_FIRMWARE_CHECK_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_CHECK_FAILED); + break; + case GIZ_SDK_OTA_UPGRADE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_UPGRADE_FAILED); + break; + case GIZ_SDK_OTA_FIRMWARE_VERIFY_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_VERIFY_SUCCESS); + break; + case GIZ_SDK_OTA_DEVICE_NOT_SUPPORT: + errorString = (String) getText(R.string.GIZ_SDK_OTA_DEVICE_NOT_SUPPORT); + break; + case GIZ_SDK_WS_HANDSHAKE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_WS_HANDSHAKE_FAILED); + break; + case GIZ_SDK_WS_LOGIN_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_WS_LOGIN_FAILED); + break; +// case GIZ_SDK_WS_DEVICE_SUBSCRIBE_FAILED: +// errorString = (String) getText(R.string.GIZ_SDK_WS_DEVICE_SUBSCRIBE_FAILED); +// break; +// case GIZ_SDK_WS_DEVICE_UNSUBSCRIBE_FAILED: +// errorString = (String) getText(R.string.GIZ_SDK_WS_DEVICE_UNSUBSCRIBE_FAILED); +// break; + case GIZ_SITE_PRODUCTKEY_INVALID: + errorString = (String) getText(R.string.GIZ_SITE_PRODUCTKEY_INVALID); + break; + case GIZ_SITE_DATAPOINTS_NOT_DEFINED: + errorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_DEFINED); + break; + case GIZ_SITE_DATAPOINTS_NOT_MALFORME: + errorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_MALFORME); + break; + case GIZ_OPENAPI_MAC_ALREADY_REGISTERED: + errorString = (String) getText(R.string.GIZ_OPENAPI_MAC_ALREADY_REGISTERED); + break; + case GIZ_OPENAPI_PRODUCT_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_KEY_INVALID); + break; + case GIZ_OPENAPI_APPID_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_APPID_INVALID); + break; + case GIZ_OPENAPI_TOKEN_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_INVALID); + break; + case GIZ_OPENAPI_USER_NOT_EXIST: + errorString = (String) getText(R.string.GIZ_OPENAPI_USER_NOT_EXIST); + break; + case GIZ_OPENAPI_TOKEN_EXPIRED: + errorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_EXPIRED); + break; + case GIZ_OPENAPI_M2M_ID_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_M2M_ID_INVALID); + break; + case GIZ_OPENAPI_SERVER_ERROR: + errorString = (String) getText(R.string.GIZ_OPENAPI_SERVER_ERROR); + break; + case GIZ_OPENAPI_CODE_EXPIRED: + errorString = (String) getText(R.string.GIZ_OPENAPI_CODE_EXPIRED); + break; + case GIZ_OPENAPI_CODE_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_CODE_INVALID); + break; + case GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED); + break; + case GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED); + break; + case GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE); + break; + case GIZ_OPENAPI_DEVICE_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_FOUND); + break; + case GIZ_OPENAPI_FORM_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_FORM_INVALID); + break; + case GIZ_OPENAPI_DID_PASSCODE_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_DID_PASSCODE_INVALID); + break; + case GIZ_OPENAPI_DEVICE_NOT_BOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_BOUND); + break; + case GIZ_OPENAPI_PHONE_UNAVALIABLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_PHONE_UNAVALIABLE); + break; + case GIZ_OPENAPI_USERNAME_UNAVALIABLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_UNAVALIABLE); + break; + case GIZ_OPENAPI_USERNAME_PASSWORD_ERROR: + errorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_PASSWORD_ERROR); + break; + case GIZ_OPENAPI_SEND_COMMAND_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SEND_COMMAND_FAILED); + break; + case GIZ_OPENAPI_EMAIL_UNAVALIABLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_UNAVALIABLE); + break; + case GIZ_OPENAPI_DEVICE_DISABLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_DISABLED); + break; + case GIZ_OPENAPI_FAILED_NOTIFY_M2M: + errorString = (String) getText(R.string.GIZ_OPENAPI_FAILED_NOTIFY_M2M); + break; + case GIZ_OPENAPI_ATTR_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_ATTR_INVALID); + break; + case GIZ_OPENAPI_USER_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_USER_INVALID); + break; + case GIZ_OPENAPI_FIRMWARE_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_FIRMWARE_NOT_FOUND); + break; + case GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND); + break; + case GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND); + break; + case GIZ_OPENAPI_SCHEDULER_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_SCHEDULER_NOT_FOUND); + break; + case GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID); + break; + case GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE); + break; + case GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED: + errorString = (String) getText(R.string.GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED); + break; + case GIZ_OPENAPI_BT_FIRMWARE_NOTHING_TO_UPGRADE: + errorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR); + break; + case GIZ_OPENAPI_SAVE_KAIROSDB_ERROR: + errorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR); + break; + case GIZ_OPENAPI_EVENT_NOT_DEFINED: + errorString = (String) getText(R.string.GIZ_OPENAPI_EVENT_NOT_DEFINED); + break; + case GIZ_OPENAPI_SEND_SMS_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SEND_SMS_FAILED); + break; +// case GIZ_OPENAPI_APPLICATION_AUTH_INVALID: +// errorString= (String) +// getText(R.string.GIZ_OPENAPI_APPLICATION_AUTH_INVALID); +// break; + case GIZ_OPENAPI_NOT_ALLOWED_CALL_API: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_ALLOWED_CALL_API); + break; + case GIZ_OPENAPI_BAD_QRCODE_CONTENT: + errorString = (String) getText(R.string.GIZ_OPENAPI_BAD_QRCODE_CONTENT); + break; + case GIZ_OPENAPI_REQUEST_THROTTLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_REQUEST_THROTTLED); + break; + case GIZ_OPENAPI_DEVICE_OFFLINE: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_OFFLINE); + break; + case GIZ_OPENAPI_TIMESTAMP_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_TIMESTAMP_INVALID); + break; + case GIZ_OPENAPI_SIGNATURE_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_SIGNATURE_INVALID); + break; + case GIZ_OPENAPI_DEPRECATED_API: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEPRECATED_API); + break; + case GIZ_OPENAPI_REGISTER_IS_BUSY: + errorString = (String) getText(R.string.GIZ_OPENAPI_REGISTER_IS_BUSY); + break; + case GIZ_OPENAPI_ALTER_PASSWORD_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_ALTER_PASSWORD_FAILED); + break; + case GIZ_OPENAPI_APPID_PK_NOT_RELATION: + errorString = (String) getText(R.string.GIZ_OPENAPI_APPID_PK_NOT_RELATION); + break; + case GIZ_OPENAPI_CALL_INNER_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_CALL_INNER_FAILED); + break; + case GIZ_OPENAPI_DEVICE_SHARING_NOT_ENABLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_SHARING_NOT_ENABLED); + break; + case GIZ_OPENAPI_NOT_FIRST_USER_OF_DEVICE: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FIRST_USER_OF_DEVICE); + break; + case GIZ_OPENAPI_PRODUCT_KEY_AUTHEN_FAULT: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_KEY_AUTHEN_FAULT); + break; + case GIZ_OPENAPI_BUSY_NOW: + errorString = (String) getText(R.string.GIZ_OPENAPI_BUSY_NOW); + break; + case GIZ_OPENAPI_TWITTER_CONSUMER_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_TWITTER_CONSUMER_KEY_INVALID); + break; + case GIZ_OPENAPI_NOT_ALLOW_WEEK_PASSWORD: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_ALLOW_WEEK_PASSWORD); + break; +// case GIZ_OPENAPI_CODE_NOT_EXIST: +// errorString = (String) getText(R.string.GIZ_OPENAPI_CODE_NOT_EXIST); +// break; +// case GIZ_OPENAPI_EMAIL_NOT_ACTIVE: +// errorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_NOT_ACTIVE); +// break; +// case GIZ_OPENAPI_EMAIL_NOT_ENABLE: +// errorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_NOT_ENABLE); +// break; +// case GIZ_OPENAPI_DEVICE_REGISTER_NOT_FOUND: +// errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_REGISTER_NOT_FOUND); +// break; + case GIZ_OPENAPI_CANNOT_SHARE_TO_SELF: + errorString = (String) getText(R.string.GIZ_OPENAPI_CANNOT_SHARE_TO_SELF); + break; + case GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE); + break; + case GIZ_OPENAPI_NOT_FOUND_GUEST: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_GUEST); + break; + case GIZ_OPENAPI_GUEST_ALREADY_BOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_GUEST_ALREADY_BOUND); + break; + case GIZ_OPENAPI_NOT_FOUND_SHARING_INFO: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_SHARING_INFO); + break; + case GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE); + break; + case GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT); + break; + case GIZ_OPENAPI_SHARING_IS_EXPIRED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_EXPIRED); + break; + case GIZ_OPENAPI_SHARING_IS_COMPLETED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_COMPLETED); + break; + case GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING: + errorString = (String) getText(R.string.GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING); + break; + case GIZ_OPENAPI_ONLY_OWNER_CAN_BIND: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_BIND); + break; + case GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE); + break; + case GIZ_OPENAPI_SHARING_ALREADY_CANCELLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_ALREADY_CANCELLED); + break; + case GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF: + errorString = (String) getText(R.string.GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF); + break; + case GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE); + break; + case GIZ_OPENAPI_MESSAGE_ALREADY_DELETED: + errorString = (String) getText(R.string.GIZ_OPENAPI_MESSAGE_ALREADY_DELETED); + break; + case GIZ_OPENAPI_BINDING_NOTIFY_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_BINDING_NOTIFY_FAILED); + break; + case GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS); + break; + case GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE); + break; + case GIZ_OPENAPI_GUEST_NOT_BIND: + errorString = (String) getText(R.string.GIZ_OPENAPI_GUEST_NOT_BIND); + break; + case GIZ_OPENAPI_CANNOT_TRANSFER_OWNER_TO_SELF: + errorString = (String) getText(R.string.GIZ_OPENAPI_CANNOT_TRANSFER_OWNER_TO_SELF); + break; + case GIZ_OPENAPI_TRANSFER_OWNER_TO_LIMIT_GUEST: + errorString = (String) getText(R.string.GIZ_OPENAPI_TRANSFER_OWNER_TO_LIMIT_GUEST); + break; + case GIZ_OPENAPI_RESERVED: + errorString = (String) getText(R.string.GIZ_OPENAPI_RESERVED); + break; + case GIZ_PUSHAPI_BODY_JSON_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_BODY_JSON_INVALID); + break; + case GIZ_PUSHAPI_DATA_NOT_EXIST: + errorString = (String) getText(R.string.GIZ_PUSHAPI_DATA_NOT_EXIST); + break; + case GIZ_PUSHAPI_NO_CLIENT_CONFIG: + errorString = (String) getText(R.string.GIZ_PUSHAPI_NO_CLIENT_CONFIG); + break; + case GIZ_PUSHAPI_NO_SERVER_DATA: + errorString = (String) getText(R.string.GIZ_PUSHAPI_NO_SERVER_DATA); + break; + case GIZ_PUSHAPI_GIZWITS_APPID_EXIST: + errorString = (String) getText(R.string.GIZ_PUSHAPI_GIZWITS_APPID_EXIST); + break; + case GIZ_PUSHAPI_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_PARAM_ERROR); + break; + case GIZ_PUSHAPI_AUTH_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_AUTH_KEY_INVALID); + break; + case GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR); + break; + case GIZ_PUSHAPI_TYPE_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_TYPE_PARAM_ERROR); + break; + case GIZ_PUSHAPI_ID_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_ID_PARAM_ERROR); + break; + case GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID); + break; + case GIZ_PUSHAPI_CHANNELID_ERROR_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_CHANNELID_ERROR_INVALID); + break; + case GIZ_PUSHAPI_PUSH_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_PUSH_ERROR); + break; + case GIZ_SDK_SUBDEVICE_ADD_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_ADD_SUBDEVICE_FAILED); + break; + + case GIZ_SDK_SUBDEVICE_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DELETE_SUBDEVICE_FAILED); + break; + + case GIZ_SDK_SUBDEVICE_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GET_SUBDEVICES_FAILED); + break; + default: + errorString = (String) getText(R.string.UNKNOWN_ERROR); + break; + } + return errorString; + } + + /** + * NoID 提示 + * + * @param context 当前上下文 + * @param alertTextID 提示内容 + */ + public static void noIDAlert(Context context, int alertTextID) { + final Dialog dialog = new AlertDialog.Builder(context, R.style.alert_dialog_style) + .setView(new EditText(context)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_no_id); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llSure; + TextView tvAlert; + llSure = (LinearLayout) window.findViewById(R.id.llSure); + tvAlert = (TextView) window.findViewById(R.id.tvAlert); + tvAlert.setText(alertTextID); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + } + + + public void startAlert(final Intent intent, String content) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + TextView tvContent; + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + tvContent = (TextView) window.findViewById(R.id.tv_prompt); + + tvContent.setText(content); + + llNo.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + startActivity(intent); + + } + }); + } + + /** + * 推出提示 AppId 无效 + * + * @param context 当前上下文 + */ + public void tipAlert(Context context, String content) { + final Dialog dialog = new AlertDialog.Builder(context, R.style.alert_dialog_style) + .setView(new EditText(context)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_tip); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + TextView tvContent; + LinearLayout llSure; + llSure = (LinearLayout) window.findViewById(R.id.llSure); + tvContent = (TextView) window.findViewById(R.id.tvContent); + tvContent.setText(content); + + llSure.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + dialog.dismiss(); + } + }); + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosConstant.java b/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosConstant.java new file mode 100644 index 0000000..2fee94c --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosConstant.java @@ -0,0 +1,34 @@ +package com.gizwits.opensource.appkit.CommonModule; + +import android.net.wifi.ScanResult; + +import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo; +import com.gizwits.gizwifisdk.api.GizUserInfo; + +import java.util.ArrayList; +import java.util.List; + +public class GosConstant { + + // 设备热点默认前缀 + public static final String SoftAP_Start = "XPG-GAgent"; + + public static final String SSIDPsw = "#10v3#"; + public static boolean isOpenHot = false; + /** + * 0 使用旧接口 setDeviceOnboarding + * 1 配网绑定接口 setDeviceOnboardingByBind + * 2 域名配网接口 setDeviceOnboardingDeploy false + * 3 域名配网接口 setDeviceOnboardingDeploy true + */ + public static int mNew = 0; + public static List ssidList = new ArrayList(); + public static int nowPager = -1; + public static List mybindUsers = new ArrayList(); + public static boolean isEdit = false; + + public static List mydeviceSharingInfos = new ArrayList(); + public static List newmydeviceSharingInfos = new ArrayList(); + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosDeploy.java b/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosDeploy.java new file mode 100644 index 0000000..b5e3141 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/CommonModule/GosDeploy.java @@ -0,0 +1,1910 @@ +package com.gizwits.opensource.appkit.CommonModule; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; +import android.text.TextUtils; +import android.util.Log; + +import com.gizwits.opensource.appkit.utils.AssetsUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + + +public class GosDeploy { + + public static HashMap allMap; + public static HashMap infoMap; + public static HashMap moduleMap; + public static HashMap uiMap; + public static HashMap templateMap; + public static HashMap functionMap; + public static HashMap viewMap; + public static List> deviceList; + private static final String TAG = "GosDeploy"; + + static Context context; + + // 配置文件名称 + private static final String fileName = "appConfig.json"; + + // 输出json的路径 + public static String fileOutName = null; + + public GosDeploy(Context context) { + super(); + GosDeploy.context = context; + + fileOutName = (context.getFilesDir().getAbsolutePath() + fileName); + copyJson(); + readJSON(); + } + /* + * ====================================================================== + * 以下Key值用来对应JSON文件中的个配置信息的名称,用于配置App主要参数 + * ====================================================================== + */ + /** + * The App_Info Key 应用信息 + */ + private static final String AppInfo_Key = "appInfo"; + + /** + * The TemplateSelect Key 模版选择 + */ + private static final String TemplateSelect_Key = "templateSelect"; + + /** + * The FunctionConfig Key 功能选择 + */ + private static final String FunctionConfig_Key = "functionConfig"; + + /** + * The ViewConfig Key 视图配置 + */ + private static final String ViewConfig_Key = "viewConfig"; + + /** + * The DeviceInfo Key 设备定制信息 + */ + private static final String DeviceInfo_Key = "deviceInfo"; + + /** + * The CloudService Key 云服务域名信息 + */ + private static final String CloudService_Key = "cloudService"; + + /** + * The API Key openapi域名信息,形如:myapi.mygizwits.com 或 myapi.mycompany.com:8081&8443。 + */ + private static final String API_Key = "api"; + + /** + * The Site Key site域名信息,形如:mysite.mygizwits.com或mysite.mycompany.com:8081&8443。 + */ + private static final String SITE_Key = "site"; + + /** + * The PUSH Key push域名信息,形如:mypush.mygizwits.com或mypush.mycompany.com:8081&8443 + */ + private static final String PUSH_Key = "push"; + + /** + * The Gizwits_Info Key 机智云应用标识 + */ + private static final String GizwitsInfo_Key = "gizwitsInfo"; + + /** + * The AppID Key 应用标识 + */ + private static final String AppID_Key = "appId"; + + /** + * The AppSecret Key 应用密钥 + */ + private static final String AppSecret_Key = "appSecret"; + + /** + * The ProductInfo Key 机智云产品标识 + */ + private static final String ProductInfo_Key = "productInfo"; + + /** + * The ProductKey Key 产品标识 + */ + private static final String ProductKey_Key = "productKey"; + + /** + * The ProductSecret Key 产品密钥 + */ + private static final String ProductSecret_Key = "productSecret"; + + /** + * The UmengInfo Key 友盟应用标识 + */ + private static final String UmengInfo_Key = "umengInfo"; + + /** + * The AppKey Key 友盟ID + */ + private static final String AppKey_Key = "appKey"; + + /** + * The MessageKey Key 友盟密钥 + */ + private static final String MessageKey_Key = "messageKey"; + + /** + * The TencentInfo Key QQ应用标识 + */ + private static final String TencentInfo_Key = "tencentInfo"; + + /** + * The WechatInfo Key 微信应用标识 + */ + private static final String WechatInfo_Key = "weChatInfo"; + + /** + * The FacebookInfo Key facebook应用标识 + */ + private static final String FacebookInfo_Key = "facebookInfo"; + + /** + * The TwitterInfo Key 推特应用标识 + */ + private static final String TwitterInfo_Key = "twitterInfo"; + + /** + * The PushInfo Key 推送应用标识 + */ + private static final String PushInfo_Key = "pushInfo"; + + /** + * The JpushAppKey Key 极光推送应用ID + */ + private static final String JpushAppKey_Key = "jpushAppKey"; + + /** + * The BpushAppKey Key 百度推送应用ID + */ + private static final String BpushAppKey_Key = "bpushAppKey"; + + /** + * The DeviceList Key 设备列表模版:提供两种显示方式,一种显示新设备和常用设备,一种显示在线设备和离线设备。 + */ + private static final String DeviceList_Key = "deviceList"; + + /** + * The AutoSubscribe Key 自动订阅设备 + */ + private static final String AutoSubscribe_Key = "autoSubscribe"; + + /** + * The UnbindDevice Key 解绑设备的按钮 + */ + private static final String UnbindDevice_Key = "unbindDevice"; + + /** + * The DisplayMac Key 设备Mac地址 + */ + private static final String DisplayMac_Key = "displayMac"; + + /** + * The ShortCutButton Key 快捷操作按钮的数据点标识 + */ + private static final String ShortCutButton_Key = "shortCutButton"; + + /** + * The DataPointID Key 快捷操作的数据点标识 + */ + private static final String DataPointID_Key = "dataPointID"; + + /** + * The Product_Light Key 灯模版_圆环样式 + */ + private static final String Product_Light_Key = "product_light"; + + /** + * The Color Key 配置彩光效果 + */ + private static final String Color_Key = "color"; + + /** + * The HueConvert Key RGB与Hue值的转换 + */ + private static final String HueConvert_Key = "hueConvert"; + + /** + * The RGBButton Key R、G、B按钮 + */ + private static final String RGBButton_Key = "rgbButton"; + + /** + * The ColorTemprature Key 配置色温效果 + */ + private static final String ColorTemprature_Key = "colorTemprature"; + + /** + * The CttLevelValue Key 色温档位值 + */ + private static final String CttLevelValue_Key = "cttLevelValue"; + + /** + * The DisplayName Key 档位值对应的显示名称 + */ + private static final String DisplayName_Key = "displayName"; + + /** + * The BindDevice_Qrcode Key 扫码绑定设备 + */ + private static final String BindDevice_Qrcode_Key = "bindDevice_qrcode"; + + /** + * The DeviceOnboarding Key 设备配网 + */ + private static final String DeviceOnboarding_Key = "deviceOnboarding"; + + /** + * The Config_softap Key 设备softap配网 + */ + private static final String Config_softap_Key = "config_softap"; + + /** + * The Config_Airlink_Key Key 设备airlink配网 + */ + private static final String Config_Airlink_Key = "config_airlink"; + + /** + * The WifiModuleType Key 模组类型 + */ + private static final String WifiModuleType_Key = "wifiModuleType"; + + /** + * The DeviceOnboarding Key 使用新的配网部署接口 + */ + private static final String UseOnboardingDeploy_Key = "useOnboardingDeploy"; + + /** + * The OnboardingBind Key 配网时是否自动绑定 + */ + private static final String OnboardingBind_Key = "onboardingBind"; + + /** + * The Login_Anonymou Key 匿名登录 + */ + private static final String Login_Anonymous_Key = "login_anonymous"; + + /** + * The Login_QQ Key qq登录 + */ + private static final String Login_QQ_Key = "login_qq"; + + /** + * The Login_WeChat Key 微信登录 + */ + private static final String Login_WeChat_Key = "login_weChat"; + + /** + * The Register_PhoneUser Key 手机用户注册 + */ + private static final String Register_PhoneUser_Key = "register_phoneUser"; + + + /** + * The ResetPassword_PhoneUser Key 手机用户找回密码 + */ + private static final String ResetPassword_PhoneUser_Key = "resetPassword_phoneUser"; + + /** + * The PersonalCenter_ChangePassword Key + */ + private static final String PersonalCenter_ChangePassword_Key = "personalCenter_changePassword"; + + /** + * The Push_BaiDu Key + */ + private static final String Push_BaiDu_Key = "push_baidu"; + + /** + * The Push_JiGuang_Key Key + */ + private static final String Push_JiGuang_Key = "push_jiguang"; + + /** + * The DisableLan Key + */ + private static final String DisableLan_Key = "disableLan"; + + /** + * The UmengSupport Key + */ + private static final String UmengSupport_Key = "umengSupport"; + + /** + * The UsingTabSet_Switch Key + */ + private static final String UsingTabSet = "usingTabSet"; + + /** + * The Device_OnBoarding Key + */ + private static final String Device_OnBoarding_Key = "deviceOnboarding"; + + + /** + * The ViewColor Key + */ + private static final String ViewColor_Key = "viewColor"; + + /** + * The Background Key + */ + private static final String Background_Key = "background"; + + /** + * The Contrast Key + */ + private static final String Contrast_Key = "contrast"; + + /** + * The TextContent Key + */ + private static final String TextContent_Key = "textContent"; + + /** + * The AboutInfo Key + */ + private static final String AboutInfo_Key = "aboutInfo"; + + /** + * The AboutInfo Key + */ + private static final String LaunchPageInfo_Key = "launchPageInfo"; + + /** + * The CH Key + */ + private static final String CH_Key = "ch"; + + /** + * The EN Key + */ + private static final String EN_Key = "en"; + + /** + * The StatusBarStyle Key + */ + private static final String StatusBarStyle_Key = "statusBarStyle"; + + /** + * The ProductName Key + */ + private static final String ProductName_Key = "productName"; + + /** + * The DataPoint Key + */ + private static final String DataPoint_Key = "dataPoint"; + + /** + * The ID Key + */ + private static final String ID_Key = "id"; + + /** + * The Name Key + */ + private static final String Name_Key = "name"; + + /** + * The GatewaySupport Key + */ + private static final String GatewaySupport_Key = "gatewaySupport"; + + /** + * The ShowGatewayDataPoint Key + */ + private static final String ShowGatewayDataPoint_Key = "showGatewayDataPoint"; + + /** + * The UsingDevicePageTemplate Key + */ + private static final String UsingDevicePageTemplate_Key = "usingDevicePageTemplate"; + + /** + * The UsingUnbindButton Key + */ + private static final String UsingPowerOnShortcutButton_Key = "usingPowerOnShortcutButton"; + + /** + * The UsingUnbindButton Key + */ + private static final String DataPointName_Key = "dataPointName"; + + /** + * The Text Key + */ + private static final String Text_Key = "text"; + + /** + * The LaunchPage_Text Key + */ + private static final String LaunchPage_Text_Key = "launchPageText"; + + /** + * The AboutPage Key + */ + private static final String AboutPage_Key = "aboutPage"; + + + /** + * The ShowSDKVersion Key + */ + private static final String ShowSDKVersion_Key = "showSDKVersion"; + + + /** + * The ShowAppVersion Key + */ + private static final String ShowAppVersion_Key = "showAppVersion"; + + + /** + * The PowerOn Key + */ + private static final String PowerOn_Key = "powerOn"; + + /** + * The PowerOff Key + */ + private static final String PowerOff_Key = "powerOff"; + + + /** The StatusBarStyle Key */ + // private static final String StatusBarStyle_Key = "statusBarStyle"; + + /* + * =================================================================== + * 以下是解析配置文件后,对各配置信息赋值的方法。 + * =================================================================== + */ + + /** + * 设置CloudService参数--ApiUrl + * + * @return + */ + public static String appConfig_CloudServiceApi() { + String api = null; + if (infoMap != null) { + if (infoMap.containsKey(CloudService_Key)) { + try { + if (infoMap.get(CloudService_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(CloudService_Key).toString()); + if (jo.has(API_Key)) { + api = (String) jo.get(API_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return api; + } + + /** + * 设置CloudService参数--SiteUrl + * + * @return + */ + public static String appConfig_CloudServiceSite() { + String site = null; + if (infoMap != null) { + try { + if (infoMap.get(CloudService_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(CloudService_Key).toString()); + if (jo.has(SITE_Key)) { + site = (String) jo.get(SITE_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return site; + } + + /** + * 设置CloudService参数--PushUrl + * + * @return + */ + public static String appConfig_CloudServicePush() { + String push = null; + if (infoMap != null) { + try { + if (infoMap.get(CloudService_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(CloudService_Key).toString()); + if (jo.has(PUSH_Key)) { + push = (String) jo.get(PUSH_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return push; + } + + /** + * 设置SDK参数--AppID(必填) + * + * @return + */ + public static String appConfig_GizwitsInfoAppID() { + String id = null; + if (infoMap != null) { + if (infoMap.containsKey(GizwitsInfo_Key)) { + try { + if (infoMap.get(GizwitsInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(GizwitsInfo_Key).toString()); + if (jo.has(AppID_Key)) { + id = (String) jo.get(AppID_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return id; + } + + /** + * 设置SDK参数--AppSecret(必填且必须与上述AppKey匹配) + * + * @return + */ + public static String appConfig_GizwitsInfoAppSecret() { + String secret = null; + if (infoMap != null) { + if (infoMap.containsKey(GizwitsInfo_Key)) { + try { + if (infoMap.get(GizwitsInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(GizwitsInfo_Key).toString()); + if (jo.has(AppSecret_Key)) { + secret = (String) jo.get(AppSecret_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return secret; + } + + /** + * 设置ProductInfo + * + * @return + */ + public static List> appConfig_ProductList() { + List> list = new ArrayList>(); + if (infoMap != null) { + if (infoMap.containsKey(ProductInfo_Key)) { + JSONArray array = (JSONArray) infoMap.get(ProductInfo_Key); + if (array != null) { + for (int i = 0; i < array.length(); i++) { + HashMap product = new HashMap(); + JSONObject jo = null; + try { + jo = new JSONObject(array.get(i).toString()); + String productkey = null, productsecret = null; + if (jo.has(ProductKey_Key)) { + productkey = (String) jo.get(ProductKey_Key); + } + if (jo.has(ProductSecret_Key)) { + productsecret = (String) jo.get(ProductSecret_Key); + } + product.put(productkey, productsecret); + list.add(product); + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + } + return list; + } + + /** + * 设置ProductKeyInfo + * + * @return + */ + public static List> appConfig_ProductInfoList() { + List> productInfoList = new ArrayList>(); + if (infoMap != null) { + if (infoMap.containsKey(ProductInfo_Key)) { + JSONArray array = (JSONArray) infoMap.get(ProductInfo_Key); + if (array != null) { + for (int i = 0; i < array.length(); i++) { + JSONObject jo = null; + try { + ConcurrentHashMap map = new ConcurrentHashMap(); + jo = new JSONObject(array.get(i).toString()); + if (jo.has(ProductKey_Key)) { + String productkey = (String) jo.get(ProductKey_Key); + if (productkey != null) { + map.put("productKey", productkey); + } + } + if (jo.has(ProductSecret_Key)) { + String productsecret = (String) jo.get(ProductSecret_Key); + if (productsecret != null) { + map.put("productSecret", productsecret); + } + } + productInfoList.add(map); + } catch (JSONException e) { + e.printStackTrace(); + } + + } + } + } + } + return productInfoList; + } + + + /** + * 设置TencentID + * + * @return + */ + public static String appConfig_TencentAppID() { + String id = null; + if (infoMap != null) { + try { + if (infoMap.get(TencentInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(TencentInfo_Key).toString()); + if (jo.has(AppID_Key)) { + id = (String) jo.get(AppID_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return id; + } + + /** + * 设置WechatAppID + * + * @return + */ + public static String appConfig_WechatAppID() { + String id = null; + if (infoMap != null) { + try { + if (infoMap.get(WechatInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(WechatInfo_Key).toString()); + if (jo.has(AppID_Key)) { + id = (String) jo.get(AppID_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return id; + } + + /** + * 设置WeChatAppSecret + * + * @return + */ + public static String appConfig_WechatAppSecret() { + String id = null; + if (infoMap != null) { + try { + if (infoMap.get(WechatInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(WechatInfo_Key).toString()); + if (jo.has(AppSecret_Key)) { + id = (String) jo.get(AppSecret_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return id; + } + + /** + * 设置FacebookAppID + * + * @return + */ + public static String appConfig_FacebookAppID() { + String id = null; + if (infoMap != null) { + try { + if (infoMap.get(FacebookInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(FacebookInfo_Key).toString()); + if (jo.has(AppID_Key)) { + id = (String) jo.get(AppID_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return id; + } + + /** + * 设置TwitterAppID + * + * @return + */ + public static String appConfig_TwitterAppID() { + String id = null; + if (infoMap != null) { + try { + if (infoMap.get(TwitterInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(TwitterInfo_Key).toString()); + if (jo.has(AppID_Key)) { + id = (String) jo.get(AppID_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return id; + } + + /** + * 设置TwitterAppSecret + * + * @return + */ + public static String appConfig_TwitterAppSecret() { + String id = null; + if (infoMap != null) { + try { + if (infoMap.get(TwitterInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(TwitterInfo_Key).toString()); + if (jo.has(AppSecret_Key)) { + id = (String) jo.get(AppSecret_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return id; + } + + /** + * 设置JiGuangPushAppKey + * + * @return + */ + public static String appConfig_JpushAppKey() { + String key = null; + if (infoMap != null) { + try { + if (infoMap.get(PushInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(PushInfo_Key).toString()); + if (jo.has(JpushAppKey_Key)) { + key = (String) jo.get(JpushAppKey_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return key; + } + + /** + * 设置BaiDuPushAppKey + * + * @return + */ + public static String appConfig_BpushAppKey() { + String key = null; + if (infoMap != null) { + try { + if (infoMap.get(PushInfo_Key) != null) { + JSONObject jo = new JSONObject(infoMap.get(PushInfo_Key).toString()); + if (jo.has(BpushAppKey_Key)) { + key = (String) jo.get(BpushAppKey_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return key; + } + + /** + * 是否自动订阅设备 + * + * @return boolean + */ + public static boolean appConfig_AutoSubscribe() { + boolean isOn = false; + if (templateMap != null) { + if (templateMap.get(DeviceList_Key) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(DeviceList_Key).toString()); + if (jo.has(AutoSubscribe_Key)) { + if (jo.get(AutoSubscribe_Key) != null) { + isOn = (Boolean) jo.get(AutoSubscribe_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return isOn; + } + + /** + * 是否显示解绑设备的按钮 + * + * @return boolean + */ + public static boolean appConfig_UnbindDevice() { + boolean isOn = false; + if (templateMap != null) { + if (templateMap.get(DeviceList_Key) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(DeviceList_Key).toString()); + if (jo.has(UnbindDevice_Key)) { + if (jo.get(UnbindDevice_Key) != null) { + isOn = (Boolean) jo.get(UnbindDevice_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return isOn; + } + + /** + * 是否显示设备Mac地址 + * + * @return boolean + */ + public static boolean appConfig_DisplayMac() { + boolean isOn = false; + if (templateMap != null) { + if (templateMap.get(DeviceList_Key) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(DeviceList_Key).toString()); + if (jo.has(DisplayMac_Key)) { + if (jo.get(DisplayMac_Key) != null) { + isOn = (Boolean) jo.get(DisplayMac_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return isOn; + } + + /** + * 快捷操作按钮的数据点标识 + * + * @return List> + */ + public static List> appConfig_ShortCutButton() { + List> colorTemprature = new ArrayList>(); + if (templateMap != null) { + if (templateMap.get(deviceList) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(deviceList).toString()); + if (jo.has(ShortCutButton_Key)) { + if (jo.get(ShortCutButton_Key) != null) { + JSONArray array = (JSONArray) jo.get(ShortCutButton_Key); + for (int i = 0; i < array.length(); i++) { + Map map = new HashMap(); + JSONObject object = (JSONObject) array.get(i); + if (object.has(ProductKey_Key)) { + if (object.get(ProductKey_Key) != null) { + String value = (String) object.get(ProductKey_Key); + map.put("productKey", value); + } + } + if (object.has(DataPointID_Key)) { + if (object.get(DataPointID_Key) != null) { + String dataPoint = (String) object.get(DataPoint_Key); + map.put("dataPointID", dataPoint); + } + } + if (!colorTemprature.contains(map)) { + colorTemprature.add(map); + } + Log.e(TAG, "appConfig_ColorTemprature------: " + map); + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return colorTemprature; + } + + /** + * 是否做RGB与Hue值的转换 + * + * @return boolean + */ + public static boolean appConfig_HueConvert() { + boolean isOn = false; + if (templateMap != null) { + if (templateMap.get(Product_Light_Key) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(Product_Light_Key).toString()); + if (jo.has(Color_Key)) { + if (jo.get(Color_Key) != null) { + JSONObject jo1 = (JSONObject) jo.get(Color_Key); + if (jo1.has(HueConvert_Key)) { + if (jo1.get(HueConvert_Key) != null) { + isOn = (Boolean) jo1.get(HueConvert_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return isOn; + } + + /** + * 是否需要R、G、B按钮 + * + * @return boolean + */ + public static boolean appConfig_RGBButton() { + boolean isOn = false; + if (templateMap != null) { + if (templateMap.get(Product_Light_Key) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(Product_Light_Key).toString()); + if (jo.has(Color_Key)) { + if (jo.get(Color_Key) != null) { + JSONObject jo1 = (JSONObject) jo.get(Color_Key); + if (jo1.has(RGBButton_Key)) { + if (jo1.get(RGBButton_Key) != null) { + isOn = (Boolean) jo1.get(RGBButton_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return isOn; + } + + /** + * 色温档位值 + * + * @return boolean + */ + public static List> appConfig_ColorTemprature() { + List> colorTemprature = new ArrayList>(); + if (templateMap != null) { + if (templateMap.get(Product_Light_Key) != null) { + try { + JSONObject jo = new JSONObject(templateMap.get(Product_Light_Key).toString()); + if (jo.has(ColorTemprature_Key)) { + if (jo.get(ColorTemprature_Key) != null) { + JSONArray array = (JSONArray) jo.get(ColorTemprature_Key); + for (int i = 0; i < array.length(); i++) { + Map map = new HashMap(); + JSONObject object = (JSONObject) array.get(i); + if (object.has(CttLevelValue_Key)) { + if (object.get(CttLevelValue_Key) != null) { + String value = object.get(CttLevelValue_Key) + ""; + map.put("cttLevelValue", value); + } + } + if (object.has(DisplayName_Key)) { + if (object.get(DisplayName_Key) != null) { + String name = (String) object.get(DisplayName_Key); + map.put("displayName", name); + } + } + colorTemprature.add(map); + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + return colorTemprature; + } + + /** + * 是否需要扫码绑定设备 + * + * @return boolean + */ + public static boolean appConfig_BindDevice_Qrcode() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(BindDevice_Qrcode_Key)) { + if (functionMap.get(BindDevice_Qrcode_Key) != null) { + isOn = (Boolean) functionMap.get(BindDevice_Qrcode_Key); + } + } + } + return isOn; + } + + /** + * 设备softap配网 + * + * @return boolean + */ + public static boolean appConfig_Config_Softap() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(DeviceOnboarding_Key)) { + if (functionMap.get(DeviceOnboarding_Key) != null) { + JSONObject ob = (JSONObject) functionMap.get(DeviceOnboarding_Key); + try { + if (ob.has(Config_softap_Key)) { + if (ob.get(Config_softap_Key) != null) { + isOn = (Boolean) ob.get(Config_softap_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + return isOn; + } + + /** + * 设备airlink配网 + * + * @return boolean + */ + public static boolean appConfig_Config_Airlink() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(DeviceOnboarding_Key)) { + if (functionMap.get(DeviceOnboarding_Key) != null) { + JSONObject ob = (JSONObject) functionMap.get(DeviceOnboarding_Key); + try { + if (ob.has(Config_Airlink_Key)) { + if (ob.get(Config_Airlink_Key) != null) { + isOn = (Boolean) ob.get(Config_Airlink_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + return isOn; + } + + /** + * 设置模组类型 + * + * @return + */ + public static List appConfig_WifiModuleType() { + List types = new ArrayList(); + if (functionMap != null) { + if (functionMap.get(Device_OnBoarding_Key) != null) { + JSONObject jo = null; + try { + jo = new JSONObject(functionMap.get(Device_OnBoarding_Key).toString()); + if (jo.has(WifiModuleType_Key)) { + if (jo.get(WifiModuleType_Key) != null) { + JSONArray array = (JSONArray) jo.get(WifiModuleType_Key); + for (int i = 0; i < array.length(); i++) { + types.add((Integer) array.get(i)); + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + Log.e(TAG, "toAirlinkReady----------: " + types); + return types; + } + + /** + * 使用新的配网部署接口 + * + * @return boolean + */ + public static boolean appConfig_UseOnboardingDeploy() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(DeviceOnboarding_Key)) { + if (functionMap.get(DeviceOnboarding_Key) != null) { + JSONObject ob = (JSONObject) functionMap.get(DeviceOnboarding_Key); + try { + if (ob.has(UseOnboardingDeploy_Key)) { + if (ob.get(UseOnboardingDeploy_Key) != null) { + isOn = (Boolean) ob.get(UseOnboardingDeploy_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + return isOn; + } + + /** + * 配网时是否自动绑定 + * + * @return boolean + */ + public static boolean appConfig_OnboardingBind() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(DeviceOnboarding_Key)) { + if (functionMap.get(DeviceOnboarding_Key) != null) { + JSONObject ob = (JSONObject) functionMap.get(DeviceOnboarding_Key); + try { + if (ob.has(OnboardingBind_Key)) { + if (ob.get(OnboardingBind_Key) != null) { + isOn = (Boolean) ob.get(OnboardingBind_Key); + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + return isOn; + } + + /** + * 用来判断是否需要打开匿名登录 + * + * @return boolean + */ + public static boolean appConfig_Login_Anonymous() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(Login_Anonymous_Key)) { + if (functionMap.get(Login_Anonymous_Key) != null) { + isOn = (Boolean) functionMap.get(Login_Anonymous_Key); + } + } + } + return isOn; + } + + + /** + * 用来判断是否需要qq登录 + * + * @return boolean + */ + public static boolean appConfig_Login_QQ() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(Login_QQ_Key)) { + if (functionMap.get(Login_QQ_Key) != null) { + isOn = (Boolean) functionMap.get(Login_QQ_Key); + } + } + } + return isOn; + } + + + /** + * 用来判断是否需要weChat登录 + * + * @return boolean + */ + public static boolean appConfig_Login_Wechat() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(Login_WeChat_Key)) { + if (functionMap.get(Login_WeChat_Key) != null) { + isOn = (Boolean) functionMap.get(Login_WeChat_Key); + } + } + } + return isOn; + } + + /** + * 是否需要手机用户注册 + * + * @return boolean + */ + public static boolean appConfig_Register_PhoneUser() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(Register_PhoneUser_Key)) { + if (functionMap.get(Register_PhoneUser_Key) != null) { + isOn = (Boolean) functionMap.get(Register_PhoneUser_Key); + } + } + } + return isOn; + } + + /** + * 是否需要手机用户找回密码 + * + * @return boolean + */ + public static boolean appConfig_ResetPassword_PhoneUser() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(ResetPassword_PhoneUser_Key)) { + if (functionMap.get(ResetPassword_PhoneUser_Key) != null) { + isOn = (Boolean) functionMap.get(ResetPassword_PhoneUser_Key); + } + } + } + return isOn; + } + + + /** + * 是否需要修改密码 + * + * @return boolean + */ + public static boolean appConfig_PersonalCenter_ChangePassword() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(PersonalCenter_ChangePassword_Key)) { + if (functionMap.get(PersonalCenter_ChangePassword_Key) != null) { + isOn = (Boolean) functionMap.get(PersonalCenter_ChangePassword_Key); + } + } + } + return isOn; + } + + /** + * 是否需要百度推送功能 + * + * @return boolean + */ + public static boolean appConfig_Push_BaiDu() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(Push_BaiDu_Key)) { + if (functionMap.get(Push_BaiDu_Key) != null) { + isOn = (Boolean) functionMap.get(Push_BaiDu_Key); + } + } + } + return isOn; + } + + /** + * 是否需要极光推送功能 + * + * @return boolean + */ + public static boolean appConfig_Push_JiGuang() { + boolean isOn = false; + if (functionMap != null) { + if (functionMap.containsKey(Push_JiGuang_Key)) { + if (functionMap.get(Push_JiGuang_Key) != null) { + isOn = (Boolean) functionMap.get(Push_JiGuang_Key); + } + } + } + return isOn; + } + + + /** + * 设置背景颜色(返回int 型) + * + * @return + */ + public static int appConfig_Background() { + int color = Color.parseColor("#FBDA51"); + if (viewMap != null) { + String ButtonTextColor_FromMap = null; + if (viewMap.get(ViewColor_Key) != null) { + JSONObject jo = null; + try { + jo = new JSONObject(viewMap.get(ViewColor_Key).toString()); + if (jo.get(Background_Key) != null) { + ButtonTextColor_FromMap = (String) jo.get(Background_Key); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + if (!TextUtils.isEmpty(ButtonTextColor_FromMap)) { + color = Color.parseColor("#" + ButtonTextColor_FromMap); + } + } + return color; + } + + /** + * 设置背景颜色(返回 Drawable 型) + * + * @return + */ + public static Drawable appConfig_BackgroundColor() { + GradientDrawable drawable = new GradientDrawable(); + drawable.setShape(GradientDrawable.RECTANGLE); + drawable.setCornerRadius(100); + if (viewMap != null) { + String ButtonColor_FromMap = null; + if (viewMap.get(ViewColor_Key) != null) { + JSONObject jo = null; + try { + jo = new JSONObject(viewMap.get(ViewColor_Key).toString()); + if (jo.get(Background_Key) != null) { + ButtonColor_FromMap = (String) jo.get(Background_Key); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + if (!TextUtils.isEmpty(ButtonColor_FromMap)) { + drawable.setColor(Color.parseColor("#" + ButtonColor_FromMap)); + } else { + drawable.setColor(Color.argb(255, 248, 220, 38)); + } + } + return drawable; + } + + /** + * 设置背景对应颜色 + * + * @return + */ + public static int appConfig_Contrast() { + int color = Color.parseColor("#333333"); + if (viewMap != null) { + String ButtonTextColor_FromMap = null; + if (viewMap.get(ViewColor_Key) != null) { + JSONObject jo = null; + try { + jo = new JSONObject(viewMap.get(ViewColor_Key).toString()); + if (jo.get(Contrast_Key) != null) { + ButtonTextColor_FromMap = (String) jo.get(Contrast_Key); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + if (!TextUtils.isEmpty(ButtonTextColor_FromMap)) { + color = Color.parseColor("#" + ButtonTextColor_FromMap); + } + } + return color; + } + + /** + * 设置关于页面文本中文文字 + * + * @return + */ + public static String appConfig_AboutInfoCH() { + String text = null; + JSONObject jo = null; + JSONObject jo1 = null; + if (viewMap != null) { + try { + if (viewMap.containsKey(TextContent_Key)) { + if (viewMap.get(TextContent_Key) != null) { + jo = new JSONObject(viewMap.get(TextContent_Key).toString()); + if (jo.get(AboutInfo_Key) != null) { + jo1 = new JSONObject(jo.get(AboutInfo_Key).toString()); + if (jo1.get(CH_Key) != null) { + text = (String) jo1.get(CH_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return text; + } + + /** + * 设置关于页面文本英文文字 + * + * @return + */ + public static String appConfig_AboutInfoEN() { + String text = null; + JSONObject jo = null; + JSONObject jo1 = null; + if (viewMap != null) { + try { + if (viewMap.containsKey(TextContent_Key)) { + if (viewMap.get(TextContent_Key) != null) { + jo = new JSONObject(viewMap.get(TextContent_Key).toString()); + if (jo.get(LaunchPageInfo_Key) != null) { + jo1 = new JSONObject(jo.get(LaunchPageInfo_Key).toString()); + if (jo1.get(EN_Key) != null) { + text = (String) jo1.get(EN_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return text; + } + + /** + * 设置启动页中文文字 + * + * @return + */ + public static String appConfig_LaunchInfoCH() { + String text = null; + JSONObject jo = null; + JSONObject jo1 = null; + if (viewMap != null) { + try { + if (viewMap.containsKey(TextContent_Key)) { + if (viewMap.get(TextContent_Key) != null) { + jo = new JSONObject(viewMap.get(TextContent_Key).toString()); + if (jo.get(LaunchPageInfo_Key) != null) { + jo1 = new JSONObject(jo.get(LaunchPageInfo_Key).toString()); + if (jo1.get(CH_Key) != null) { + text = (String) jo1.get(CH_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return text; + } + + /** + * 设置启动页英文文字 + * + * @return + */ + public static String appConfig_LaunchInfoEN() { + String text = null; + JSONObject jo = null; + JSONObject jo1 = null; + if (viewMap != null) { + try { + if (viewMap.containsKey(TextContent_Key)) { + if (viewMap.get(TextContent_Key) != null) { + jo = new JSONObject(viewMap.get(TextContent_Key).toString()); + if (jo.get(LaunchPageInfo_Key) != null) { + jo1 = new JSONObject(jo.get(LaunchPageInfo_Key).toString()); + if (jo1.get(EN_Key) != null) { + text = (String) jo1.get(EN_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return text; + } + + /** + * 状态栏样式 + * + * @return boolean + */ + public static String appConfig_StatusBarStyle() { + String style = "default"; + if (viewMap != null) { + if (viewMap.containsKey(StatusBarStyle_Key)) { + if (viewMap.get(StatusBarStyle_Key) != null) { + style = (String) functionMap.get(StatusBarStyle_Key); + } + } + } + return style; + } + + /** + * 可在此填写设备需要显示的产品名称或者操作名称 + * + * @return boolean + */ + public static List> appConfig_DeviceInfo() { + List> mapList = new ArrayList>(); + if (deviceList != null) { + for (Map device : deviceList) { + Map map = new HashMap(); + if (device.containsKey(ProductKey_Key)) { + if (device.get(ProductKey_Key) != null) { + String productKey = (String) device.get(ProductKey_Key); + map.put(ProductKey_Key, productKey); + } + } + if (device.containsKey(ProductName_Key)) { + if (device.get(ProductName_Key) != null) { + JSONObject productName = (JSONObject) device.get(ProductName_Key); + try { + if (productName.get(CH_Key) != null) { + String text = (String) productName.get(CH_Key); + map.put("productNameCH", text); + } + if (productName.get(EN_Key) != null) { + String text = (String) productName.get(EN_Key); + map.put("productNameEN", text); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + mapList.add(map); + } + } + return mapList; + } + +// /** +// * 设置UsingTab 开关 +// * +// * @return +// */ +// public static int appConfig_UsingTabSetOn() { +// int modeOnOff = View.GONE; +// boolean isOn = false; +// if (uiMap != null) { +// if (uiMap.get(UsingTabSet) == null) { +// isOn = false; +// } else { +// isOn = (Boolean) uiMap.get(UsingTabSet); +// } +// if (isOn) { +// modeOnOff = View.VISIBLE; +// } +// } +// return modeOnOff; +// } + +// /** +// * 用来判断是否需要打开设备控制界面 +// * +// * @return +// */ +// public static boolean setUsingDevicePageTemplate() { +// boolean isOn = false; +// if (uiMap != null) { +// if (uiMap.get(UsingDevicePageTemplate_Key) == null) { +// isOn = false; +// } else { +// isOn = (Boolean) uiMap.get(UsingDevicePageTemplate_Key); +// } +// } +// return isOn; +// } + + /** + * 用来判断是否要在设备(子设备)列表中显示指定品类的快捷开关机按钮 + * + * @return + */ + public static List> appConfig_UsingPowerOnShortcutButton() { + List> list = new ArrayList>(); + List list1 = new ArrayList(); + if (uiMap != null) { + JSONArray jsonArray = (JSONArray) uiMap.get(UsingPowerOnShortcutButton_Key); + if (jsonArray != null) { + for (int i = 0; i < jsonArray.length(); i++) { + HashMap product = new HashMap(); + JSONObject jo = null; + try { + jo = new JSONObject(jsonArray.get(i).toString()); + String productkey = (String) jo.get(ProductKey_Key); + String datapointname = (String) jo.get(DataPointName_Key); + product.put(productkey, datapointname); + if (!list1.contains(productkey)) { + list1.add(productkey); + list.add(product); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + } + return list; + } + + /** + * 设置ProductKey + * + * @return + */ + public static List appConfig_ProductKeyList() { + //entity.getAppInfo().getProductInfo(); + List productKeyList = new ArrayList(); + if (uiMap != null) { + JSONArray array = (JSONArray) infoMap.get(ProductInfo_Key); + if (array != null) { + for (int i = 0; i < array.length(); i++) { + JSONObject jo = null; + try { + jo = new JSONObject(array.get(i).toString()); + if (jo.has(ProductKey_Key)) { + String productkey = (String) jo.get(ProductKey_Key); + productKeyList.add(productkey); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + } + } + return productKeyList; + } + + /** + * 是否显示SDK版本号 + * + * @return + */ + public static boolean appConfig_ShowSDKVersion() { + boolean isOn = false; + JSONObject jo = null; + JSONObject jo1 = null; + if (uiMap != null) { + try { + if (uiMap.containsKey(Text_Key)) { + if (uiMap.get(Text_Key) != null) { + jo = new JSONObject(uiMap.get(Text_Key).toString()); + if (jo.get(AboutPage_Key) != null) { + jo1 = new JSONObject(jo.get(AboutPage_Key).toString()); + if (jo1.get(ShowSDKVersion_Key) != null) { + isOn = (Boolean) jo1.get(ShowSDKVersion_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return isOn; + } + + + /** + * 是否显示APP版本号 + * + * @return + */ + public static boolean appConfig_ShowAPPVersion() { + boolean isOn = false; + JSONObject jo = null; + JSONObject jo1 = null; + if (uiMap != null) { + try { + if (uiMap.containsKey(Text_Key)) { + if (uiMap.get(Text_Key) != null) { + jo = new JSONObject(uiMap.get(Text_Key).toString()); + if (jo.get(AboutPage_Key) != null) { + jo1 = new JSONObject(jo.get(AboutPage_Key).toString()); + if (jo1.get(ShowAppVersion_Key) != null) { + isOn = (Boolean) jo1.get(ShowAppVersion_Key); + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + return isOn; + } + +// /** +// * 设置添加设备标题 +// * +// * @return +// */ +// public static String setAddDeviceTitle() { +// +// String addDeviceTitle = context.getResources().getString( +// R.string.addDeviceTitle); +// String AddDeviceTitle_FromMap = infoMap.get(AddDeviceTitle_Key) +// .toString(); +// if (!TextUtils.isEmpty(AddDeviceTitle_FromMap)) { +// addDeviceTitle = AddDeviceTitle_FromMap; +// } +// +// return addDeviceTitle; +// +// } + + /** + * 读取本地的JSON文件 + */ + public static void readJSON() { + try { + FileInputStream input = new FileInputStream(fileOutName); + InputStreamReader inputStreamReader = new InputStreamReader(input, "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String line; + StringBuilder stringBuilder = new StringBuilder(); + while ((line = bufferedReader.readLine()) != null) { + stringBuilder.append(line); + } + bufferedReader.close(); + inputStreamReader.close(); + // 加载JSON数据到Entity + //setEntity(stringBuilder); + setMap(stringBuilder); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + +// public static void setEntity(StringBuilder stringBuilder) { +// // 加载JSON数据到Map +// Gson gson = new Gson(); +// +// entity = gson.fromJson(stringBuilder.toString(), Entity.class); +// } + + + //拷贝json文件 + private void copyJson() { + try { + AssetsUtils.assetsDataToSD(fileOutName, fileName, context); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + + public static void setMap(StringBuilder stringBuilder) { + infoMap = new HashMap(); + moduleMap = new HashMap(); + uiMap = new HashMap(); + templateMap = new HashMap(); + functionMap = new HashMap(); + viewMap = new HashMap(); + deviceList = new ArrayList>(); + + try { + JSONObject root = new JSONObject(stringBuilder.toString()); + Iterator actions = root.keys(); + while (actions.hasNext()) { + String param = actions.next().toString(); + Object valus = root.get(param); + String info = valus.toString(); + if (param.matches(DeviceInfo_Key)) { + JSONArray array = new JSONArray(info); + for (int i = 0; i < array.length(); i++) { + JSONObject data = (JSONObject) array.get(i); + Iterator action = data.keys(); + HashMap map = new HashMap(); + while (action.hasNext()) { + String param1 = action.next().toString(); + Object valus1 = data.get(param1); + map.put(param1, valus1); + } + deviceList.add(map); + } + Log.e(TAG, "setMap----: " + deviceList); + } else { + JSONObject data = new JSONObject(info); + Iterator action = data.keys(); + Log.e(TAG, "param-----: " + param); + Log.e(TAG, "info------: " + info); + if (param.matches(AppInfo_Key)) { + while (action.hasNext()) { + String param1 = action.next().toString(); + Object valus1 = data.get(param1); + infoMap.put(param1, valus1); + } + } + if (param.matches(TemplateSelect_Key)) { + while (action.hasNext()) { + String param1 = action.next().toString(); + Object valus1 = data.get(param1); + templateMap.put(param1, valus1); + } + } + if (param.matches(FunctionConfig_Key)) { + while (action.hasNext()) { + String param1 = action.next().toString(); + Object valus1 = data.get(param1); + functionMap.put(param1, valus1); + } + } + if (param.matches(ViewConfig_Key)) { + while (action.hasNext()) { + String param1 = action.next().toString(); + Object valus1 = data.get(param1); + viewMap.put(param1, valus1); + } + } + } + + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/CommonModule/NoScrollViewPager.java b/src/main/java/com/gizwits/opensource/appkit/CommonModule/NoScrollViewPager.java new file mode 100644 index 0000000..a439094 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/CommonModule/NoScrollViewPager.java @@ -0,0 +1,56 @@ +package com.gizwits.opensource.appkit.CommonModule; + +import android.content.Context; +import android.support.v4.view.ViewPager; +import android.util.AttributeSet; +import android.view.MotionEvent; + +public class NoScrollViewPager extends ViewPager { + private boolean noScroll = false; + + public NoScrollViewPager(Context context, AttributeSet attrs) { + super(context, attrs); + // TODO Auto-generated constructor stub + } + + public NoScrollViewPager(Context context) { + super(context); + } + + public void setNoScroll(boolean noScroll) { + this.noScroll = noScroll; + } + + @Override + public void scrollTo(int x, int y) { + super.scrollTo(x, y); + } + + @Override + public boolean onTouchEvent(MotionEvent arg0) { + /* return false;//super.onTouchEvent(arg0); */ + if (noScroll) + return false; + else + return super.onTouchEvent(arg0); + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent arg0) { + if (noScroll) + return false; + else + return super.onInterceptTouchEvent(arg0); + } + + @Override + public void setCurrentItem(int item, boolean smoothScroll) { + super.setCurrentItem(item, smoothScroll); + } + + @Override + public void setCurrentItem(int item) { + super.setCurrentItem(item); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/CommonModule/SplashActivity.java b/src/main/java/com/gizwits/opensource/appkit/CommonModule/SplashActivity.java new file mode 100644 index 0000000..96107ab --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/CommonModule/SplashActivity.java @@ -0,0 +1,115 @@ +package com.gizwits.opensource.appkit.CommonModule; + +import android.app.Activity; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.os.Handler; +import android.support.v4.app.ActivityCompat; +import android.util.Log; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.MessageCenter; +import com.gizwits.opensource.appkit.PushModule.GosPushManager; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.UserModule.GosUserLoginActivity; +import com.gizwits.opensource.appkit.utils.AssetsUtils; + +/** + * Created by admin on 2017/6/8. + */ + +public class SplashActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback { + private final int SPLASH_DISPLAY_LENGHT = 2000; + private Handler handler; + + private static final int REQUEST_EXTERNAL_STORAGE = 1; + private static String[] PERMISSIONS_STORAGE = { + "android.permission.READ_EXTERNAL_STORAGE", + "android.permission.WRITE_EXTERNAL_STORAGE"}; + + //push-all-start + private GosPushManager gosPushManager; + //push-all-end + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (!this.isTaskRoot()) {// 判断此activity是不是任务控件的源Activity,“非”也就是说是被系统重新实例化出来的 + Intent mainIntent = getIntent(); + String action = mainIntent.getAction(); + if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) + && action.equals(Intent.ACTION_MAIN)) { + finish(); + return; + } + } +// getWindow().requestFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.activity_gos_splash); + + handler = new Handler(); + getWindow().getDecorView().post(new Runnable() { + @Override + public void run() { + //检测是否有写的权限 + int permission = ActivityCompat.checkSelfPermission(SplashActivity.this, + "android.permission.WRITE_EXTERNAL_STORAGE"); + if (permission != PackageManager.PERMISSION_GRANTED) { + try { + // 没有写的权限,去申请写的权限,会弹出对话框 + ActivityCompat.requestPermissions(SplashActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + initEvent(); + } + } + }); + + } + + private void initEvent() { + + // 延迟SPLASH_DISPLAY_LENGHT时间然后跳转到MainActivity + handler.postDelayed(new Runnable() { + @Override + public void run() { + Intent intent = new Intent(SplashActivity.this, + GosUserLoginActivity.class); + startActivity(intent); + SplashActivity.this.finish(); + } + }, SPLASH_DISPLAY_LENGHT); + + MessageCenter.getInstance(SplashActivity.this); + // 在配置文件中选择推送类型((2:百度,1:极光推送 )) + if (GosDeploy.appConfig_Push_BaiDu()) { + Log.e("TAG", "initEvent----: 百度推送"); + gosPushManager = new GosPushManager(2, this); + } + if (GosDeploy.appConfig_Push_JiGuang()) { + gosPushManager = new GosPushManager(1, this); + } + + TextView tvName = (TextView) findViewById(R.id.tvName); + if (AssetsUtils.isZh(SplashActivity.this)) { + if (GosDeploy.appConfig_LaunchInfoCH() != null) { + tvName.setText(GosDeploy.appConfig_LaunchInfoCH()); + } + } else { + if (GosDeploy.appConfig_LaunchInfoEN() != null) { + tvName.setText(GosDeploy.appConfig_LaunchInfoEN()); + } + } + + } + + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + initEvent(); + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/CommonModule/TipsDialog.java b/src/main/java/com/gizwits/opensource/appkit/CommonModule/TipsDialog.java new file mode 100644 index 0000000..30e0247 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/CommonModule/TipsDialog.java @@ -0,0 +1,59 @@ +package com.gizwits.opensource.appkit.CommonModule; + +import android.app.Dialog; +import android.content.Context; +import android.view.View; +import android.view.Window; +import android.widget.Button; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; + + +public class TipsDialog extends Dialog implements + View.OnClickListener { + + private Button btnSure; + private TextView tvTips; + + public TipsDialog(Context context) { + super(context); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().setBackgroundDrawableResource(R.drawable.shape_button2); + setContentView(R.layout.dialog_tips); + initView(); + setCancelable(false); + + } + + public TipsDialog(Context context, String txt) { + this(context); + + tvTips.setText(txt); + } + + public TipsDialog(Context context, int res) { + this(context); + + tvTips.setText(res); + } + + + + + private void initView() { + btnSure = (Button) findViewById(R.id.btnSure); + tvTips = (TextView) findViewById(R.id.tvTips); + + btnSure.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnSure: + cancel(); + break; + } + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/.DS_Store new file mode 100644 index 0000000..b28d391 Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkChooseDeviceWorkWiFiActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkChooseDeviceWorkWiFiActivity.java new file mode 100644 index 0000000..70f2c49 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkChooseDeviceWorkWiFiActivity.java @@ -0,0 +1,505 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.location.LocationManager; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiInfo; +import android.os.Bundle; +import android.support.v4.app.ActivityCompat; +import android.text.TextUtils; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +import com.gizwits.opensource.appkit.utils.NetUtils; +import com.gizwits.opensource.appkit.utils.ToolUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +@SuppressLint("InflateParams") +public class GosAirlinkChooseDeviceWorkWiFiActivity extends GosConfigModuleBaseActivity implements OnClickListener { + + private AlertDialog create; + private ArrayList wifiList; + + private static final int REQUEST_EXTERNAL_STORAGE = 1; + private static String[] PERMISSIONS_STORAGE = { + "android.permission.ACCESS_FINE_LOCATION", + "android.permission.ACCESS_COARSE_LOCATION"}; + /** + * wifi信息 + */ + public WifiInfo wifiInfo; + + /** + * The et SSID + */ + private EditText etSSID; + + /** + * The et Psw + */ + private EditText etPsw; + + /** + * The btn Next + */ + private Button btnNext; + + /** The ll ChooseMode */ + //private LinearLayout llChooseMode; + + /** + * The cb Laws + */ + private CheckBox cbLaws; + + /** The tv Mode */ + //private TextView tvMode; + + /** + * The rl WiFiList + */ + private RelativeLayout rlWiFiList; + + /** + * 配置用参数 + */ + private String workSSID, workSSIDPsw; + + /** + * The data + */ + List modeList; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_airlink_choose_device_workwifi); + // 设置ActionBar + setToolBar(true, getString(R.string.choose_wifi)); + + initData(); + initView(); + ininEvent(); + } + + @Override + protected void onResume() { + super.onResume(); + try { + // 预设workSSID && workSSIDPsw + workSSID = NetUtils.getCurentWifiSSID(this); + String mypass = spf.getString("mypass", ""); + + if (!TextUtils.isEmpty(workSSID)) { + etSSID.setText(workSSID); + etSSID.setSelection(workSSID.length()); + if (!TextUtils.isEmpty(mypass)) { + JSONObject obj = new JSONObject(mypass); + + if (obj.has(workSSID)) { + String pass = obj.getString(workSSID); + etPsw.setText(pass); + } else { + etPsw.setText(""); + } + } + } else { + etSSID.setText(NetUtils.getCurentWifiSSID(this)); + } + + // 当没有任何文字的时候设置为明文显示 +// if (TextUtils.isEmpty(etPsw.getText().toString())) { +// cbLaws.setChecked(true); +// etPsw.setInputType(0x90); +// } else { +// etPsw.setInputType(0x81); +// cbLaws.setChecked(false); +// } + } catch(JSONException e) { + e.printStackTrace(); + } + } + + private void initView() { + //tvMode = (TextView) findViewById(R.id.tvMode); + etSSID = (EditText) findViewById(R.id.etSSID); + + etPsw = (EditText) findViewById(R.id.etPsw); + cbLaws = (CheckBox) findViewById(R.id.cbLaws); + btnNext = (Button) findViewById(R.id.btnNext); + //llChooseMode = (LinearLayout) findViewById(R.id.llChooseMode); + rlWiFiList = (RelativeLayout) findViewById(R.id.rlWiFiList); + + // 配置文件部署 + btnNext.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnNext.setTextColor(GosDeploy.appConfig_Contrast()); + // llChooseMode.setVisibility(GosDeploy.setModuleSelectOn()); + + //llChooseMode.setVisibility(View.GONE); + } + + + private void ininEvent() { + btnNext.setOnClickListener(this); + rlWiFiList.setOnClickListener(this); + //llChooseMode.setOnClickListener(this); + + cbLaws.setOnCheckedChangeListener(new OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + String psw = etPsw.getText().toString(); + + if (isChecked) { + etPsw.setInputType(0x90); + } else { + etPsw.setInputType(0x81); + } + etPsw.setSelection(psw.length()); + } + }); + + //检测是否有位置定位的权限 + int permission = ActivityCompat.checkSelfPermission(GosAirlinkChooseDeviceWorkWiFiActivity.this, + "android.permission.ACCESS_FINE_LOCATION"); + if (permission != PackageManager.PERMISSION_GRANTED) { + try { + // 没有写的权限,去申请写的权限,会弹出对话框 + ActivityCompat.requestPermissions(GosAirlinkChooseDeviceWorkWiFiActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); + } catch(Exception e) { + e.printStackTrace(); + } + } + } + + private void initData() { + modeList = new ArrayList(); + String[] modes = this.getResources().getStringArray(R.array.mode); + for (String string : modes) { + modeList.add(string); + } + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnNext: + if (ToolUtils.noDoubleClick()) { + workSSID = etSSID.getText().toString(); + workSSIDPsw = etPsw.getText().toString(); + + if (TextUtils.isEmpty(workSSID)) { + Toast.makeText(GosAirlinkChooseDeviceWorkWiFiActivity.this, R.string.choose_wifi_list_title, toastTime) + .show(); + return; + } + + if (!workSSID.equals(NetUtils.getCurentWifiSSID(this))) { + final Dialog dialog1 = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog1.setCanceledOnTouchOutside(false); + dialog1.show(); + + Window window = dialog1.getWindow(); + window.setContentView(R.layout.alert_gos_wifi); + + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog1.cancel(); + return; + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + if (dialog1.isShowing()) { + dialog1.cancel(); + } + isEmptyAlert(); + } + }); + } else { + isEmptyAlert(); + } + } + break; + + case R.id.rlWiFiList: + AlertDialog.Builder dia = new AlertDialog.Builder(GosAirlinkChooseDeviceWorkWiFiActivity.this); + View view = View.inflate(GosAirlinkChooseDeviceWorkWiFiActivity.this, R.layout.alert_gos_wifi_list, null); + ListView listview = (ListView) view.findViewById(R.id.wifi_list); + List rsList = NetUtils.getCurrentWifiScanResult(this); + List localList = new ArrayList(); + localList.clear(); + wifiList = new ArrayList(); + wifiList.clear(); + for (ScanResult sss : rsList) { + if (sss.SSID.contains(SoftAP_Start)) { + } else { + if (localList.toString().contains(sss.SSID)) { + } else { + localList.add(sss.SSID); + wifiList.add(sss); + } + } + } + if (wifiList.size() == 0) { + LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + // 未打开位置开关,可能导致定位失败或定位不准,提示用户或做相应处理 + Toast.makeText(this, getString(R.string.open), Toast.LENGTH_LONG).show(); + return; + } + } + WifiListAdapter adapter = new WifiListAdapter(wifiList); + listview.setAdapter(adapter); + listview.setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { + ScanResult sResult = wifiList.get(arg2); + String sSID = sResult.SSID; + etSSID.setText(sSID); + etSSID.setSelection(sSID.length()); + etPsw.setText(""); + create.dismiss(); + } + }); + dia.setView(view); + create = dia.create(); + create.show(); + break; + + default: + break; + } + } + + private static final String TAG = "GosAirlinkChooseDevice"; + + private void toAirlinkReady() { + // 需要记录所有配置过的wifi和密码 + + try { + String mypass = spf.getString("mypass", ""); + if (TextUtils.isEmpty(mypass)) { + JSONObject mUserAndPass = new JSONObject(); + mUserAndPass.put(workSSID, workSSIDPsw); + spf.edit().putString("mypass", mUserAndPass.toString()).commit(); + } else { + JSONObject obj = new JSONObject(mypass); + obj.put(workSSID, workSSIDPsw); + spf.edit().putString("mypass", obj.toString()).commit(); + } + } catch(JSONException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + spf.edit().putString("workSSID", workSSID).commit(); + spf.edit().putString("workSSIDPsw", workSSIDPsw).commit(); + //wifiModuleType-false-start wifiModuleType-true-start + if (GosDeploy.appConfig_WifiModuleType().size() == 0) { + //wifiModuleType-false-end + Intent intent = new Intent(this, GosModeListActivity2.class); + startActivity(intent); + //wifiModuleType-false-start + } else { + //wifiModuleType-true-end + List moduleTypes = GosDeploy.appConfig_WifiModuleType(); + JSONArray array = new JSONArray(); + for (int type : moduleTypes) { + if (type == 4) { + type = 0; + } else if (type < 4) { + type = type + 1; + } else if (type == 12) { + type = 6; + } else if (type >= 6 && type < 12) { + type = type + 1; + } + array.put(type); + } + spf.edit().putString("modulestyles", array.toString()).commit(); + Intent intent = new Intent(this, GosAirlinkReadyActivity.class); + startActivity(intent); + //wifiModuleType-true-start + } + //wifiModuleType-false-end wifiModuleType-true-end + + } + + /* + * // 检查当前使用的WiFi是否曾经用过 protected boolean checkworkSSIDUsed(String workSSID) + * { if (spf.contains("workSSID")) { if (spf.getString("workSSID", + * "").equals(workSSID)) { return true; } } return false; } + */ + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + Intent intent = new Intent(this, GosMainActivity.class); + startActivity(intent); + //quitAlert(this, intent); + return true; + } + return false; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + Intent intent = new Intent(this, GosMainActivity.class); + startActivity(intent); + //quitAlert(this, intent); + break; + } + + return true; + } + + + private void isEmptyAlert() { + if (TextUtils.isEmpty(workSSIDPsw)) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_empty); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + if (dialog.isShowing()) { + dialog.cancel(); + } + toAirlinkReady(); + } + }); + } else { + toAirlinkReady(); + } + } + + class WifiListAdapter extends BaseAdapter { + + ArrayList xpgList; + + public WifiListAdapter(ArrayList list) { + this.xpgList = list; + } + + @Override + public int getCount() { + return xpgList.size(); + } + + @Override + public Object getItem(int position) { + return null; + } + + @Override + public long getItemId(int position) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + Holder holder; + if (view == null) { + view = LayoutInflater.from(GosAirlinkChooseDeviceWorkWiFiActivity.this) + .inflate(R.layout.item_gos_wifi_list, null); + holder = new Holder(view); + view.setTag(holder); + } else { + holder = (Holder) view.getTag(); + } + + String ssid = xpgList.get(position).SSID; + holder.getTextView().setText(ssid); + + return view; + } + + } + + class Holder { + View view; + + public Holder(View view) { + this.view = view; + } + + TextView textView; + + public TextView getTextView() { + if (textView == null) { + textView = (TextView) view.findViewById(R.id.SSID_text); + } + return textView; + } + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkConfigCountdownActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkConfigCountdownActivity.java new file mode 100644 index 0000000..754177b --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkConfigCountdownActivity.java @@ -0,0 +1,310 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.annotation.SuppressLint; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.style.ForegroundColorSpan; +import android.util.Log; +import android.view.KeyEvent; +import android.view.View; +import android.view.ViewGroup.LayoutParams; +import android.view.WindowManager; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiConfigureMode; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.enumration.GizWifiGAgentType; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +import com.gizwits.opensource.appkit.view.RoundProgressBar; + +import org.json.JSONArray; +import org.json.JSONException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import static com.gizwits.gizwifisdk.enumration.GizWifiErrorCode.GIZ_SDK_ONBOARDING_STOPPED; + +@SuppressLint("HandlerLeak") +public class GosAirlinkConfigCountdownActivity extends + GosConfigModuleBaseActivity { + + /** The tv Time */ + //private TextView tvTimer; + + /** + * The rpb Config + */ + private RoundProgressBar rpbConfig; + + /** + * 倒计时 + */ + int secondleft = 60; + + /** + * The timer + */ + Timer timer; + + /** + * 配置用参数 + */ + String workSSID, workSSIDPsw; + + + List modeList, modeDataList; + private TextView tvLeft; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_airlink_config_countdown); + // 设置ActionBar + setToolBar(false, R.string.search_join); + initView(); + initData(); + startAirlink(); + tvLeft = (TextView) findViewById(R.id.tvLeft); + tvLeft.setVisibility(View.VISIBLE); + SpannableString ssTitle = new SpannableString(this.getString(R.string.cancel)); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvLeft.setText(ssTitle); + tvLeft.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(GosAirlinkConfigCountdownActivity.this, GosMainActivity.class); + quitAlert(GosAirlinkConfigCountdownActivity.this, intent, getString(R.string.cancel_configuration)); + } + }); + } + + private void initView() { + WindowManager wm = this.getWindowManager(); + int width = wm.getDefaultDisplay().getWidth(); + + RelativeLayout cel_layout = (RelativeLayout) findViewById(R.id.params); + LayoutParams params = cel_layout.getLayoutParams(); + params.height = width; + params.width = width; + cel_layout.setLayoutParams(params); + //tvTimer = (TextView) findViewById(R.id.tvTimer); + + rpbConfig = (RoundProgressBar) findViewById(R.id.rpbConfig); + + } + + private static final String TAG = "GosAirlinkConfigCountdo"; + + private void initData() { + workSSID = spf.getString("workSSID", ""); + workSSIDPsw = spf.getString("workSSIDPsw", ""); + modeDataList = new ArrayList(); + modeDataList.add(GizWifiGAgentType.GizGAgentESP); + modeDataList.add(GizWifiGAgentType.GizGAgentMXCHIP); + modeDataList.add(GizWifiGAgentType.GizGAgentHF); + modeDataList.add(GizWifiGAgentType.GizGAgentRTK); + modeDataList.add(GizWifiGAgentType.GizGAgentWM); + modeDataList.add(GizWifiGAgentType.GizGAgentQCA); + modeDataList.add(GizWifiGAgentType.GizGAgentFlyLink); + modeDataList.add(GizWifiGAgentType.GizGAgentTI); + modeDataList.add(GizWifiGAgentType.GizGAgentFSK); + modeDataList.add(GizWifiGAgentType.GizGAgentMXCHIP3); + modeDataList.add(GizWifiGAgentType.GizGAgentBL); + modeDataList.add(GizWifiGAgentType.GizGAgentAtmelEE); + modeDataList.add(GizWifiGAgentType.GizGAgentOther); + modeList = new ArrayList(); + + String types = spf.getString("modulestyles", null); + if (types != null) { + try { + JSONArray array = new JSONArray(types); + for (int i = 0; i < array.length(); i++) { + int type = (Integer) array.get(i); + modeList.add(modeDataList.get(type)); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + + private void startAirlink() { + String nullStr = null; + switch (GosConstant.mNew) { + case 0: + GizWifiSDK.sharedInstance().setDeviceOnboarding(workSSID, workSSIDPsw, + GizWifiConfigureMode.GizWifiAirLink, null, 60, modeList); + break; + case 1: + GizWifiSDK.sharedInstance().setDeviceOnboardingByBind(workSSID, workSSIDPsw, + GizWifiConfigureMode.GizWifiAirLink, null, 60, modeList); + break; + case 2: + GizWifiSDK.sharedInstance().setDeviceOnboardingDeploy( + workSSID, + workSSIDPsw, + GizWifiConfigureMode.GizWifiAirLink, + nullStr, + 60, + modeList, + false + ); + break; + case 3: + GizWifiSDK.sharedInstance().setDeviceOnboardingDeploy( + workSSID, + workSSIDPsw, + GizWifiConfigureMode.GizWifiAirLink, + nullStr, + 60, + modeList, + true + ); + break; + } + handler.sendEmptyMessage(handler_key.START_TIMER.ordinal()); + } + + private enum handler_key { + + /** + * 倒计时提示 + */ + TIMER_TEXT, + + /** + * 倒计时开始 + */ + START_TIMER, + + /** + * 配置成功 + */ + SUCCESSFUL, + + /** + * 配置失败 + */ + FAILED, + + } + + /** + * The handler. + */ + Handler handler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + + case START_TIMER: + isStartTimer(); + break; + + case SUCCESSFUL: + Toast.makeText(GosAirlinkConfigCountdownActivity.this, + R.string.configuration_successful, toastTime).show(); + Intent intent1 = new Intent(GosAirlinkConfigCountdownActivity.this, GosMainActivity.class); + startActivity(intent1); + break; + + case FAILED: + if (GosDeploy.appConfig_Config_Softap()) { + Toast.makeText(GosAirlinkConfigCountdownActivity.this, + getString(R.string.configuration_timeout), toastTime).show(); + Intent intent = new Intent( + GosAirlinkConfigCountdownActivity.this, + GosDeviceReadyActivity.class); + /** 判断是否是从一键配置界面传过去的 */ + intent.putExtra("isAirLink", true); + startActivity(intent); + } else { + Intent intent = new Intent( + GosAirlinkConfigCountdownActivity.this, + GosConfigFailedActivity.class); + /** 判断是否是从一键配置界面传过去的 */ + intent.putExtra("isAirLink", true); + startActivity(intent); + } + break; + + default: + break; + + } + } + + }; + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + Intent intent = new Intent(GosAirlinkConfigCountdownActivity.this, GosMainActivity.class); + //quitAlert(this, intent); + quitAlert(this, intent, getString(R.string.cancel_configuration)); + overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); + return true; + } + return false; + } + + // 倒计时 + public void isStartTimer() { + + secondleft = 60; + timer = new Timer(); + timer.schedule(new TimerTask() { + @Override + public void run() { + secondleft--; + rpbConfig.setProgress((60 - secondleft) * (100 / 60.0)); + } + }, 1000, 1000); + } + + /** + * 设备配置回调 + * + * @param result 错误码 + * @param mac MAC + * @param did DID + * @param productKey PK + */ + protected void didSetDeviceOnboarding(GizWifiErrorCode result, String mac, + String did, String productKey) { + if (GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING == result) { + return; + } + + if (timer != null) { + timer.cancel(); + } + Message message = new Message(); + if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) { + message.what = handler_key.SUCCESSFUL.ordinal(); + } else if (result == GIZ_SDK_ONBOARDING_STOPPED) { + + } else { + message.what = handler_key.FAILED.ordinal(); + message.obj = toastError(result); + } + Log.i("Apptest", result.toString()); + handler.sendMessage(message); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkReadyActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkReadyActivity.java new file mode 100644 index 0000000..41cfb61 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosAirlinkReadyActivity.java @@ -0,0 +1,132 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Intent; +import android.graphics.Color; +import android.os.Bundle; +import android.text.SpannableString; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.utils.AssetsUtils; +import com.gizwits.opensource.appkit.utils.ToolUtils; + +import java.util.ArrayList; +import java.util.List; + +public class GosAirlinkReadyActivity extends GosConfigModuleBaseActivity implements OnClickListener { + + + /** + * The tv Ready + */ + TextView tvReady; + + + /** + * The btn Next + */ + Button btnNext; + + TextView tvDeviceTip; + + private int sum = 0; + + //private TextView moudlechoose; + + private List modeList; + private ImageView ivReady; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.actvity_gos_airlink_ready); + // 设置ActionBar + setToolBar(true, R.string.airlink_ready_title); + + initData(); + initView(); + initEvent(); + } + + private void initData() { + // workSSID = spf.getString("workSSID", ""); + + modeList = new ArrayList(); + String[] modes = this.getResources().getStringArray(R.array.mode); + for (String string : modes) { + modeList.add(string); + } + } + + private void initView() { + tvReady = (TextView) findViewById(R.id.tvReady); + btnNext = (Button) findViewById(R.id.btnNext); + tvDeviceTip = (TextView) findViewById(R.id.tvDeviceTip); + ivReady = (ImageView) findViewById(R.id.ivReady); + SpannableString spannableString = new SpannableString(getString(R.string.common_ready_message)); + if (AssetsUtils.isZh(this)) { + spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), 9, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } else { + spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), 28, 45, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + tvReady.setText(spannableString); + + // 配置文件部署 + btnNext.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnNext.setTextColor(GosDeploy.appConfig_Contrast()); + } + + private void initEvent() { + btnNext.setOnClickListener(this); + tvDeviceTip.setOnClickListener(this); + ivReady.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnNext: + if (ToolUtils.noDoubleClick()) { + sum = 0; + Intent intent = new Intent(this, GosAirlinkConfigCountdownActivity.class); + startActivity(intent); + } + break; + + default: + break; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + sum = 0; + this.finish(); + //overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); + break; + } + return true; + } + +// @Override +// public boolean onKeyDown(int keyCode, KeyEvent event) { +// Intent intent = new Intent(this, GosAirlinkChooseDeviceWorkWiFiActivity.class); +// startActivity(intent); +// overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); +// this.finish(); +// return true; +// } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceActivity.java new file mode 100644 index 0000000..3ba9e57 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceActivity.java @@ -0,0 +1,279 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.location.LocationManager; +import android.net.wifi.ScanResult; +import android.os.Bundle; +import android.os.Handler; +import android.util.Log; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.log.SDKLog; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.utils.AssetsUtils; + +import java.util.ArrayList; +import java.util.Timer; +import java.util.TimerTask; + +@SuppressLint({"InflateParams", "HandlerLeak"}) +public class GosChooseDeviceActivity extends GosConfigModuleBaseActivity implements OnClickListener { + + /** + * The tv Nodevice + */ + TextView tvNodevice; + + /** + * The list View + */ + ListView listView; + + /** + * 系统WiFi集合 + */ + ArrayList list; + + /** + * 设备热点集合 + */ + ArrayList softList; + + /** + * 适配器 + */ + Myadapter myadapter; + + /** + * 计时器 + */ + Timer timer; + + int flag = 0; + + private enum handler_key { + + /** + * 刷新列表 + */ + UPDATALIST, + + } + + Handler handler = new Handler() { + public void handleMessage(android.os.Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + // 更新列表 + case UPDATALIST: + initData(); + break; + } + } + + ; + + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_choose_device); + // 设置ActionBar + setToolBar(true, R.string.choosedevice); + + initView(); + initEvent(); + } + + @Override + protected void onResume() { + super.onResume(); + startTimer(); + } + + @Override + public void onPause() { + super.onPause(); + timer.cancel(); + } + + private void initData() { +// list = new ArrayList(); + list = (ArrayList) GosConstant.ssidList; + //list = (ArrayList) NetUtils.getCurrentWifiScanResult(GosChooseDeviceActivity.this); + softList = new ArrayList(); + ScanResult scanResult; + for (int i = 0; i < list.size(); i++) { + scanResult = list.get(i); + if (scanResult.SSID.length() > SoftAP_Start.length()) { + if (scanResult.SSID.contains(SoftAP_Start)) { + softList.add(scanResult); + } + } + } + myadapter = new Myadapter(softList); + listView.setAdapter(myadapter); + } + + private void initView() { + tvNodevice = (TextView) findViewById(R.id.nodevice); + listView = (ListView) findViewById(R.id.list_view); + } + + private void initEvent() { + tvNodevice.setOnClickListener(this); + + listView.setOnItemClickListener(new OnItemClickListener() { + + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + Intent intent = new Intent(GosChooseDeviceActivity.this, GosConfigCountdownActivity.class); + intent.putExtra("softSSID", softList.get(position).SSID); + startActivity(intent); + finish(); + } + }); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.nodevice: + if (list == null) { + LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + // 未打开位置开关,可能导致定位失败或定位不准,提示用户或做相应处理 + Toast.makeText(this, getString(R.string.open), Toast.LENGTH_LONG).show(); + return; + } + } else if (list.size() == 0) { + LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + // 未打开位置开关,可能导致定位失败或定位不准,提示用户或做相应处理 + Toast.makeText(this, getString(R.string.open), Toast.LENGTH_LONG).show(); + return; + } + } + finish(); + break; + + default: + break; + } + } + + private void startTimer() { + timer = new Timer(); + timer.schedule(new TimerTask() { + + @Override + public void run() { + handler.sendEmptyMessage(handler_key.UPDATALIST.ordinal()); + } + }, 0, 3000); + } + + class Myadapter extends BaseAdapter { + + ArrayList softList; + + public Myadapter(ArrayList list) { + this.softList = list; + } + + @Override + public int getCount() { + return softList.size(); + } + + @Override + public Object getItem(int position) { + return null; + } + + @Override + public long getItemId(int position) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + Holder holder; + if (view == null) { + view = LayoutInflater.from(GosChooseDeviceActivity.this).inflate(R.layout.item_gos_wifi_device, null); + holder = new Holder(view); + view.setTag(holder); + } else { + + holder = (Holder) view.getTag(); + } + String ssid = softList.get(position).SSID; + +// String itemStart = (String) getText(R.string.itemtext_start); +// String itemEnd = (String) getText(R.string.itemtext_end); + String s = ""; + if (AssetsUtils.isZh(GosChooseDeviceActivity.this)) { + s = getString(R.string.device) + ssid.substring(ssid.length() - 4); + } else { + s = getString(R.string.device) + " " + ssid.substring(ssid.length() - 4); + } + holder.getTextView().setText(s); + + return view; + } + } + + class Holder { + View view; + + public Holder(View view) { + this.view = view; + } + + TextView textView; + + public TextView getTextView() { + if (textView == null) { + textView = (TextView) view.findViewById(R.id.SSID_text); + } + return textView; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + break; + } + return true; + } + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + finish(); + return true; + } + return false; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceWorkWiFiActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceWorkWiFiActivity.java new file mode 100644 index 0000000..0041362 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceWorkWiFiActivity.java @@ -0,0 +1,465 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.location.LocationManager; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiInfo; +import android.os.Bundle; +import android.support.v4.app.ActivityCompat; +import android.text.TextUtils; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.NetUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +public class GosChooseDeviceWorkWiFiActivity extends GosConfigModuleBaseActivity + implements OnClickListener, OnItemClickListener { + + private AlertDialog create; + private ArrayList wifiList; + + private static final int REQUEST_EXTERNAL_STORAGE = 1; + private static String[] PERMISSIONS_STORAGE = { + "android.permission.ACCESS_FINE_LOCATION", + "android.permission.ACCESS_COARSE_LOCATION"}; + + /** + * wifi信息 + */ + public WifiInfo wifiInfo; + + /** + * The et SSID + */ + private EditText etSSID; + + /** + * The et Psw + */ + private EditText etPsw; + + /** + * The btn Next + */ + private Button btnNext; + + /** + * The cb Laws + */ + private CheckBox cbLaws; + + /** + * The img WiFiList + */ + private RelativeLayout rlWiFiList; + + /** + * 配置用参数 + */ + private String softSSID, workSSID, workSSIDPsw; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_choose_device_workwifi); + // 设置ActionBar + setToolBar(true, R.string.choose_wifi); + + initData(); + initView(); + ininEvent(); + } + + private void initView() { + etSSID = (EditText) findViewById(R.id.etSSID); + etPsw = (EditText) findViewById(R.id.etPsw); + btnNext = (Button) findViewById(R.id.btnNext); + cbLaws = (CheckBox) findViewById(R.id.cbLaws); + rlWiFiList = (RelativeLayout) findViewById(R.id.rlWiFiList); + // 配置文件部署 + btnNext.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnNext.setTextColor(GosDeploy.appConfig_Contrast()); + if (!TextUtils.isEmpty(workSSID)) { + etSSID.setText(workSSID); + etSSID.setSelection(workSSID.length()); + if (checkworkSSIDUsed(workSSID)) { + if (!TextUtils.isEmpty(spf.getString("workSSIDPsw", ""))) { + etPsw.setText(spf.getString("workSSIDPsw", "")); + } + } + } + } + + + private void ininEvent() { + + btnNext.setOnClickListener(this); + rlWiFiList.setOnClickListener(this); + + cbLaws.setOnCheckedChangeListener(new OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + String psw = etPsw.getText().toString(); + + if (isChecked) { + etPsw.setInputType(0x90); + } else { + etPsw.setInputType(0x81); + } + etPsw.setSelection(psw.length()); + } + }); + + //检测是否有位置定位的权限 + int permission = ActivityCompat.checkSelfPermission(GosChooseDeviceWorkWiFiActivity.this, + "android.permission.ACCESS_FINE_LOCATION"); + if (permission != PackageManager.PERMISSION_GRANTED) { + try { + // 没有写的权限,去申请写的权限,会弹出对话框 + ActivityCompat.requestPermissions(GosChooseDeviceWorkWiFiActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + private void initData() { + //softSSID = getIntent().getStringExtra("softssid"); + workSSID = spf.getString("workSSID", ""); + } + + + @Override + protected void onResume() { + super.onResume(); + + try { + // 预设workSSID && workSSIDPsw + workSSID = NetUtils.getCurentWifiSSID(this); + String mypass = spf.getString("mypass", ""); + + if (!TextUtils.isEmpty(workSSID)) { + etSSID.setText(workSSID); + etSSID.setSelection(workSSID.length()); + if (!TextUtils.isEmpty(mypass)) { + JSONObject obj = new JSONObject(mypass); + + if (obj.has(workSSID)) { + String pass = obj.getString(workSSID); + etPsw.setText(pass); + } else { + etPsw.setText(""); + } + } + + } else { + etSSID.setText(NetUtils.getCurentWifiSSID(this)); + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + Intent intent = new Intent(this, GosMainActivity.class); + startActivity(intent); + //quitAlert(this, intent); + break; + } + return true; + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnNext: + workSSID = etSSID.getText().toString(); + workSSIDPsw = etPsw.getText().toString(); + + if (TextUtils.isEmpty(workSSID)) { + Toast.makeText(GosChooseDeviceWorkWiFiActivity.this, R.string.choose_wifi_list_title, + Toast.LENGTH_SHORT).show(); + return; + } + if (TextUtils.isEmpty(workSSIDPsw)) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_empty); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + if (dialog.isShowing()) { + dialog.cancel(); + } + Intent intent = null; + //wifiModuleType-false-start wifiModuleType-true-start + if (GosDeploy.appConfig_WifiModuleType().size() == 0) { + //wifiModuleType-false-end + intent = new Intent(GosChooseDeviceWorkWiFiActivity.this, + GosModeListActivity2.class); + //wifiModuleType-false-start + } else { + //wifiModuleType-true-end + List moduleTypes = GosDeploy.appConfig_WifiModuleType(); + JSONArray array = new JSONArray(); + for (int type : moduleTypes) { + if (type == 4) { + type = 0; + } else if (type < 4) { + type = type + 1; + } else if (type == 12) { + type = 6; + } else if (type >= 6 && type < 12) { + type = type + 1; + } + array.put(type); + } + spf.edit().putString("modulestyles", array.toString()).commit(); + intent = new Intent(GosChooseDeviceWorkWiFiActivity.this, + GosDeviceReadyActivity.class); + //wifiModuleType-true-start + } + //wifiModuleType-false-end wifiModuleType-true-end + spf.edit().putString("workSSID", workSSID).commit(); + spf.edit().putString("workSSIDPsw", workSSIDPsw).commit(); + intent.putExtra("isAirlink", false); + startActivity(intent); + } + }); + } else { + Intent intent = null; + //wifiModuleType-false-start wifiModuleType-true-start + if (GosDeploy.appConfig_WifiModuleType().size() == 0) { + //wifiModuleType-false-end + intent = new Intent(GosChooseDeviceWorkWiFiActivity.this, + GosModeListActivity2.class); + //wifiModuleType-false-start + } else { + //wifiModuleType-true-end + List moduleTypes = GosDeploy.appConfig_WifiModuleType(); + JSONArray array = new JSONArray(); + for (int type : moduleTypes) { + if (type == 4) { + type = 0; + } else if (type < 4) { + type = type + 1; + } else if (type == 12) { + type = 6; + } else if (type >= 6 && type < 12) { + type = type + 1; + } + array.put(type); + } + spf.edit().putString("modulestyles", array.toString()).commit(); + intent = new Intent(GosChooseDeviceWorkWiFiActivity.this, + GosDeviceReadyActivity.class); + //wifiModuleType-true-start + } + //wifiModuleType-false-end wifiModuleType-true-end + spf.edit().putString("workSSID", workSSID).commit(); + spf.edit().putString("workSSIDPsw", workSSIDPsw).commit(); + /** 判断是否是从一键配置界面传过去的 */ + intent.putExtra("isAirlink", false); + startActivity(intent); + } + break; + + case R.id.rlWiFiList: + AlertDialog.Builder dia = new AlertDialog.Builder(GosChooseDeviceWorkWiFiActivity.this); + View view = View.inflate(GosChooseDeviceWorkWiFiActivity.this, R.layout.alert_gos_wifi_list, null); + ListView listview = (ListView) view.findViewById(R.id.wifi_list); + List rsList = NetUtils.getCurrentWifiScanResult(this); + List localList = new ArrayList(); + localList.clear(); + wifiList = new ArrayList(); + wifiList.clear(); + + for (ScanResult sss : rsList) { + if (sss.SSID.contains(GosConstant.SoftAP_Start)) { + + } else { + if (localList.toString().contains(sss.SSID)) { + } else { + localList.add(sss.SSID); + wifiList.add(sss); + } + } + } + if (wifiList.size() == 0) { + LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { + // 未打开位置开关,可能导致定位失败或定位不准,提示用户或做相应处理 + Toast.makeText(this, getString(R.string.open), Toast.LENGTH_LONG).show(); + return; + } + } + + WifiListAdapter adapter = new WifiListAdapter(wifiList); + listview.setAdapter(adapter); + listview.setOnItemClickListener(this); + dia.setView(view); + create = dia.create(); + create.show(); + + break; + + default: + break; + } + } + + @Override + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { + + ScanResult sResult = wifiList.get(arg2); + String sSID = sResult.SSID; + etSSID.setText(sSID); + etSSID.setSelection(sSID.length()); + etPsw.setText(""); + create.dismiss(); + } + + // 检查当前使用的WiFi是否曾经用过 + protected boolean checkworkSSIDUsed(String workSSID) { + if (spf.contains("workSSID")) { + if (spf.getString("workSSID", "").equals(workSSID)) { + return true; + } + } + return false; + } + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + Intent intent = new Intent(this, GosMainActivity.class); + startActivity(intent); + //quitAlert(this, intent); + return true; + } + return false; + } + + class WifiListAdapter extends BaseAdapter { + + ArrayList xpgList; + + public WifiListAdapter(ArrayList list) { + this.xpgList = list; + } + + @Override + public int getCount() { + return xpgList.size(); + } + + @Override + public Object getItem(int position) { + return null; + } + + @Override + public long getItemId(int position) { + return 0; + } + + @SuppressLint("InflateParams") + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + Holder holder; + if (view == null) { + view = LayoutInflater.from(GosChooseDeviceWorkWiFiActivity.this).inflate(R.layout.item_gos_wifi_list, + null); + holder = new Holder(view); + view.setTag(holder); + } else { + holder = (Holder) view.getTag(); + } + String ssid = xpgList.get(position).SSID; + holder.getTextView().setText(ssid); + + return view; + } + + } + + class Holder { + View view; + + public Holder(View view) { + this.view = view; + } + + TextView textView; + + public TextView getTextView() { + if (textView == null) { + textView = (TextView) view.findViewById(R.id.SSID_text); + } + return textView; + } + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseModuleHelpActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseModuleHelpActivity.java new file mode 100644 index 0000000..96efd82 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosChooseModuleHelpActivity.java @@ -0,0 +1,41 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.os.Bundle; +import android.webkit.WebSettings; +import android.webkit.WebView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.AssetsUtils; + + +/** + * Created by admin on 2017/6/15. + */ + +public class GosChooseModuleHelpActivity extends com.gizwits.opensource.appkit.ConfigModule.GosConfigModuleBaseActivity { + private WebView webHelp; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_choose_module_help); + initView(); + initEvent(); + } + + private void initEvent() { + setToolBar(true, getString(R.string.module_help)); + WebSettings wSet = webHelp.getSettings(); + wSet.setJavaScriptEnabled(true); + if (AssetsUtils.isZh(this)) { + webHelp.loadUrl("file:///android_asset/moduleTypeInfo.html"); + } else { + webHelp.loadUrl("file:///android_asset/moduleTypeInfoEnglish.html"); + } + + } + + private void initView() { + webHelp = (WebView) findViewById(R.id.webHelp); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigCountdownActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigCountdownActivity.java new file mode 100644 index 0000000..c51b93a --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigCountdownActivity.java @@ -0,0 +1,424 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiConfigureMode; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.enumration.GizWifiGAgentType; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +import com.gizwits.opensource.appkit.utils.NetUtils; +import com.gizwits.opensource.appkit.view.RoundProgressBar; +import com.gizwits.opensource.appkit.R; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.style.ForegroundColorSpan; +import android.view.KeyEvent; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import org.json.JSONArray; +import org.json.JSONException; + +import static com.gizwits.gizwifisdk.enumration.GizWifiErrorCode.GIZ_SDK_ONBOARDING_STOPPED; + +@SuppressLint("HandlerLeak") +public class GosConfigCountdownActivity extends GosConfigModuleBaseActivity { + + private GosWifiChangeReciver broadcase; + + /** + * The rpb Config + */ + private RoundProgressBar rpbConfig; + + /** + * 倒计时 + */ + int secondleft = 60; + + /** + * The timer + */ + Timer timer; + + /** + * The Frist + */ + boolean isFrist = true; + + /** + * The isChecked + */ + boolean isChecked = false; + + String softSSID, presentSSID, workSSID, workSSIDPsw; + + private boolean isShowing = false; + private String SSID = null, SSIDPsw = null; + List modeList, modeDataList; + private TextView tvLeft; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_config_countdown); + // 设置ActionBar + setToolBar(false, R.string.search_join); + initView(); + initData(); + tvLeft = (TextView) findViewById(R.id.tvLeft); + tvLeft.setVisibility(View.VISIBLE); + SpannableString ssTitle = new SpannableString(this.getString(R.string.cancel)); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvLeft.setText(ssTitle); + tvLeft.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(GosConfigCountdownActivity.this, GosMainActivity.class); + quitAlert(GosConfigCountdownActivity.this, intent, getString(R.string.cancel_configuration)); + } + }); + } + + @Override + public void onWindowFocusChanged(boolean hasFocus) { + super.onWindowFocusChanged(hasFocus); + if (hasFocus && isFrist) { + isShowing = true; + new Thread() { + public void run() { + try { + Thread.sleep(1 * 1000); + readyToSoftAP(); + } catch(InterruptedException e) { + e.printStackTrace(); + } + + } + + ; + }.start(); + + isFrist = false; + } + } + + private void initView() { + rpbConfig = (RoundProgressBar) findViewById(R.id.rpbConfig); + } + + private void initData() { + softSSID = getIntent().getStringExtra("softSSID"); + workSSIDPsw = spf.getString("workSSIDPsw", ""); + modeDataList = new ArrayList(); + modeDataList.add(GizWifiGAgentType.GizGAgentESP); + modeDataList.add(GizWifiGAgentType.GizGAgentMXCHIP); + modeDataList.add(GizWifiGAgentType.GizGAgentHF); + modeDataList.add(GizWifiGAgentType.GizGAgentRTK); + modeDataList.add(GizWifiGAgentType.GizGAgentWM); + modeDataList.add(GizWifiGAgentType.GizGAgentQCA); + modeDataList.add(GizWifiGAgentType.GizGAgentFlyLink); + modeDataList.add(GizWifiGAgentType.GizGAgentTI); + modeDataList.add(GizWifiGAgentType.GizGAgentFSK); + modeDataList.add(GizWifiGAgentType.GizGAgentMXCHIP3); + modeDataList.add(GizWifiGAgentType.GizGAgentBL); + modeDataList.add(GizWifiGAgentType.GizGAgentAtmelEE); + modeDataList.add(GizWifiGAgentType.GizGAgentOther); + modeList = new ArrayList(); + + String types = spf.getString("modulestyles", null); + if (types != null) { + try { + JSONArray array = new JSONArray(types); + for (int i = 0; i < array.length(); i++) { + int type = (Integer) array.get(i); + modeList.add(modeDataList.get(type)); + } + } catch(JSONException e) { + e.printStackTrace(); + } + } + } + + private enum handler_key { + + /** + * 倒计时结束 + */ + TICK_TIME, + + /** + * 设置手机开启热点 + */ + OPEN_HOT, + + /** + * 倒计时开始 + */ + START_TIMER, + + /** + * 配置成功 + */ + SUCCESSFUL, + + /** + * 配置失败 + */ + FAILED, + + } + + private static final String TAG = "GosConfigCountdownActiv"; + /** + * The handler. + */ + Handler handler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + + case TICK_TIME: + + break; + case OPEN_HOT: + if (GosConstant.isOpenHot) { + boolean b = setWifiApEnabled(true); + // boolean b = setWifiAp(true); + } + break; + + case START_TIMER: + isStartTimer(); + break; + // 配置成功 + case SUCCESSFUL: + Toast.makeText(GosConfigCountdownActivity.this, R.string.configuration_successful, toastTime) + .show(); + Intent intent1 = new Intent(GosConfigCountdownActivity.this, GosMainActivity.class); + startActivity(intent1); + break; + // 配置失败 + case FAILED: + isChecked = false; + if (msg.obj != null) { + Toast.makeText(GosConfigCountdownActivity.this, msg.obj.toString(), toastTime) + .show(); + } + Intent intent = new Intent(GosConfigCountdownActivity.this, GosConfigFailedActivity.class); + startActivity(intent); + finish(); + break; + + + default: + break; + + } + } + }; + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + quitAlert(this, timer); + return true; + } + return false; + } + + // 倒计时 + public void isStartTimer() { + secondleft = 60; + timer = new Timer(); + // 切换至设备热点 + wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); + final WifiAutoConnectManager.WifiCipherType cipherType = WifiAutoConnectManager.getCipherType(GosConfigCountdownActivity.this, softSSID); + final WifiAutoConnectManager manager = new WifiAutoConnectManager(wifiManager); + timer.schedule(new TimerTask() { + @Override + public void run() { + if (isShowing) { + manager.connect(softSSID, SoftAP_PSW, cipherType); + } + secondleft--; + rpbConfig.setProgress((60 - secondleft) * (100 / 60.0)); + if (secondleft == 1) { + handler.sendEmptyMessage(handler_key.FAILED.ordinal()); + timer.cancel(); + } + + } + }, 1000, 1000); + } + + private void readyToSoftAP() { + + IntentFilter filter = new IntentFilter(); + filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); + + workSSID = spf.getString("workSSID", ""); + workSSIDPsw = spf.getString("workSSIDPsw", ""); + if (!workSSIDPsw.isEmpty() && workSSIDPsw.equals(GosConstant.SSIDPsw)) { + GosConstant.isOpenHot = true; + } + //新加 + handler.sendEmptyMessage(handler_key.START_TIMER.ordinal()); + isChecked = true; + while (isChecked) { + String presentSSID = NetUtils.getCurentWifiSSID(GosConfigCountdownActivity.this); + if (!TextUtils.isEmpty(presentSSID) && presentSSID.contains(SoftAP_Start)) { + if (checkNetwork(GosConfigCountdownActivity.this)) { + String connectWifiSsid = NetUtils.getConnectWifiSsid(GosConfigCountdownActivity.this); + isShowing = false; + isChecked = false; + //handler.sendEmptyMessage(handler_key.START_TIMER.ordinal()); + switch (GosConstant.mNew) { + case 0: + GizWifiSDK.sharedInstance().setDeviceOnboarding(workSSID, workSSIDPsw, + GizWifiConfigureMode.GizWifiSoftAP, presentSSID, 60, modeList); + break; + case 1: + GizWifiSDK.sharedInstance().setDeviceOnboardingByBind(workSSID, workSSIDPsw, + GizWifiConfigureMode.GizWifiSoftAP, presentSSID, 60, modeList); + break; + case 2: + GizWifiSDK.sharedInstance().setDeviceOnboardingDeploy(workSSID, workSSIDPsw, + GizWifiConfigureMode.GizWifiSoftAP, presentSSID, 60, modeList, false); + break; + case 3: + GizWifiSDK.sharedInstance().setDeviceOnboardingDeploy(workSSID, workSSIDPsw, + GizWifiConfigureMode.GizWifiSoftAP, presentSSID, 60, modeList, true); + break; + } + if (GosConstant.isOpenHot) { + final Timer mtimer1 = new Timer(); + mtimer1.schedule(new TimerTask() { + @Override + public void run() { + handler.sendEmptyMessage(handler_key.OPEN_HOT.ordinal()); + } + }, 5 * 1000); + } + // handler.sendEmptyMessageDelayed(handler_key.OFFTIME.ordinal(), 2000); + } + if (broadcase == null && !GosConstant.isOpenHot) { + broadcase = new GosWifiChangeReciver(); + registerReceiver(broadcase, filter); + } + + } + } + } + + + private WifiManager wifiManager = null; + + + // wifi热点开关 + public boolean setWifiApEnabled(boolean enabled) { + //获取wifi管理服务 + if (enabled) { // disable WiFi in any case + //wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi + wifiManager.setWifiEnabled(false); + } + try { + //热点的配置类 + WifiConfiguration apConfig = new WifiConfiguration(); + //配置热点的名称(可以在名字后面加点随机数什么的) + if (SSID == null && SSID.equals("")) { + SSID = android.os.Build.MODEL; + apConfig.SSID = SSID; + apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + } else if (SSIDPsw == null && SSIDPsw.equals("")) { + apConfig.SSID = SSID; + apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + } else { + apConfig.SSID = SSID; + //配置热点的密码 + apConfig.preSharedKey = SSIDPsw; + //返回热点打开状态 +// for (int i = 0; i < WifiConfiguration.KeyMgmt.strings.length; i++) { +// if ("WPA2_PSK".equals(WifiConfiguration.KeyMgmt.strings[i])) { +// apConfig.allowedKeyManagement.set(i);//直接给它赋索引的值 +// Log.e("wpa2索引", String.valueOf(i));//结果是4 +// } +// } + apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);//直接给它赋索引的值 + } + //通过反射调用设置热点 + Method method = wifiManager.getClass().getMethod( + "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE); + //返回热点打开状态 + return (Boolean) method.invoke(wifiManager, apConfig, enabled); + } catch(Exception e) { + return false; + } + + } + + + /** + * 设备配置回调 + * + * @param result 错误码 + * @param mac MAC + * @param did DID + * @param productKey PK + */ + protected void didSetDeviceOnboarding(GizWifiErrorCode result, String mac, String did, String productKey) { + if (GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING == result) { + return; + } + if (timer != null) { + timer.cancel(); + } + Message message = new Message(); + if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) { + message.what = handler_key.SUCCESSFUL.ordinal(); + } else if (result == GIZ_SDK_ONBOARDING_STOPPED) { + + } else { + message.what = handler_key.FAILED.ordinal(); + message.obj = toastError(result); + } + handler.sendMessage(message); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + isChecked = false; + if (timer != null) { + timer.cancel(); + } + if (broadcase != null) { + unregisterReceiver(broadcase); + broadcase = null; + } + + + } +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigFailedActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigFailedActivity.java new file mode 100644 index 0000000..b2a00e9 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigFailedActivity.java @@ -0,0 +1,118 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Intent; +import android.os.Bundle; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.style.ForegroundColorSpan; +import android.view.KeyEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +import com.gizwits.opensource.appkit.utils.ToolUtils; + +public class GosConfigFailedActivity extends GosConfigModuleBaseActivity implements OnClickListener { + + /** + * The btn Again + */ + Button btnAgain; + + /** + * The soft SSID + */ + String softSSID; + + /** + * The data + */ + String promptText, cancelBesureText, beSureText, cancelText; + private boolean isAirLink; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_config_failed); + // 设置ActionBar + setToolBar(false, R.string.join_failed_title); + TextView tvLeft = (TextView) findViewById(R.id.tvLeft); + tvLeft.setVisibility(View.VISIBLE); + SpannableString ssTitle = new SpannableString(this.getString(R.string.cancel)); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvLeft.setText(ssTitle); + tvLeft.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(GosConfigFailedActivity.this, GosMainActivity.class); + quitAlert(GosConfigFailedActivity.this, intent); + } + }); + initView(); + initEvent(); + initData(); + } + + private void initView() { + btnAgain = (Button) findViewById(R.id.btnAgain); + + // 配置文件部署 + btnAgain.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnAgain.setTextColor(GosDeploy.appConfig_Contrast()); + } + + private void initEvent() { + btnAgain.setOnClickListener(this); + } + + private void initData() { + /** 判断是否是从一键配置界面传过去的 */ + isAirLink = getIntent().getBooleanExtra("isAirLink", false); + promptText = (String) getText(R.string.prompt); + cancelBesureText = (String) getText(R.string.cancel_besure); + beSureText = (String) getText(R.string.besure); + cancelText = (String) getText(R.string.cancel); + } + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + Intent intent = new Intent(GosConfigFailedActivity.this, GosMainActivity.class); + quitAlert(this, intent); + return true; + } + return false; + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnAgain: + if (ToolUtils.noDoubleClick()) { + if (isAirLink) { + //config_airlink-false-start + Intent intent = new Intent(this, GosAirlinkChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + //config_airlink-false-end + } else { + // config_softap-false-start + Intent intent = new Intent(this, GosChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + // config_softap-false-end + } + + } + + break; + + default: + break; + } + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigModuleBaseActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigModuleBaseActivity.java new file mode 100644 index 0000000..4597b29 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosConfigModuleBaseActivity.java @@ -0,0 +1,238 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.util.Log; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.Window; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizWifiSDKListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; + +import java.util.List; +import java.util.Timer; + +public class GosConfigModuleBaseActivity extends GosBaseActivity { + + private GizWifiSDKListener gizWifiSDKListener = new GizWifiSDKListener() { + + /** 用于设备配置 */ + public void didSetDeviceOnboarding(GizWifiErrorCode result, String mac, String did, String productKey) { + GosConfigModuleBaseActivity.this.didSetDeviceOnboarding(result, mac, did, productKey); + } + + }; + + /** + * 设备配置回调 + * + * @param result 错误码 + * @param mac MAC + * @param did DID + * @param productKey PK + */ + protected void didSetDeviceOnboarding(GizWifiErrorCode result, String mac, String did, String productKey) { + } + + @Override + protected void onResume() { + super.onResume(); + // 每次返回activity都要注册一次sdk监听器,保证sdk状态能正确回调 + GizWifiSDK.sharedInstance().setListener(gizWifiSDKListener); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return super.onOptionsItemSelected(item); + } + + /** + * 推出提示 + * + * @param context 当前上下文 + */ + protected void quitAlert(Context context, final Intent intent) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + if (dialog.isShowing()) { + dialog.cancel(); + } + startActivity(intent); + + } + }); + } + + /** + * 推出提示 + * + * @param context 当前上下文 + */ + protected void quitAlert(Context context) { + final Dialog dialog = new AlertDialog.Builder(context, R.style.alert_dialog_style).setView(new EditText(context)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + + if (dialog.isShowing()) { + dialog.cancel(); + } + finish(); + + } + }); + } + + /** + * 推出提示 + * + * @param context 当前上下文 + */ + protected void quitAlert(Context context, final Intent intent, String content) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + TextView tvContent; + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + tvContent = (TextView) window.findViewById(R.id.tv_prompt); + + tvContent.setText(content); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + GizWifiSDK.sharedInstance().stopDeviceOnboarding(); + startActivity(intent); + } + }); + } + + + /** + * 退出提示 + * + * @param context 当前上下文 + * @param timer 已开启定时器 + */ + protected void quitAlert(Context context, final Timer timer) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + GizWifiSDK.sharedInstance().stopDeviceOnboarding(); + if (timer != null) { + timer.cancel(); + } + if (dialog.isShowing()) { + dialog.cancel(); + } + finish(); + } + }); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosDeviceReadyActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosDeviceReadyActivity.java new file mode 100644 index 0000000..e8851a8 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosDeviceReadyActivity.java @@ -0,0 +1,139 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Intent; +import android.graphics.Color; +import android.os.Bundle; +import android.text.SpannableString; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.AssetsUtils; +import com.gizwits.opensource.appkit.utils.ToolUtils; + +public class GosDeviceReadyActivity extends GosConfigModuleBaseActivity implements OnClickListener { + + /** + * The tv Ready + */ + TextView tvReady; + + /** + * The tv DeviceTip + */ + TextView tvDeviceTips; + + /** + * The btn Next + */ + Button btnNext; + + private int sum = 0; + /** + * The flag + */ + boolean flag = false; + + boolean isAirLink = false; + private ImageView ivReady; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_device_ready); + // 设置ActionBar + setToolBar(true, R.string.model_confirmation); + /** 判断是否是从一键配置界面传过去的 */ + isAirLink = getIntent().getBooleanExtra("isAirLink", false); + + initView(); + initEvent(); + } + + private void initView() { + tvReady = (TextView) findViewById(R.id.tvReady); + tvDeviceTips = (TextView) findViewById(R.id.tvDeviceTip); + btnNext = (Button) findViewById(R.id.btnNext); + ivReady = (ImageView) findViewById(R.id.ivReady); + SpannableString spannableString = new SpannableString(getString(R.string.common_ready_message)); + if (AssetsUtils.isZh(this)) { + spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF9500")), 9, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } else { + spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF9500")), 28, 45, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + + tvReady.setText(spannableString); + + // 配置文件部署 + btnNext.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnNext.setTextColor(GosDeploy.appConfig_Contrast()); + + } + + private void initEvent() { + btnNext.setOnClickListener(this); + tvDeviceTips.setOnClickListener(this); + ivReady.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + + case R.id.btnNext: + if (ToolUtils.noDoubleClick()) { + sum = 0; + Intent intent2 = new Intent(GosDeviceReadyActivity.this, GosChooseDeviceActivity.class); + startActivity(intent2); + } + + break; + + default: + break; + } + } + + // 屏蔽掉返回键 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + sum = 0; + if (isAirLink) { + Intent intent = new Intent(GosDeviceReadyActivity.this, GosMainActivity.class); + startActivity(intent); + } else { + finish(); + } + return true; + } + return false; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + sum = 0; + if (isAirLink) { + Intent intent = new Intent(GosDeviceReadyActivity.this, GosMainActivity.class); + startActivity(intent); + } else { + finish(); + } + break; + } + return true; + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosDeviceResetActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosDeviceResetActivity.java new file mode 100644 index 0000000..f2aec95 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosDeviceResetActivity.java @@ -0,0 +1,143 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +public class GosDeviceResetActivity extends GosConfigModuleBaseActivity implements OnClickListener { + + /** + * The cb Select + */ + CheckBox cbSelect; + + /** + * The tv Select + */ + TextView tvSelect; + + /** + * The btn Next + */ + Button btnNext; + + /** + * The flag + */ + String flag; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.actvity_gos_device_reset); + // 设置ActionBar + setToolBar(true, R.string.reset_device); + + initView(); + initEvent(); + } + + private void initView() { + cbSelect = (CheckBox) findViewById(R.id.cbSelect); + tvSelect = (TextView) findViewById(R.id.tvSelect); + btnNext = (Button) findViewById(R.id.btnNext); + + + /** 加载标志位 */ + flag = getIntent().getStringExtra("flag").toString(); + + // 配置文件部署 + btnNext.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnNext.setTextColor(GosDeploy.appConfig_Contrast()); + + } + + private void initEvent() { + btnNext.setOnClickListener(this); + tvSelect.setOnClickListener(this); + btnNext.setClickable(false); + btnNext.setBackgroundResource(R.drawable.btn_next_shape_gray); + + cbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + btnNext.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnNext.setClickable(true); + } else { + btnNext.setBackgroundResource(R.drawable.btn_next_shape_gray); + btnNext.setClickable(false); + } + + } + }); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnNext: + if (TextUtils.isEmpty(flag)) { + Intent intent = new Intent(GosDeviceResetActivity.this, GosChooseDeviceActivity.class); + startActivity(intent); + } + finish(); + + break; + + case R.id.tvSelect: + if (cbSelect.isChecked()) { + cbSelect.setChecked(false); + } else { + cbSelect.setChecked(true); + } + break; + + default: + break; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + if (TextUtils.isEmpty(flag)) { + Intent intent = new Intent(GosDeviceResetActivity.this, GosDeviceReadyActivity.class); + startActivity(intent); + overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); + } + this.finish(); + + break; + } + return true; + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (TextUtils.isEmpty(flag)) { + Intent intent = new Intent(GosDeviceResetActivity.this, GosDeviceReadyActivity.class); + startActivity(intent); + overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); + } + this.finish(); + + } + return true; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosModeListActivity.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosModeListActivity.java new file mode 100644 index 0000000..68266e1 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosModeListActivity.java @@ -0,0 +1,222 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Context; +import android.content.Intent; +import android.graphics.PorterDuff; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.utils.ToolUtils; + +import org.json.JSONArray; +import org.json.JSONException; + +import java.util.ArrayList; +import java.util.List; + +public class GosModeListActivity extends GosConfigModuleBaseActivity { + + /** + * The lv Mode + */ + ListView lvMode; + + /** + * The data + */ + List modeList; + + /** + * The Adapter + */ + ModeListAdapter modeListAdapter; + + List list = new ArrayList(); + + private Button btnOk; + + private boolean isAirlink = true; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_modelist); + // 设置ActionBar + setToolBar(true, R.string.choose_mode_start); + final Drawable add = getResources().getDrawable(R.drawable.config_help_button); + int color = GosDeploy.appConfig_Contrast(); + add.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); + mToolbar.setOverflowIcon(add); + initData(); + initView(); + initEvent(); + } + + private void initView() { + lvMode = (ListView) findViewById(R.id.lvMode); + + lvMode.setAdapter(modeListAdapter);// 初始化 + + btnOk = (Button) findViewById(R.id.btnOk); + btnOk.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnOk.setTextColor(GosDeploy.appConfig_Contrast()); + + } + + private void initEvent() { + + lvMode.setOnItemClickListener(new OnItemClickListener() { + + @Override + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { + modeListAdapter.selectIndex = arg2; + modeListAdapter.notifyDataSetChanged(); + } + }); + + btnOk.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (ToolUtils.noDoubleClick()) { + if (modeListAdapter.selectIndex == 100) { + Toast.makeText(GosModeListActivity.this, getString(R.string.selece_module_type), toastTime).show(); + } else { + JSONArray array = new JSONArray(); + array.put(modeListAdapter.selectIndex); + spf.edit().putString("modulestyles", array.toString()).commit(); + if (isAirlink) { + // config_airlink-false-start + Intent intent = new Intent(GosModeListActivity.this, GosAirlinkReadyActivity.class); + startActivity(intent); + // config_airlink-false-end + } else { + //config_softap-false-start + Intent intent = new Intent(GosModeListActivity.this, GosDeviceReadyActivity.class); + startActivity(intent); + //config_softap-false-end + } + } + } + + } + }); + } + + private void initData() { + isAirlink = getIntent().getBooleanExtra("isAirlink", true); + modeList = new ArrayList(); + String[] modes = this.getResources().getStringArray(R.array.mode); + for (String string : modes) { + modeList.add(string); + } + modeListAdapter = new ModeListAdapter(this, modeList); + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.module_style, menu); + return super.onCreateOptionsMenu(menu); + } + + class ModeListAdapter extends BaseAdapter { + + Context context; + List modeList; + int selectIndex = 100; + + public ModeListAdapter(Context context, List modeList) { + super(); + this.context = context; + this.modeList = modeList; + if (spf.getString("modulestyles", null) != null) { + try { + JSONArray array = new JSONArray(spf.getString("modulestyles", null)); + for (int i = 0; i < array.length(); i++) { + selectIndex = Integer.parseInt(array.get(i).toString()); + } + } catch(JSONException e) { + e.printStackTrace(); + } + } + } + + @Override + public int getCount() { + return modeList.size(); + } + + @Override + public Object getItem(int position) { + return null; + } + + @Override + public long getItemId(int position) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + if (null == convertView) { + convertView = View.inflate(context, R.layout.item_gos_mode_list, null); + } + + TextView tvModeText = (TextView) convertView.findViewById(R.id.tvModeText); + + String modeText = modeList.get(position); + tvModeText.setText(modeText); + + ImageView ivChoosed = (ImageView) convertView.findViewById(R.id.ivChoosed); + if (selectIndex == position) { + ivChoosed.setVisibility(View.VISIBLE); + } else { + ivChoosed.setVisibility(View.GONE); + } + + + return convertView; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); + break; + case R.id.module_help: + if (ToolUtils.noDoubleClick()) { + startActivity(new Intent(GosModeListActivity.this, GosChooseModuleHelpActivity.class)); + } + break; + } + return true; + } + +// @Override +// public boolean onKeyDown(int keyCode, KeyEvent event) { +// Intent intent = new Intent(this, GosAirlinkChooseDeviceWorkWiFiActivity.class); +// startActivity(intent); +// overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); +// this.finish(); +// return true; +// } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosModeListActivity2.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosModeListActivity2.java new file mode 100644 index 0000000..c2391e9 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosModeListActivity2.java @@ -0,0 +1,219 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.utils.ToolUtils; + +import org.json.JSONArray; +import org.json.JSONException; + +import java.util.ArrayList; +import java.util.List; + +public class GosModeListActivity2 extends GosConfigModuleBaseActivity { + + /** + * The lv Mode + */ + ListView lvMode; + + /** + * The data + */ + List modeList; + + /** + * The Adapter + */ + ModeListAdapter modeListAdapter; + + List list = new ArrayList(); + + private Button btnOk; + private boolean isAirlink = true; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_modelist); + // 设置ActionBar + setToolBar(true, R.string.choose_mode_start); + initData(); + initView(); + initEvent(); + } + + private void initView() { + lvMode = (ListView) findViewById(R.id.lvMode); + + lvMode.setAdapter(modeListAdapter);// 初始化 + + btnOk = (Button) findViewById(R.id.btnOk); + btnOk.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnOk.setTextColor(GosDeploy.appConfig_Contrast()); + } + + private void initEvent() { + + lvMode.setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { + boolean isRemove = false; + for (int i = 0; i < list.size(); i++) { + if (list.get(i) == arg2) { + list.remove(i); + isRemove = true; + } + } + if (!isRemove) { + list.add(arg2); + } + modeListAdapter.notifyDataSetChanged(); + } + }); + + + btnOk.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (ToolUtils.noDoubleClick()) { + if (list.size() == 0) { + Toast.makeText(GosModeListActivity2.this, getString(R.string.selece_module_type), toastTime).show(); + } else { + JSONArray array = new JSONArray(); + for (int i = 0; i < list.size(); i++) { + array.put(list.get(i)); + } + Log.e("TAG", "onClick: " + array.toString()); + spf.edit().putString("modulestyles", array.toString()).commit(); + if (isAirlink) { + // config_airlink-false-start + Intent intent = new Intent(GosModeListActivity2.this, GosAirlinkReadyActivity.class); + startActivity(intent); + // config_airlink-false-end + } else { + //config_softap-false-start + Intent intent = new Intent(GosModeListActivity2.this, GosDeviceReadyActivity.class); + startActivity(intent); + //config_softap-false-end + } + } + } + + } + }); + } + + private void initData() { + isAirlink = getIntent().getBooleanExtra("isAirlink", true); + String modules = spf.getString("modulestyles", null); + if (modules != null) { + try { + JSONArray array = new JSONArray(modules); + for (int i = 0; i < array.length(); i++) { + int type = (Integer) array.get(i); + list.add(type); + } + } catch(JSONException e) { + e.printStackTrace(); + } + } + modeList = new ArrayList(); + String[] modes = this.getResources().getStringArray(R.array.mode); + for (String string : modes) { + modeList.add(string); + } + modeListAdapter = new ModeListAdapter(this, modeList); + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.module_style, menu); + MenuItem menuItem = menu.findItem(R.id.module_help); + menuItem.setIcon(ToolUtils.editIcon(getResources(), R.drawable.config_help_button)); + return super.onCreateOptionsMenu(menu); + } + + class ModeListAdapter extends BaseAdapter { + + Context context; + List modeList; + + public ModeListAdapter(Context context, List modeList) { + super(); + this.context = context; + this.modeList = modeList; + } + + @Override + public int getCount() { + return modeList.size(); + } + + @Override + public Object getItem(int position) { + return null; + } + + @Override + public long getItemId(int position) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + if (null == convertView) { + convertView = View.inflate(context, R.layout.item_gos_mode_list, null); + } + + TextView tvModeText = (TextView) convertView.findViewById(R.id.tvModeText); + + String modeText = modeList.get(position); + tvModeText.setText(modeText); + + ImageView ivChoosed = (ImageView) convertView.findViewById(R.id.ivChoosed); + if (list.contains(position)) { + ivChoosed.setVisibility(View.VISIBLE); + } else { + ivChoosed.setVisibility(View.GONE); + } + + return convertView; + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); + break; + case R.id.module_help: + if (ToolUtils.noDoubleClick()) { + startActivity(new Intent(GosModeListActivity2.this, GosChooseModuleHelpActivity.class)); + } + break; + } + return true; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosWifiChangeReciver.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosWifiChangeReciver.java new file mode 100644 index 0000000..f78f158 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/GosWifiChangeReciver.java @@ -0,0 +1,36 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.utils.NetUtils; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.wifi.WifiManager; + + +public class GosWifiChangeReciver extends BroadcastReceiver { + + SharedPreferences spf; + + @Override + public void onReceive(Context context, Intent intent) { + + spf = context.getSharedPreferences(GosBaseActivity.SPF_Name, Context.MODE_PRIVATE); + + String wifiname = spf.getString("workSSID", ""); + String wifipass = spf.getString("workSSIDPsw", ""); + String connectWifiSsid = NetUtils.getConnectWifiSsid(context); + if (connectWifiSsid != null && connectWifiSsid.contains(GosBaseActivity.SoftAP_Start)) { + } else { + if (connectWifiSsid.contains(wifiname)) { + return; + } + WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); + WifiAutoConnectManager manager = new WifiAutoConnectManager(wifiManager); + manager.connect(wifiname, wifipass, WifiAutoConnectManager.getCipherType(context, wifiname)); + + } + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ConfigModule/WifiAutoConnectManager.java b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/WifiAutoConnectManager.java new file mode 100644 index 0000000..9ba59e7 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ConfigModule/WifiAutoConnectManager.java @@ -0,0 +1,231 @@ +package com.gizwits.opensource.appkit.ConfigModule; + +import android.content.Context; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiConfiguration.AuthAlgorithm; +import android.net.wifi.WifiConfiguration.KeyMgmt; +import android.net.wifi.WifiManager; +import android.text.TextUtils; +import android.util.Log; + +import java.util.List; + +public class WifiAutoConnectManager { + + private static final String TAG = WifiAutoConnectManager.class + .getSimpleName(); + + WifiManager wifiManager; + + // 定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况 + public enum WifiCipherType { + WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID + } + + // 构造函数 + public WifiAutoConnectManager(WifiManager wifiManager) { + this.wifiManager = wifiManager; + } + + // 提供一个外部接口,传入要连接的无线网 + public void connect(String ssid, String password, WifiCipherType type) { + Thread thread = new Thread(new ConnectRunnable(ssid, password, type)); + thread.start(); + } + + // 查看以前是否也配置过这个网络 + private WifiConfiguration isExsits(String SSID) { + List existingConfigs = wifiManager + .getConfiguredNetworks(); + if (existingConfigs != null) { + for (WifiConfiguration existingConfig : existingConfigs) { + if (existingConfig.SSID != null) { + if (existingConfig.SSID.equals("\"" + SSID + "\"")) { + return existingConfig; + } + } + } + } + return null; + } + + private WifiConfiguration createWifiInfo(String SSID, String Password, + WifiCipherType Type) { + WifiConfiguration config = new WifiConfiguration(); + config.allowedAuthAlgorithms.clear(); + config.allowedGroupCiphers.clear(); + config.allowedKeyManagement.clear(); + config.allowedPairwiseCiphers.clear(); + config.allowedProtocols.clear(); + config.SSID = "\"" + SSID + "\""; + // config.SSID = SSID; + // nopass + if (Type == WifiCipherType.WIFICIPHER_NOPASS) { + // config.wepKeys[0] = ""; + config.allowedKeyManagement.set(KeyMgmt.NONE); + // config.wepTxKeyIndex = 0; + } + // wep + if (Type == WifiCipherType.WIFICIPHER_WEP) { + if (!TextUtils.isEmpty(Password)) { + if (isHexWepKey(Password)) { + config.wepKeys[0] = Password; + } else { + config.wepKeys[0] = "\"" + Password + "\""; + } + } + config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); + config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); + config.allowedKeyManagement.set(KeyMgmt.NONE); + config.wepTxKeyIndex = 0; + } + // wpa + if (Type == WifiCipherType.WIFICIPHER_WPA) { + config.preSharedKey = "\"" + Password + "\""; + config.hiddenSSID = true; + config.allowedAuthAlgorithms + .set(AuthAlgorithm.OPEN); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); + config.allowedPairwiseCiphers + .set(WifiConfiguration.PairwiseCipher.TKIP); + // 此处需要修改否则不能自动重联 + // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + config.allowedPairwiseCiphers + .set(WifiConfiguration.PairwiseCipher.CCMP); + config.status = WifiConfiguration.Status.ENABLED; + + } + return config; + } + + // 打开wifi功能 + private boolean openWifi() { + boolean bRet = true; + if (!wifiManager.isWifiEnabled()) { + bRet = wifiManager.setWifiEnabled(true); + } + return bRet; + } + + // 关闭WIFI + private void closeWifi() { + if (wifiManager.isWifiEnabled()) { + wifiManager.setWifiEnabled(false); + } + } + + class ConnectRunnable implements Runnable { + private String ssid; + + private String password; + + private WifiCipherType type; + + public ConnectRunnable(String ssid, String password, WifiCipherType type) { + this.ssid = ssid; + this.password = password; + this.type = type; + } + + @Override + public void run() { + // 打开wifi + openWifi(); + // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi + // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句 + while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { + try { + // 为了避免程序一直while循环,让它睡个100毫秒检测…… + Thread.sleep(100); + + } catch (InterruptedException ie) { + Log.i(TAG, ie.toString()); + } + } + + WifiConfiguration tempConfig = isExsits(ssid); + + if (tempConfig != null) { + // wifiManager.removeNetwork(tempConfig.networkId); + + boolean b = wifiManager.enableNetwork(tempConfig.networkId, + true); + } else { + WifiConfiguration wifiConfig = createWifiInfo(ssid, password, + type); + // + if (wifiConfig == null) { + Log.d(TAG, "wifiConfig is null!"); + return; + } + + int netID = wifiManager.addNetwork(wifiConfig); + boolean enabled = wifiManager.enableNetwork(netID, true); + Log.d(TAG, "enableNetwork status enable=" + enabled); + boolean connected = wifiManager.reconnect(); + Log.d(TAG, "enableNetwork connected=" + connected); + } + + } + } + + private static boolean isHexWepKey(String wepKey) { + final int len = wepKey.length(); + + // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) + if (len != 10 && len != 26 && len != 58) { + return false; + } + + return isHex(wepKey); + } + + private static boolean isHex(String key) { + for (int i = key.length() - 1; i >= 0; i--) { + final char c = key.charAt(i); + if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' + && c <= 'f')) { + return false; + } + } + + return true; + } + + // 获取ssid的加密方式 + + public static WifiCipherType getCipherType(Context context, String ssid) { + WifiManager wifiManager = (WifiManager) context + .getSystemService(Context.WIFI_SERVICE); + + List list = wifiManager.getScanResults(); + + for (ScanResult scResult : list) { + + if (!TextUtils.isEmpty(scResult.SSID) && scResult.SSID.equals(ssid)) { + String capabilities = scResult.capabilities; + // Log.i("hefeng","capabilities=" + capabilities); + + if (!TextUtils.isEmpty(capabilities)) { + + if (capabilities.contains("WPA") + || capabilities.contains("wpa")) { + Log.i("hefeng", "wpa"); + return WifiCipherType.WIFICIPHER_WPA; + } else if (capabilities.contains("WEP") + || capabilities.contains("wep")) { + Log.i("hefeng", "wep"); + return WifiCipherType.WIFICIPHER_WEP; + } else { + Log.i("hefeng", "no"); + return WifiCipherType.WIFICIPHER_NOPASS; + } + } + } + } + return WifiCipherType.WIFICIPHER_INVALID; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ControlModule/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/ControlModule/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/ControlModule/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/ControlModule/GosControlModuleBaseActivity.java b/src/main/java/com/gizwits/opensource/appkit/ControlModule/GosControlModuleBaseActivity.java new file mode 100644 index 0000000..17f7dbf --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ControlModule/GosControlModuleBaseActivity.java @@ -0,0 +1,429 @@ +package com.gizwits.opensource.appkit.ControlModule; + +import java.text.DecimalFormat; +import java.util.concurrent.ConcurrentHashMap; + +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.utils.HexStrUtils; + +import android.util.Log; +import android.content.Context; +import android.view.MenuItem; +import android.view.inputmethod.InputMethodManager; +import android.widget.Toast; + +public class GosControlModuleBaseActivity extends GosBaseActivity { + + /* + * =========================================================== + * 以下key值对应开发者在云端定义的数据点标识名 + * =========================================================== + */ + // 数据点"心率检测"对应的标识名 + protected static final String KEY_HREAT = "hreat"; + // 数据点"心率上限"对应的标识名 + protected static final String KEY_HEARTUP = "heartup"; + // 数据点"心率下限"对应的标识名 + protected static final String KEY_HEARTDW = "heartdw"; + // 数据点"血氧检测"对应的标识名 + protected static final String KEY_SPO2 = "spo2"; + // 数据点"血氧上限"对应的标识名 + protected static final String KEY_SPO2UP = "spo2up"; + // 数据点"血氧下限"对应的标识名 + protected static final String KEY_SPO2DW = "spo2dw"; + // 数据点"体温上限"对应的标识名 + protected static final String KEY_TEMPUP = "tempup"; + // 数据点"体温下限"对应的标识名 + protected static final String KEY_TEMPDW = "tempdw"; + // 数据点"计步步数"对应的标识名 + protected static final String KEY_BUS = "bus"; + // 数据点"GPS纬度N"对应的标识名 + protected static final String KEY_GPS_N = "GPS_N"; + // 数据点"体温检测"对应的标识名 + protected static final String KEY_TEMP = "temp"; + // 数据点"GPS经度E"对应的标识名 + protected static final String KEY_GPS_E = "GPS_E"; + + /* + * =========================================================== + * 以下数值对应开发者在云端定义的可写数值型数据点增量值、数据点定义的分辨率、seekbar滚动条补偿值 + * _ADDITION:数据点增量值 + * _RATIO:数据点定义的分辨率 + * _OFFSET:seekbar滚动条补偿值 + * APP与设备定义的协议公式为:y(APP接收的值)=x(设备上报的值)* RATIO(分辨率)+ADDITION(增量值) + * 由于安卓的原生seekbar无法设置最小值,因此代码中增加了一个补偿量OFFSET + * 实际上公式中的:x(设备上报的值)=seekbar的值+补偿值 + * =========================================================== + */ + // 数据点"心率检测"对应seekbar滚动条补偿值 + protected static final int HREAT_OFFSET = 0; + // 数据点"心率检测"对应数据点增量值 + protected static final int HREAT_ADDITION = 0; + // 数据点"心率检测"对应数据点定义的分辨率 + protected static final int HREAT_RATIO = 1; + + // 数据点"心率上限"对应seekbar滚动条补偿值 + protected static final int HEARTUP_OFFSET = 0; + // 数据点"心率上限"对应数据点增量值 + protected static final int HEARTUP_ADDITION = 0; + // 数据点"心率上限"对应数据点定义的分辨率 + protected static final int HEARTUP_RATIO = 1; + + // 数据点"心率下限"对应seekbar滚动条补偿值 + protected static final int HEARTDW_OFFSET = 0; + // 数据点"心率下限"对应数据点增量值 + protected static final int HEARTDW_ADDITION = 0; + // 数据点"心率下限"对应数据点定义的分辨率 + protected static final int HEARTDW_RATIO = 1; + + // 数据点"血氧检测"对应seekbar滚动条补偿值 + protected static final int SPO2_OFFSET = 0; + // 数据点"血氧检测"对应数据点增量值 + protected static final int SPO2_ADDITION = 0; + // 数据点"血氧检测"对应数据点定义的分辨率 + protected static final int SPO2_RATIO = 1; + + // 数据点"血氧上限"对应seekbar滚动条补偿值 + protected static final int SPO2UP_OFFSET = 0; + // 数据点"血氧上限"对应数据点增量值 + protected static final int SPO2UP_ADDITION = 0; + // 数据点"血氧上限"对应数据点定义的分辨率 + protected static final int SPO2UP_RATIO = 1; + + // 数据点"血氧下限"对应seekbar滚动条补偿值 + protected static final int SPO2DW_OFFSET = 0; + // 数据点"血氧下限"对应数据点增量值 + protected static final int SPO2DW_ADDITION = 0; + // 数据点"血氧下限"对应数据点定义的分辨率 + protected static final int SPO2DW_RATIO = 1; + + // 数据点"体温上限"对应seekbar滚动条补偿值 + protected static final int TEMPUP_OFFSET = 0; + // 数据点"体温上限"对应数据点增量值 + protected static final int TEMPUP_ADDITION = 0; + // 数据点"体温上限"对应数据点定义的分辨率 + protected static final int TEMPUP_RATIO = 1; + + // 数据点"体温下限"对应seekbar滚动条补偿值 + protected static final int TEMPDW_OFFSET = 0; + // 数据点"体温下限"对应数据点增量值 + protected static final int TEMPDW_ADDITION = 0; + // 数据点"体温下限"对应数据点定义的分辨率 + protected static final int TEMPDW_RATIO = 1; + + // 数据点"计步步数"对应seekbar滚动条补偿值 + protected static final int BUS_OFFSET = 0; + // 数据点"计步步数"对应数据点增量值 + protected static final int BUS_ADDITION = 0; + // 数据点"计步步数"对应数据点定义的分辨率 + protected static final int BUS_RATIO = 1; + + // 数据点"GPS纬度N"对应seekbar滚动条补偿值 + protected static final int GPS_N_OFFSET = 0; + // 数据点"GPS纬度N"对应数据点增量值 + protected static final int GPS_N_ADDITION = 0; + // 数据点"GPS纬度N"对应数据点定义的分辨率 + protected static final double GPS_N_RATIO = 0.001; + + // 数据点"体温检测"对应seekbar滚动条补偿值 + protected static final int TEMP_OFFSET = 0; + // 数据点"体温检测"对应数据点增量值 + protected static final int TEMP_ADDITION = 0; + // 数据点"体温检测"对应数据点定义的分辨率 + protected static final double TEMP_RATIO = 0.1; + + // 数据点"GPS经度E"对应seekbar滚动条补偿值 + protected static final int GPS_E_OFFSET = 0; + // 数据点"GPS经度E"对应数据点增量值 + protected static final int GPS_E_ADDITION = 50; + // 数据点"GPS经度E"对应数据点定义的分辨率 + protected static final double GPS_E_RATIO = 0.001; + + + /* + * =========================================================== + * 以下变量对应设备上报类型为布尔、数值、扩展数据点的数据存储 + * =========================================================== + */ + // 数据点"心率检测"对应的存储数据 + protected static int data_hreat; + // 数据点"心率上限"对应的存储数据 + protected static int data_heartup; + // 数据点"心率下限"对应的存储数据 + protected static int data_heartdw; + // 数据点"血氧检测"对应的存储数据 + protected static int data_spo2; + // 数据点"血氧上限"对应的存储数据 + protected static int data_spo2up; + // 数据点"血氧下限"对应的存储数据 + protected static int data_spo2dw; + // 数据点"体温上限"对应的存储数据 + protected static int data_tempup; + // 数据点"体温下限"对应的存储数据 + protected static int data_tempdw; + // 数据点"计步步数"对应的存储数据 + protected static int data_bus; + // 数据点"GPS纬度N"对应的存储数据 + protected static double data_GPS_N; + // 数据点"体温检测"对应的存储数据 + protected static double data_temp; + // 数据点"GPS经度E"对应的存储数据 + protected static double data_GPS_E; + + /* + * =========================================================== + * 以下key值对应设备硬件信息各明细的名称,用与回调中提取硬件信息字段。 + * =========================================================== + */ + protected static final String WIFI_HARDVER_KEY = "wifiHardVersion"; + protected static final String WIFI_SOFTVER_KEY = "wifiSoftVersion"; + protected static final String MCU_HARDVER_KEY = "mcuHardVersion"; + protected static final String MCU_SOFTVER_KEY = "mcuSoftVersion"; + protected static final String WIFI_FIRMWAREID_KEY = "wifiFirmwareId"; + protected static final String WIFI_FIRMWAREVER_KEY = "wifiFirmwareVer"; + protected static final String PRODUCT_KEY = "productKey"; + + private Toast mToast; + + @SuppressWarnings("unchecked") + protected void getDataFromReceiveDataMap(ConcurrentHashMap dataMap) { + // 已定义的设备数据点,有布尔、数值和枚举型数据 + + if (dataMap.get("data") != null) { + ConcurrentHashMap map = (ConcurrentHashMap) dataMap.get("data"); + for (String dataKey : map.keySet()) { + if (dataKey.equals(KEY_HREAT)) { + + data_hreat = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_HEARTUP)) { + + data_heartup = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_HEARTDW)) { + + data_heartdw = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_SPO2)) { + + data_spo2 = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_SPO2UP)) { + + data_spo2up = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_SPO2DW)) { + + data_spo2dw = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_TEMPUP)) { + + data_tempup = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_TEMPDW)) { + + data_tempdw = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_BUS)) { + + data_bus = (Integer) map.get(dataKey); + } + if (dataKey.equals(KEY_GPS_N)) { + + if (map.get(dataKey) instanceof Integer) { + data_GPS_N = (Integer) map.get(dataKey); + } else { + data_GPS_N = (Double) map.get(dataKey); + } + } + if (dataKey.equals(KEY_TEMP)) { + + if (map.get(dataKey) instanceof Integer) { + data_temp = (Integer) map.get(dataKey); + } else { + data_temp = (Double) map.get(dataKey); + } + } + if (dataKey.equals(KEY_GPS_E)) { + + if (map.get(dataKey) instanceof Integer) { + data_GPS_E = (Integer) map.get(dataKey); + } else { + data_GPS_E = (Double) map.get(dataKey); + } + } + } + } + + StringBuilder sBuilder = new StringBuilder(); + + // 已定义的设备报警数据点,设备发生报警后该字段有内容,没有发生报警则没内容 + if (dataMap.get("alerts") != null) { + ConcurrentHashMap map = (ConcurrentHashMap) dataMap.get("alerts"); + for (String alertsKey : map.keySet()) { + if ((Boolean) map.get(alertsKey)) { + sBuilder.append("报警:" + alertsKey + "=true" + "\n"); + } + } + } + + // 已定义的设备故障数据点,设备发生故障后该字段有内容,没有发生故障则没内容 + if (dataMap.get("faults") != null) { + ConcurrentHashMap map = (ConcurrentHashMap) dataMap.get("faults"); + for (String faultsKey : map.keySet()) { + if ((Boolean) map.get(faultsKey)) { + sBuilder.append("故障:" + faultsKey + "=true" + "\n"); + } + } + } + + if (sBuilder.length() > 0) { + sBuilder.insert(0, "[设备故障或报警]\n"); + myToast(sBuilder.toString().trim()); + } + + // 透传数据,无数据点定义,适合开发者自行定义协议自行解析 + if (dataMap.get("binary") != null) { + byte[] binary = (byte[]) dataMap.get("binary"); + Log.i("", "Binary data:" + HexStrUtils.bytesToHexString(binary)); + } + } + + GizWifiDeviceListener gizWifiDeviceListener = new GizWifiDeviceListener() { + + /** 用于设备订阅 */ + public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + GosControlModuleBaseActivity.this.didSetSubscribe(result, device, isSubscribed); + }; + + /** 用于获取设备状态 */ + public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, + java.util.concurrent.ConcurrentHashMap dataMap, int sn) { + GosControlModuleBaseActivity.this.didReceiveData(result, device, dataMap, sn); + }; + + /** 用于设备硬件信息 */ + public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, + java.util.concurrent.ConcurrentHashMap hardwareInfo) { + GosControlModuleBaseActivity.this.didGetHardwareInfo(result, device, hardwareInfo); + }; + + /** 用于修改设备信息 */ + public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) { + GosControlModuleBaseActivity.this.didSetCustomInfo(result, device); + }; + + /** 用于设备状态变化 */ + public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + GosControlModuleBaseActivity.this.didUpdateNetStatus(device, netStatus); + }; + + }; + + /** + * 设备订阅回调 + * + * @param result + * 错误码 + * @param device + * 被订阅设备 + * @param isSubscribed + * 订阅状态 + */ + protected void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + } + + /** + * 设备状态回调 + * + * @param result + * 错误码 + * @param device + * 当前设备 + * @param dataMap + * 当前设备状态 + * @param sn + * 命令序号 + */ + protected void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, + java.util.concurrent.ConcurrentHashMap dataMap, int sn) { + } + + /** + * 设备硬件信息回调 + * + * @param result + * 错误码 + * @param device + * 当前设备 + * @param hardwareInfo + * 当前设备硬件信息 + */ + protected void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, + java.util.concurrent.ConcurrentHashMap hardwareInfo) { + } + + /** + * 修改设备信息回调 + * + * @param result + * 错误码 + * @param device + * 当前设备 + */ + protected void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) { + } + + /** + * 设备状态变化回调 + */ + protected void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return super.onOptionsItemSelected(item); + } + + public void myToast(String string) { + if (mToast != null) { + mToast.setText(string); + } else { + mToast = Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG); + } + mToast.show(); + } + + protected void hideKeyBoard() { + // 隐藏键盘 + InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null) { + imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0); + } + } + + + /** + *Description:显示格式化数值,保留对应分辨率的小数个数,比如传入参数(20.3656,0.01),将返回20.37 + *@param date 传入的数值 + *@param scale 保留多少位小数 + *@return + */ + protected String formatValue(double date, Object scale) { + if (scale instanceof Double) { + DecimalFormat df = new DecimalFormat(scale.toString()); + return df.format(date); + } + return Math.round(date) + ""; + } + +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/ControlModule/GosDeviceControlActivity.java b/src/main/java/com/gizwits/opensource/appkit/ControlModule/GosDeviceControlActivity.java new file mode 100644 index 0000000..eab6491 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ControlModule/GosDeviceControlActivity.java @@ -0,0 +1,603 @@ +package com.gizwits.opensource.appkit.ControlModule; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.DialogInterface; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.graphics.PorterDuff; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.text.TextUtils; +import android.util.Log; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.view.View.OnClickListener; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemSelectedListener; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.SeekBar; +import android.widget.SeekBar.OnSeekBarChangeListener; +import android.widget.Spinner; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; +import android.widget.Toast; + +import java.util.concurrent.ConcurrentHashMap; + +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.HexStrUtils; +import com.gizwits.opensource.appkit.view.HexWatcher; + +public class GosDeviceControlActivity extends GosControlModuleBaseActivity + implements OnClickListener, OnEditorActionListener, OnSeekBarChangeListener { + + /** 设备列表传入的设备变量 */ + private GizWifiDevice mDevice; + + private TextView tv_data_hreat; + private SeekBar sb_data_hreat; + private TextView tv_data_heartup; + private SeekBar sb_data_heartup; + private TextView tv_data_heartdw; + private SeekBar sb_data_heartdw; + private TextView tv_data_spo2; + private SeekBar sb_data_spo2; + private TextView tv_data_spo2up; + private SeekBar sb_data_spo2up; + private TextView tv_data_spo2dw; + private SeekBar sb_data_spo2dw; + private TextView tv_data_tempup; + private SeekBar sb_data_tempup; + private TextView tv_data_tempdw; + private SeekBar sb_data_tempdw; + private TextView tv_data_bus; + private SeekBar sb_data_bus; + private TextView tv_data_GPS_N; + private SeekBar sb_data_GPS_N; + private TextView tv_data_temp; + private SeekBar sb_data_temp; + private TextView tv_data_GPS_E; + private SeekBar sb_data_GPS_E; + + private enum handler_key { + + /** 更新界面 */ + UPDATE_UI, + + DISCONNECT, + } + + private Runnable mRunnable = new Runnable() { + public void run() { + if (isDeviceCanBeControlled()) { + progressDialog.cancel(); + } else { + toastDeviceNoReadyAndExit(); + } + } + + }; + + /** The handler. */ + Handler mHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + case UPDATE_UI: + updateUI(); + break; + case DISCONNECT: + toastDeviceDisconnectAndExit(); + break; + } + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_device_control); + initDevice(); + setToolBar(true, getDeviceName()); + final Drawable add = getResources().getDrawable(R.drawable.common_setting_more); + int color = GosDeploy.appConfig_Contrast(); + add.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); + mToolbar.setOverflowIcon(add); + initView(); + initEvent(); + } + + private void initView() { + + tv_data_hreat = (TextView) findViewById(R.id.tv_data_hreat); + sb_data_hreat = (SeekBar) findViewById(R.id.sb_data_hreat); + tv_data_heartup = (TextView) findViewById(R.id.tv_data_heartup); + sb_data_heartup = (SeekBar) findViewById(R.id.sb_data_heartup); + tv_data_heartdw = (TextView) findViewById(R.id.tv_data_heartdw); + sb_data_heartdw = (SeekBar) findViewById(R.id.sb_data_heartdw); + tv_data_spo2 = (TextView) findViewById(R.id.tv_data_spo2); + sb_data_spo2 = (SeekBar) findViewById(R.id.sb_data_spo2); + tv_data_spo2up = (TextView) findViewById(R.id.tv_data_spo2up); + sb_data_spo2up = (SeekBar) findViewById(R.id.sb_data_spo2up); + tv_data_spo2dw = (TextView) findViewById(R.id.tv_data_spo2dw); + sb_data_spo2dw = (SeekBar) findViewById(R.id.sb_data_spo2dw); + tv_data_tempup = (TextView) findViewById(R.id.tv_data_tempup); + sb_data_tempup = (SeekBar) findViewById(R.id.sb_data_tempup); + tv_data_tempdw = (TextView) findViewById(R.id.tv_data_tempdw); + sb_data_tempdw = (SeekBar) findViewById(R.id.sb_data_tempdw); + tv_data_bus = (TextView) findViewById(R.id.tv_data_bus); + sb_data_bus = (SeekBar) findViewById(R.id.sb_data_bus); + tv_data_GPS_N = (TextView) findViewById(R.id.tv_data_GPS_N); + sb_data_GPS_N = (SeekBar) findViewById(R.id.sb_data_GPS_N); + tv_data_temp = (TextView) findViewById(R.id.tv_data_temp); + sb_data_temp = (SeekBar) findViewById(R.id.sb_data_temp); + tv_data_GPS_E = (TextView) findViewById(R.id.tv_data_GPS_E); + sb_data_GPS_E = (SeekBar) findViewById(R.id.sb_data_GPS_E); + } + + private void initEvent() { + + sb_data_hreat.setOnSeekBarChangeListener(this); + sb_data_heartup.setOnSeekBarChangeListener(this); + sb_data_heartdw.setOnSeekBarChangeListener(this); + sb_data_spo2.setOnSeekBarChangeListener(this); + sb_data_spo2up.setOnSeekBarChangeListener(this); + sb_data_spo2dw.setOnSeekBarChangeListener(this); + sb_data_tempup.setOnSeekBarChangeListener(this); + sb_data_tempdw.setOnSeekBarChangeListener(this); + sb_data_bus.setOnSeekBarChangeListener(this); + sb_data_GPS_N.setOnSeekBarChangeListener(this); + sb_data_temp.setOnSeekBarChangeListener(this); + sb_data_GPS_E.setOnSeekBarChangeListener(this); + + } + + private void initDevice() { + Intent intent = getIntent(); + mDevice = (GizWifiDevice) intent.getParcelableExtra("GizWifiDevice"); + mDevice.setListener(gizWifiDeviceListener); + Log.i("Apptest", mDevice.getDid()); + } + + private String getDeviceName() { + if (TextUtils.isEmpty(mDevice.getAlias())) { + return mDevice.getProductName(); + } + return mDevice.getAlias(); + } + + @Override + protected void onResume() { + super.onResume(); + getStatusOfDevice(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + mHandler.removeCallbacks(mRunnable); + // 退出页面,取消设备订阅 + mDevice.setSubscribe(false); + mDevice.setListener(null); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + default: + break; + } + } + + /* + * ======================================================================== + * EditText 点击键盘“完成”按钮方法 + * ======================================================================== + */ + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + + switch (v.getId()) { + default: + break; + } + hideKeyBoard(); + return false; + + } + + /* + * ======================================================================== + * seekbar 回调方法重写 + * ======================================================================== + */ + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + + switch (seekBar.getId()) { + case R.id.sb_data_hreat: + tv_data_hreat.setText(formatValue((progress + HREAT_OFFSET) * HREAT_RATIO + HREAT_ADDITION, 1)); + break; + case R.id.sb_data_heartup: + tv_data_heartup.setText(formatValue((progress + HEARTUP_OFFSET) * HEARTUP_RATIO + HEARTUP_ADDITION, 1)); + break; + case R.id.sb_data_heartdw: + tv_data_heartdw.setText(formatValue((progress + HEARTDW_OFFSET) * HEARTDW_RATIO + HEARTDW_ADDITION, 1)); + break; + case R.id.sb_data_spo2: + tv_data_spo2.setText(formatValue((progress + SPO2_OFFSET) * SPO2_RATIO + SPO2_ADDITION, 1)); + break; + case R.id.sb_data_spo2up: + tv_data_spo2up.setText(formatValue((progress + SPO2UP_OFFSET) * SPO2UP_RATIO + SPO2UP_ADDITION, 1)); + break; + case R.id.sb_data_spo2dw: + tv_data_spo2dw.setText(formatValue((progress + SPO2DW_OFFSET) * SPO2DW_RATIO + SPO2DW_ADDITION, 1)); + break; + case R.id.sb_data_tempup: + tv_data_tempup.setText(formatValue((progress + TEMPUP_OFFSET) * TEMPUP_RATIO + TEMPUP_ADDITION, 1)); + break; + case R.id.sb_data_tempdw: + tv_data_tempdw.setText(formatValue((progress + TEMPDW_OFFSET) * TEMPDW_RATIO + TEMPDW_ADDITION, 1)); + break; + case R.id.sb_data_bus: + tv_data_bus.setText(formatValue((progress + BUS_OFFSET) * BUS_RATIO + BUS_ADDITION, 1)); + break; + case R.id.sb_data_GPS_N: + tv_data_GPS_N.setText(formatValue((progress + GPS_N_OFFSET) * GPS_N_RATIO + GPS_N_ADDITION, 0.001)); + break; + case R.id.sb_data_temp: + tv_data_temp.setText(formatValue((progress + TEMP_OFFSET) * TEMP_RATIO + TEMP_ADDITION, 0.1)); + break; + case R.id.sb_data_GPS_E: + tv_data_GPS_E.setText(formatValue((progress + GPS_E_OFFSET) * GPS_E_RATIO + GPS_E_ADDITION, 0.001)); + break; + default: + break; + } + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + switch (seekBar.getId()) { + case R.id.sb_data_hreat: + sendCommand(KEY_HREAT, (seekBar.getProgress() + HREAT_OFFSET ) * HREAT_RATIO + HREAT_ADDITION); + break; + case R.id.sb_data_heartup: + sendCommand(KEY_HEARTUP, (seekBar.getProgress() + HEARTUP_OFFSET ) * HEARTUP_RATIO + HEARTUP_ADDITION); + break; + case R.id.sb_data_heartdw: + sendCommand(KEY_HEARTDW, (seekBar.getProgress() + HEARTDW_OFFSET ) * HEARTDW_RATIO + HEARTDW_ADDITION); + break; + case R.id.sb_data_spo2: + sendCommand(KEY_SPO2, (seekBar.getProgress() + SPO2_OFFSET ) * SPO2_RATIO + SPO2_ADDITION); + break; + case R.id.sb_data_spo2up: + sendCommand(KEY_SPO2UP, (seekBar.getProgress() + SPO2UP_OFFSET ) * SPO2UP_RATIO + SPO2UP_ADDITION); + break; + case R.id.sb_data_spo2dw: + sendCommand(KEY_SPO2DW, (seekBar.getProgress() + SPO2DW_OFFSET ) * SPO2DW_RATIO + SPO2DW_ADDITION); + break; + case R.id.sb_data_tempup: + sendCommand(KEY_TEMPUP, (seekBar.getProgress() + TEMPUP_OFFSET ) * TEMPUP_RATIO + TEMPUP_ADDITION); + break; + case R.id.sb_data_tempdw: + sendCommand(KEY_TEMPDW, (seekBar.getProgress() + TEMPDW_OFFSET ) * TEMPDW_RATIO + TEMPDW_ADDITION); + break; + case R.id.sb_data_bus: + sendCommand(KEY_BUS, (seekBar.getProgress() + BUS_OFFSET ) * BUS_RATIO + BUS_ADDITION); + break; + case R.id.sb_data_GPS_N: + sendCommand(KEY_GPS_N, (seekBar.getProgress() + GPS_N_OFFSET ) * GPS_N_RATIO + GPS_N_ADDITION); + break; + case R.id.sb_data_temp: + sendCommand(KEY_TEMP, (seekBar.getProgress() + TEMP_OFFSET ) * TEMP_RATIO + TEMP_ADDITION); + break; + case R.id.sb_data_GPS_E: + sendCommand(KEY_GPS_E, (seekBar.getProgress() + GPS_E_OFFSET ) * GPS_E_RATIO + GPS_E_ADDITION); + break; + default: + break; + } + } + + /* + * ======================================================================== + * 菜单栏 + * ======================================================================== + */ + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.device_more, menu); + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + + case R.id.action_setDeviceInfo: + setDeviceInfo(); + break; + + case R.id.action_getHardwareInfo: + if (mDevice.isLAN()) { + mDevice.getHardwareInfo(); + } else { + myToast("只允许在局域网下获取设备硬件信息!"); + } + break; + + case R.id.action_getStatu: + mDevice.getDeviceStatus(); + break; + + default: + break; + } + + return super.onOptionsItemSelected(item); + } + + /** + * Description:根据保存的的数据点的值来更新UI + */ + protected void updateUI() { + + tv_data_hreat.setText(data_hreat+""); + sb_data_hreat.setProgress((int)((data_hreat - HREAT_ADDITION) / HREAT_RATIO - HREAT_OFFSET)); + tv_data_heartup.setText(data_heartup+""); + sb_data_heartup.setProgress((int)((data_heartup - HEARTUP_ADDITION) / HEARTUP_RATIO - HEARTUP_OFFSET)); + tv_data_heartdw.setText(data_heartdw+""); + sb_data_heartdw.setProgress((int)((data_heartdw - HEARTDW_ADDITION) / HEARTDW_RATIO - HEARTDW_OFFSET)); + tv_data_spo2.setText(data_spo2+""); + sb_data_spo2.setProgress((int)((data_spo2 - SPO2_ADDITION) / SPO2_RATIO - SPO2_OFFSET)); + tv_data_spo2up.setText(data_spo2up+""); + sb_data_spo2up.setProgress((int)((data_spo2up - SPO2UP_ADDITION) / SPO2UP_RATIO - SPO2UP_OFFSET)); + tv_data_spo2dw.setText(data_spo2dw+""); + sb_data_spo2dw.setProgress((int)((data_spo2dw - SPO2DW_ADDITION) / SPO2DW_RATIO - SPO2DW_OFFSET)); + tv_data_tempup.setText(data_tempup+""); + sb_data_tempup.setProgress((int)((data_tempup - TEMPUP_ADDITION) / TEMPUP_RATIO - TEMPUP_OFFSET)); + tv_data_tempdw.setText(data_tempdw+""); + sb_data_tempdw.setProgress((int)((data_tempdw - TEMPDW_ADDITION) / TEMPDW_RATIO - TEMPDW_OFFSET)); + tv_data_bus.setText(data_bus+""); + sb_data_bus.setProgress((int)((data_bus - BUS_ADDITION) / BUS_RATIO - BUS_OFFSET)); + tv_data_GPS_N.setText(data_GPS_N+""); + sb_data_GPS_N.setProgress((int)((data_GPS_N - GPS_N_ADDITION) / GPS_N_RATIO - GPS_N_OFFSET)); + tv_data_temp.setText(data_temp+""); + sb_data_temp.setProgress((int)((data_temp - TEMP_ADDITION) / TEMP_RATIO - TEMP_OFFSET)); + tv_data_GPS_E.setText(data_GPS_E+""); + sb_data_GPS_E.setProgress((int)((data_GPS_E - GPS_E_ADDITION) / GPS_E_RATIO - GPS_E_OFFSET)); + + } + + private void setEditText(EditText et, Object value) { + et.setText(value.toString()); + et.setSelection(value.toString().length()); + et.clearFocus(); + } + + /** + * Description:页面加载后弹出等待框,等待设备可被控制状态回调,如果一直不可被控,等待一段时间后自动退出界面 + */ + private void getStatusOfDevice() { + // 设备是否可控 + if (isDeviceCanBeControlled()) { + // 可控则查询当前设备状态 + mDevice.getDeviceStatus(); + } else { + // 显示等待栏 + progressDialog.show(); + if (mDevice.isLAN()) { + // 小循环10s未连接上设备自动退出 + mHandler.postDelayed(mRunnable, 10000); + } else { + // 大循环20s未连接上设备自动退出 + mHandler.postDelayed(mRunnable, 20000); + } + } + } + + /** + * 发送指令,下发单个数据点的命令可以用这个方法 + * + *

注意

+ *

+ * 下发多个数据点命令不能用这个方法多次调用,一次性多次调用这个方法会导致模组无法正确接收消息,参考方法内注释。 + *

+ * + * @param key + * 数据点对应的标识名 + * @param value + * 需要改变的值 + */ + private void sendCommand(String key, Object value) { + if (value == null) { + return; + } + int sn = 5; + ConcurrentHashMap hashMap = new ConcurrentHashMap(); + hashMap.put(key, value); + // 同时下发多个数据点需要一次性在map中放置全部需要控制的key,value值 + // hashMap.put(key2, value2); + // hashMap.put(key3, value3); + mDevice.write(hashMap, sn); + Log.i("liang", "下发命令:" + hashMap.toString()); + } + + private boolean isDeviceCanBeControlled() { + return mDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled; + } + + private void toastDeviceNoReadyAndExit() { + Toast.makeText(this, "设备无响应,请检查设备是否正常工作", Toast.LENGTH_SHORT).show(); + finish(); + } + + private void toastDeviceDisconnectAndExit() { + Toast.makeText(GosDeviceControlActivity.this, "连接已断开", Toast.LENGTH_SHORT).show(); + finish(); + } + + /** + * 展示设备硬件信息 + * + * @param hardwareInfo + */ + private void showHardwareInfo(String hardwareInfo) { + String hardwareInfoTitle = "设备硬件信息"; + new AlertDialog.Builder(this).setTitle(hardwareInfoTitle).setMessage(hardwareInfo) + .setPositiveButton(R.string.besure, null).show(); + } + + /** + * Description:设置设备别名与备注 + */ + private void setDeviceInfo() { + + final Dialog mDialog = new AlertDialog.Builder(this,R.style.edit_dialog_style).setView(new EditText(this)).create(); + mDialog.show(); + + Window window = mDialog.getWindow(); + window.setContentView(R.layout.alert_gos_set_device_info); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + final EditText etAlias; + final EditText etRemark; + etAlias = (EditText) window.findViewById(R.id.etAlias); + etRemark = (EditText) window.findViewById(R.id.etRemark); + + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + if (!TextUtils.isEmpty(mDevice.getAlias())) { + setEditText(etAlias, mDevice.getAlias()); + } + if (!TextUtils.isEmpty(mDevice.getRemark())) { + setEditText(etRemark, mDevice.getRemark()); + } + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + mDialog.dismiss(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + if (TextUtils.isEmpty(etRemark.getText().toString()) + && TextUtils.isEmpty(etAlias.getText().toString())) { + myToast("请输入设备别名或备注!"); + return; + } + mDevice.setCustomInfo(etRemark.getText().toString(), etAlias.getText().toString()); + mDialog.dismiss(); + String loadingText = (String) getText(R.string.loadingtext); + progressDialog.setMessage(loadingText); + progressDialog.show(); + } + }); + + mDialog.setOnDismissListener(new OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialog) { + hideKeyBoard(); + } + }); + } + + /* + * 获取设备硬件信息回调 + */ + @Override + protected void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, + ConcurrentHashMap hardwareInfo) { + super.didGetHardwareInfo(result, device, hardwareInfo); + StringBuffer sb = new StringBuffer(); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + myToast("获取设备硬件信息失败:" + result.name()); + } else { + sb.append("Wifi Hardware Version:" + hardwareInfo.get(WIFI_HARDVER_KEY) + "\r\n"); + sb.append("Wifi Software Version:" + hardwareInfo.get(WIFI_SOFTVER_KEY) + "\r\n"); + sb.append("MCU Hardware Version:" + hardwareInfo.get(MCU_HARDVER_KEY) + "\r\n"); + sb.append("MCU Software Version:" + hardwareInfo.get(MCU_SOFTVER_KEY) + "\r\n"); + sb.append("Wifi Firmware Id:" + hardwareInfo.get(WIFI_FIRMWAREID_KEY) + "\r\n"); + sb.append("Wifi Firmware Version:" + hardwareInfo.get(WIFI_FIRMWAREVER_KEY) + "\r\n"); + sb.append("Product Key:" + "\r\n" + hardwareInfo.get(PRODUCT_KEY) + "\r\n"); + + // 设备属性 + sb.append("Device ID:" + "\r\n" + mDevice.getDid() + "\r\n"); + sb.append("Device IP:" + mDevice.getIPAddress() + "\r\n"); + sb.append("Device MAC:" + mDevice.getMacAddress() + "\r\n"); + } + showHardwareInfo(sb.toString()); + } + + /* + * 设置设备别名和备注回调 + */ + @Override + protected void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) { + super.didSetCustomInfo(result, device); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) { + myToast("设置成功"); + progressDialog.cancel(); + finish(); + } else { + myToast("设置失败:" + result.name()); + } + } + + /* + * 设备状态改变回调,只有设备状态为可控才可以下发控制命令 + */ + @Override + protected void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + super.didUpdateNetStatus(device, netStatus); + if (netStatus == GizWifiDeviceNetStatus.GizDeviceControlled) { + mHandler.removeCallbacks(mRunnable); + progressDialog.cancel(); + } else { + mHandler.sendEmptyMessage(handler_key.DISCONNECT.ordinal()); + } + } + + /* + * 设备上报数据回调,此回调包括设备主动上报数据、下发控制命令成功后设备返回ACK + */ + @Override + protected void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, + ConcurrentHashMap dataMap, int sn) { + super.didReceiveData(result, device, dataMap, sn); + Log.i("liang", "接收到数据"); + if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS && dataMap.get("data") != null) { + getDataFromReceiveDataMap(dataMap); + mHandler.sendEmptyMessage(handler_key.UPDATE_UI.ordinal()); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosBaseFragment.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosBaseFragment.java new file mode 100644 index 0000000..3cd8df7 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosBaseFragment.java @@ -0,0 +1,735 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.support.v4.app.Fragment; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; + +/** + * author: smile . + * date: On 2018/6/7 + */ +public class GosBaseFragment extends Fragment { + /** + * 存储器 + */ + public SharedPreferences spf; + + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + spf = getActivity().getSharedPreferences("set", Context.MODE_PRIVATE); + } + public String toastError(GizWifiErrorCode errorCode) { + String errorString = (String) getText(R.string.UNKNOWN_ERROR); + switch (errorCode) { + case GIZ_SDK_SUCCESS: + errorString=(String)getText(R.string.GIZ_SDK_SUCCESS); + break; + case GIZ_SDK_PARAM_FORM_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PARAM_FORM_INVALID); + break; + case GIZ_SDK_CLIENT_NOT_AUTHEN: + errorString = (String) getText(R.string.GIZ_SDK_CLIENT_NOT_AUTHEN); + break; + case GIZ_SDK_CLIENT_VERSION_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_CLIENT_VERSION_INVALID); + break; + case GIZ_SDK_UDP_PORT_BIND_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_UDP_PORT_BIND_FAILED); + break; + case GIZ_SDK_DAEMON_EXCEPTION: + errorString = (String) getText(R.string.GIZ_SDK_DAEMON_EXCEPTION); + break; + case GIZ_SDK_PARAM_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PARAM_INVALID); + break; + case GIZ_SDK_APPID_LENGTH_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_APPID_LENGTH_ERROR); + break; + case GIZ_SDK_LOG_PATH_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_LOG_PATH_INVALID); + break; + case GIZ_SDK_LOG_LEVEL_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_LOG_LEVEL_INVALID); + break; + case GIZ_SDK_UID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_UID_INVALID); + break; + case GIZ_SDK_TOKEN_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_TOKEN_INVALID); + break; + case GIZ_SDK_USER_NOT_LOGIN: + errorString = (String) getText(R.string.GIZ_SDK_USER_NOT_LOGIN); + break; + case GIZ_SDK_APPID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_APPID_INVALID); + break; + case GIZ_SDK_APP_SECRET_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_APP_SECRET_INVALID); + break; + case GIZ_SDK_PRODUCT_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCT_KEY_INVALID); + break; + case GIZ_SDK_PRODUCT_SECRET_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCT_SECRET_INVALID); + break; + case GIZ_SDK_DEVICE_NOT_IN_LAN: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_IN_LAN); + break; + case GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIAL_LIST: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCTKEY_NOT_IN_SPECIAL_LIST); + break; + case GIZ_SDK_PRODUCTKEY_NOT_RELATED_WITH_APPID: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCTKEY_NOT_RELATED_WITH_APPID); + break; + case GIZ_SDK_NO_AVAILABLE_DEVICE: + errorString = (String) getText(R.string.GIZ_SDK_NO_AVAILABLE_DEVICE); + break; + case GIZ_SDK_DEVICE_CONFIG_SEND_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SEND_FAILED); + break; + case GIZ_SDK_DEVICE_CONFIG_IS_RUNNING: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING); + break; + case GIZ_SDK_DEVICE_CONFIG_TIMEOUT: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_TIMEOUT); + break; + case GIZ_SDK_DEVICE_DID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_DID_INVALID); + break; + case GIZ_SDK_DEVICE_MAC_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_MAC_INVALID); + break; + case GIZ_SDK_SUBDEVICE_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_SUBDEVICE_INVALID); + break; + case GIZ_SDK_DEVICE_PASSCODE_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_PASSCODE_INVALID); + break; + case GIZ_SDK_DEVICE_NOT_CENTERCONTROL: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_CENTERCONTROL); + break; + case GIZ_SDK_DEVICE_NOT_SUBSCRIBED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_SUBSCRIBED); + break; + case GIZ_SDK_DEVICE_NO_RESPONSE: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NO_RESPONSE); + break; + case GIZ_SDK_DEVICE_NOT_READY: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_READY); + break; + case GIZ_SDK_DEVICE_NOT_BINDED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_BINDED); + break; + case GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND); + break; +// case GIZ_SDK_DEVICE_CONTROL_FAILED: +// errorString= (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_FAILED); +// break; + case GIZ_SDK_DEVICE_GET_STATUS_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_GET_STATUS_FAILED); + break; + case GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR); + break; + case GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE); + break; + case GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND); + break; + case GIZ_SDK_BIND_DEVICE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_BIND_DEVICE_FAILED); + break; + case GIZ_SDK_UNBIND_DEVICE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_UNBIND_DEVICE_FAILED); + break; + case GIZ_SDK_DNS_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DNS_FAILED); + break; + case GIZ_SDK_M2M_CONNECTION_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_M2M_CONNECTION_SUCCESS); + break; + case GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED); + break; + case GIZ_SDK_CONNECTION_TIMEOUT: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_TIMEOUT); + break; + case GIZ_SDK_CONNECTION_REFUSED: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_REFUSED); + break; + case GIZ_SDK_CONNECTION_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_ERROR); + break; + case GIZ_SDK_CONNECTION_CLOSED: + errorString = (String) getText(R.string.GIZ_SDK_CONNECTION_CLOSED); + break; + case GIZ_SDK_SSL_HANDSHAKE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SSL_HANDSHAKE_FAILED); + break; + case GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED); + break; + case GIZ_SDK_INTERNET_NOT_REACHABLE: + errorString = (String) getText(R.string.GIZ_SDK_INTERNET_NOT_REACHABLE); + break; + case GIZ_SDK_M2M_CONNECTION_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_M2M_CONNECTION_FAILED); + break; + case GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API); + break; + case GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR); + break; + case GIZ_SDK_HTTP_ANSWER_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_PARAM_ERROR); + break; + case GIZ_SDK_HTTP_SERVER_NO_ANSWER: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NO_ANSWER); + break; + case GIZ_SDK_HTTP_REQUEST_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_HTTP_REQUEST_FAILED); + break; + case GIZ_SDK_OTHERWISE: + errorString = (String) getText(R.string.GIZ_SDK_OTHERWISE); + break; + case GIZ_SDK_MEMORY_MALLOC_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_MEMORY_MALLOC_FAILED); + break; + case GIZ_SDK_THREAD_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_THREAD_CREATE_FAILED); + break; + case GIZ_SDK_JSON_OBJECT_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_JSON_OBJECT_CREATE_FAILED); + break; + case GIZ_SDK_JSON_PARSE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_JSON_PARSE_FAILED); + break; + case GIZ_SDK_SCHEDULER_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_CREATE_FAILED); + break; + case GIZ_SDK_SCHEDULER_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_DELETE_FAILED); + break; + case GIZ_SDK_SCHEDULER_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_EDIT_FAILED); + break; + case GIZ_SDK_SCHEDULER_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCHEDULER_TASK_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_TASK_EDIT_FAILED); + break; + case GIZ_SDK_SCHEDULER_TASK_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_TASK_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCHEDULER_ID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_ID_INVALID); + break; + case GIZ_SDK_SCHEDULER_ENABLE_DISABLE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_ENABLE_DISABLE_FAILED); + break; + case GIZ_SDK_SCHEDULER_STATUS_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCHEDULER_STATUS_UPDATE_FAILED); + break; + case GIZ_SDK_GROUP_ID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_ID_INVALID); + break; + case GIZ_SDK_GROUP_FAILED_DELETE_DEVICE: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_DELETE_DEVICE); + break; + case GIZ_SDK_GROUP_FAILED_ADD_DEVICE: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_ADD_DEVICE); + break; + case GIZ_SDK_GROUP_PRODUCTKEY_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_PRODUCTKEY_INVALID); + break; + case GIZ_SDK_GROUP_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_CREATE_FAILED); + break; + case GIZ_SDK_GROUP_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_DELETE_DEVICE); + break; + case GIZ_SDK_GROUP_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_EDIT_FAILED); + break; + case GIZ_SDK_GROUP_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GROUP_GET_DEVICE_FAILED); + break; + case GIZ_SDK_SCENE_CREATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_CREATE_FAILED); + break; + case GIZ_SDK_SCENE_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_DELETE_FAILED); + break; + case GIZ_SDK_SCENE_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_EDIT_FAILED); + break; + case GIZ_SDK_SCENE_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCENE_ITEM_LIST_EDIT_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_ITEM_LIST_EDIT_FAILED); + break; + case GIZ_SDK_SCENE_ITEM_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_ITEM_LIST_UPDATE_FAILED); + break; + case GIZ_SDK_SCENE_ID_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_ID_INVALID); + break; + case GIZ_SDK_SCENE_RUN_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_RUN_FAILED); + break; + case GIZ_SDK_SCENE_STATUS_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_SCENE_STATUS_UPDATE_FAILED); + break; + case GIZ_SDK_JOINT_ACTION_CREATE_FAILED: + errorString= (String) getText(R.string.GIZ_SDK_JOINT_ACTION_CREATE_FAILED); + break; + case GIZ_SDK_JOINT_ACTION_DELETE_FAILED: + errorString= (String) getText(R.string.GIZ_SDK_JOINT_ACTION_DELETE_FAILED); + break; + case GIZ_SDK_JOINT_ACTION_VER_UNSUPPORTED: + errorString= (String) getText(R.string.GIZ_SDK_JOINT_ACTION_VER_UNSUPPORTED); + break; +// case GIZ_SDK_JOINT_ACTION_INVALID_CONDITION_TYPE: +// errorString= (String) getText(R.string.GIZ_SDK_JOINT_ACTION_INVALID_CONDITION_TYPE); +// break; +// case GIZ_SDK_JOINT_ACTION_INVALID_RESULT_EVENT_TYPE: +// errorString= (String) getText(R.string.GIZ_SDK_JOINT_ACTION_INVALID_RESULT_EVENT_TYPE); +// break; + case GIZ_SDK_DATAPOINT_NOT_DOWNLOAD: + errorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_NOT_DOWNLOAD); + break; + case GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE: + errorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE); + break; + case GIZ_SDK_DATAPOINT_PARSE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_PARSE_FAILED); + break; + // case GIZ_SDK_NOT_INITIALIZED: + // errorString= (String) getText(R.string.GIZ_SDK_SDK_NOT_INITIALIZED); + // break; + case GIZ_SDK_APK_CONTEXT_IS_NULL: + errorString = (String) getText(R.string.GIZ_SDK_APK_CONTEXT_IS_NULL); + break; + case GIZ_SDK_APK_PERMISSION_NOT_SET: + errorString = (String) getText(R.string.GIZ_SDK_APK_PERMISSION_NOT_SET); + break; + case GIZ_SDK_CHMOD_DAEMON_REFUSED: + errorString = (String) getText(R.string.GIZ_SDK_CHMOD_DAEMON_REFUSED); + break; + case GIZ_SDK_EXEC_DAEMON_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_EXEC_DAEMON_FAILED); + break; + case GIZ_SDK_EXEC_CATCH_EXCEPTION: + errorString = (String) getText(R.string.GIZ_SDK_EXEC_CATCH_EXCEPTION); + break; + case GIZ_SDK_APPID_IS_EMPTY: + errorString = (String) getText(R.string.GIZ_SDK_APPID_IS_EMPTY); + break; + case GIZ_SDK_UNSUPPORTED_API: + errorString = (String) getText(R.string.GIZ_SDK_UNSUPPORTED_API); + break; + case GIZ_SDK_REQUEST_TIMEOUT: + errorString = (String) getText(R.string.GIZ_SDK_REQUEST_TIMEOUT); + break; + case GIZ_SDK_DAEMON_VERSION_INVALID: + errorString = (String) getText(R.string.GIZ_SDK_DAEMON_VERSION_INVALID); + break; + case GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID: + errorString = (String) getText(R.string.GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID); + break; + case GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED: + errorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED); + break; + case GIZ_SDK_NOT_IN_SOFTAPMODE: + errorString = (String) getText(R.string.GIZ_SDK_NOT_IN_SOFTAPMODE); + break; +// case GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE: +// errorString= (String)getText(R.string.GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE); +// break; + case GIZ_SDK_RAW_DATA_TRANSMIT: + errorString = (String) getText(R.string.GIZ_SDK_RAW_DATA_TRANSMIT); + break; + case GIZ_SDK_PRODUCT_IS_DOWNLOADING: + errorString = (String) getText(R.string.GIZ_SDK_PRODUCT_IS_DOWNLOADING); + break; + case GIZ_SDK_START_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_START_SUCCESS); + break; + case GIZ_SDK_NEED_UPDATE_TO_LATEST: + errorString = (String) getText(R.string.GIZ_SDK_NEED_UPDATE_TO_LATEST); + break; + case GIZ_SDK_ONBOARDING_STOPPED: + errorString = (String) getText(R.string.GIZ_SDK_ONBOARDING_STOPPED); + break; + case GIZ_SDK_ONBOARDING_WIFI_IS_5G: + errorString = (String) getText(R.string.GIZ_SDK_ONBOARDING_WIFI_IS_5G); + break; + case GIZ_SDK_OTA_FIRMWARE_IS_LATEST: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_IS_LATEST); + break; + case GIZ_SDK_OTA_FIRMWARE_CHECK_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_CHECK_UPDATE_FAILED); + break; + case GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_OK: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_OK); + break; + case GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_DOWNLOAD_FAILED); + break; + case GIZ_SDK_OTA_DEVICE_BUSY_IN_UPGRADE: + errorString = (String) getText(R.string.GIZ_SDK_OTA_DEVICE_BUSY_IN_UPGRADE); + break; + case GIZ_SDK_OTA_PUSH_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_PUSH_FAILED); + break; + case GIZ_SDK_OTA_FIRMWARE_VERSION_TOO_LOW: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_VERSION_TOO_LOW); + break; + case GIZ_SDK_OTA_FIRMWARE_CHECK_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_CHECK_FAILED); + break; + case GIZ_SDK_OTA_UPGRADE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_OTA_UPGRADE_FAILED); + break; + case GIZ_SDK_OTA_FIRMWARE_VERIFY_SUCCESS: + errorString = (String) getText(R.string.GIZ_SDK_OTA_FIRMWARE_VERIFY_SUCCESS); + break; + case GIZ_SDK_OTA_DEVICE_NOT_SUPPORT: + errorString = (String) getText(R.string.GIZ_SDK_OTA_DEVICE_NOT_SUPPORT); + break; + case GIZ_SDK_WS_HANDSHAKE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_WS_HANDSHAKE_FAILED); + break; + case GIZ_SDK_WS_LOGIN_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_WS_LOGIN_FAILED); + break; +// case GIZ_SDK_WS_DEVICE_SUBSCRIBE_FAILED: +// errorString = (String) getText(R.string.GIZ_SDK_WS_DEVICE_SUBSCRIBE_FAILED); +// break; +// case GIZ_SDK_WS_DEVICE_UNSUBSCRIBE_FAILED: +// errorString = (String) getText(R.string.GIZ_SDK_WS_DEVICE_UNSUBSCRIBE_FAILED); +// break; + case GIZ_SITE_PRODUCTKEY_INVALID: + errorString = (String) getText(R.string.GIZ_SITE_PRODUCTKEY_INVALID); + break; + case GIZ_SITE_DATAPOINTS_NOT_DEFINED: + errorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_DEFINED); + break; + case GIZ_SITE_DATAPOINTS_NOT_MALFORME: + errorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_MALFORME); + break; + case GIZ_OPENAPI_MAC_ALREADY_REGISTERED: + errorString = (String) getText(R.string.GIZ_OPENAPI_MAC_ALREADY_REGISTERED); + break; + case GIZ_OPENAPI_PRODUCT_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_KEY_INVALID); + break; + case GIZ_OPENAPI_APPID_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_APPID_INVALID); + break; + case GIZ_OPENAPI_TOKEN_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_INVALID); + break; + case GIZ_OPENAPI_USER_NOT_EXIST: + errorString = (String) getText(R.string.GIZ_OPENAPI_USER_NOT_EXIST); + break; + case GIZ_OPENAPI_TOKEN_EXPIRED: + errorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_EXPIRED); + break; + case GIZ_OPENAPI_M2M_ID_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_M2M_ID_INVALID); + break; + case GIZ_OPENAPI_SERVER_ERROR: + errorString = (String) getText(R.string.GIZ_OPENAPI_SERVER_ERROR); + break; + case GIZ_OPENAPI_CODE_EXPIRED: + errorString = (String) getText(R.string.GIZ_OPENAPI_CODE_EXPIRED); + break; + case GIZ_OPENAPI_CODE_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_CODE_INVALID); + break; + case GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED); + break; + case GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED); + break; + case GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE); + break; + case GIZ_OPENAPI_DEVICE_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_FOUND); + break; + case GIZ_OPENAPI_FORM_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_FORM_INVALID); + break; + case GIZ_OPENAPI_DID_PASSCODE_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_DID_PASSCODE_INVALID); + break; + case GIZ_OPENAPI_DEVICE_NOT_BOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_BOUND); + break; + case GIZ_OPENAPI_PHONE_UNAVALIABLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_PHONE_UNAVALIABLE); + break; + case GIZ_OPENAPI_USERNAME_UNAVALIABLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_UNAVALIABLE); + break; + case GIZ_OPENAPI_USERNAME_PASSWORD_ERROR: + errorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_PASSWORD_ERROR); + break; + case GIZ_OPENAPI_SEND_COMMAND_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SEND_COMMAND_FAILED); + break; + case GIZ_OPENAPI_EMAIL_UNAVALIABLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_UNAVALIABLE); + break; + case GIZ_OPENAPI_DEVICE_DISABLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_DISABLED); + break; + case GIZ_OPENAPI_FAILED_NOTIFY_M2M: + errorString = (String) getText(R.string.GIZ_OPENAPI_FAILED_NOTIFY_M2M); + break; + case GIZ_OPENAPI_ATTR_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_ATTR_INVALID); + break; + case GIZ_OPENAPI_USER_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_USER_INVALID); + break; + case GIZ_OPENAPI_FIRMWARE_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_FIRMWARE_NOT_FOUND); + break; + case GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND); + break; + case GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND); + break; + case GIZ_OPENAPI_SCHEDULER_NOT_FOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_SCHEDULER_NOT_FOUND); + break; + case GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID); + break; + case GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE: + errorString = (String) getText(R.string.GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE); + break; + case GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED: + errorString = (String) getText(R.string.GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED); + break; + case GIZ_OPENAPI_BT_FIRMWARE_NOTHING_TO_UPGRADE: + errorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR); + break; + case GIZ_OPENAPI_SAVE_KAIROSDB_ERROR: + errorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR); + break; + case GIZ_OPENAPI_EVENT_NOT_DEFINED: + errorString = (String) getText(R.string.GIZ_OPENAPI_EVENT_NOT_DEFINED); + break; + case GIZ_OPENAPI_SEND_SMS_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SEND_SMS_FAILED); + break; +// case GIZ_OPENAPI_APPLICATION_AUTH_INVALID: +// errorString= (String) +// getText(R.string.GIZ_OPENAPI_APPLICATION_AUTH_INVALID); +// break; + case GIZ_OPENAPI_NOT_ALLOWED_CALL_API: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_ALLOWED_CALL_API); + break; + case GIZ_OPENAPI_BAD_QRCODE_CONTENT: + errorString = (String) getText(R.string.GIZ_OPENAPI_BAD_QRCODE_CONTENT); + break; + case GIZ_OPENAPI_REQUEST_THROTTLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_REQUEST_THROTTLED); + break; + case GIZ_OPENAPI_DEVICE_OFFLINE: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_OFFLINE); + break; + case GIZ_OPENAPI_TIMESTAMP_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_TIMESTAMP_INVALID); + break; + case GIZ_OPENAPI_SIGNATURE_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_SIGNATURE_INVALID); + break; + case GIZ_OPENAPI_DEPRECATED_API: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEPRECATED_API); + break; + case GIZ_OPENAPI_REGISTER_IS_BUSY: + errorString = (String) getText(R.string.GIZ_OPENAPI_REGISTER_IS_BUSY); + break; + case GIZ_OPENAPI_ALTER_PASSWORD_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_ALTER_PASSWORD_FAILED); + break; + case GIZ_OPENAPI_APPID_PK_NOT_RELATION: + errorString = (String) getText(R.string.GIZ_OPENAPI_APPID_PK_NOT_RELATION); + break; + case GIZ_OPENAPI_CALL_INNER_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_CALL_INNER_FAILED); + break; + case GIZ_OPENAPI_DEVICE_SHARING_NOT_ENABLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_SHARING_NOT_ENABLED); + break; + case GIZ_OPENAPI_NOT_FIRST_USER_OF_DEVICE: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FIRST_USER_OF_DEVICE); + break; + case GIZ_OPENAPI_PRODUCT_KEY_AUTHEN_FAULT: + errorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_KEY_AUTHEN_FAULT); + break; + case GIZ_OPENAPI_BUSY_NOW: + errorString = (String) getText(R.string.GIZ_OPENAPI_BUSY_NOW); + break; + case GIZ_OPENAPI_TWITTER_CONSUMER_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_OPENAPI_TWITTER_CONSUMER_KEY_INVALID); + break; + case GIZ_OPENAPI_NOT_ALLOW_WEEK_PASSWORD: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_ALLOW_WEEK_PASSWORD); + break; +// case GIZ_OPENAPI_CODE_NOT_EXIST: +// errorString = (String) getText(R.string.GIZ_OPENAPI_CODE_NOT_EXIST); +// break; +// case GIZ_OPENAPI_EMAIL_NOT_ACTIVE: +// errorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_NOT_ACTIVE); +// break; +// case GIZ_OPENAPI_EMAIL_NOT_ENABLE: +// errorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_NOT_ENABLE); +// break; +// case GIZ_OPENAPI_DEVICE_REGISTER_NOT_FOUND: +// errorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_REGISTER_NOT_FOUND); +// break; + case GIZ_OPENAPI_CANNOT_SHARE_TO_SELF: + errorString = (String) getText(R.string.GIZ_OPENAPI_CANNOT_SHARE_TO_SELF); + break; + case GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE); + break; + case GIZ_OPENAPI_NOT_FOUND_GUEST: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_GUEST); + break; + case GIZ_OPENAPI_GUEST_ALREADY_BOUND: + errorString = (String) getText(R.string.GIZ_OPENAPI_GUEST_ALREADY_BOUND); + break; + case GIZ_OPENAPI_NOT_FOUND_SHARING_INFO: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_SHARING_INFO); + break; + case GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE: + errorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE); + break; + case GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT); + break; + case GIZ_OPENAPI_SHARING_IS_EXPIRED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_EXPIRED); + break; + case GIZ_OPENAPI_SHARING_IS_COMPLETED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_COMPLETED); + break; + case GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING: + errorString = (String) getText(R.string.GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING); + break; + case GIZ_OPENAPI_ONLY_OWNER_CAN_BIND: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_BIND); + break; + case GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE); + break; + case GIZ_OPENAPI_SHARING_ALREADY_CANCELLED: + errorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_ALREADY_CANCELLED); + break; + case GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF: + errorString = (String) getText(R.string.GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF); + break; + case GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE); + break; + case GIZ_OPENAPI_MESSAGE_ALREADY_DELETED: + errorString = (String) getText(R.string.GIZ_OPENAPI_MESSAGE_ALREADY_DELETED); + break; + case GIZ_OPENAPI_BINDING_NOTIFY_FAILED: + errorString = (String) getText(R.string.GIZ_OPENAPI_BINDING_NOTIFY_FAILED); + break; + case GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS); + break; + case GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE: + errorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE); + break; + case GIZ_OPENAPI_GUEST_NOT_BIND: + errorString = (String) getText(R.string.GIZ_OPENAPI_GUEST_NOT_BIND); + break; + case GIZ_OPENAPI_CANNOT_TRANSFER_OWNER_TO_SELF: + errorString = (String) getText(R.string.GIZ_OPENAPI_CANNOT_TRANSFER_OWNER_TO_SELF); + break; + case GIZ_OPENAPI_TRANSFER_OWNER_TO_LIMIT_GUEST: + errorString = (String) getText(R.string.GIZ_OPENAPI_TRANSFER_OWNER_TO_LIMIT_GUEST); + break; + case GIZ_OPENAPI_RESERVED: + errorString = (String) getText(R.string.GIZ_OPENAPI_RESERVED); + break; + case GIZ_PUSHAPI_BODY_JSON_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_BODY_JSON_INVALID); + break; + case GIZ_PUSHAPI_DATA_NOT_EXIST: + errorString = (String) getText(R.string.GIZ_PUSHAPI_DATA_NOT_EXIST); + break; + case GIZ_PUSHAPI_NO_CLIENT_CONFIG: + errorString = (String) getText(R.string.GIZ_PUSHAPI_NO_CLIENT_CONFIG); + break; + case GIZ_PUSHAPI_NO_SERVER_DATA: + errorString = (String) getText(R.string.GIZ_PUSHAPI_NO_SERVER_DATA); + break; + case GIZ_PUSHAPI_GIZWITS_APPID_EXIST: + errorString = (String) getText(R.string.GIZ_PUSHAPI_GIZWITS_APPID_EXIST); + break; + case GIZ_PUSHAPI_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_PARAM_ERROR); + break; + case GIZ_PUSHAPI_AUTH_KEY_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_AUTH_KEY_INVALID); + break; + case GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR); + break; + case GIZ_PUSHAPI_TYPE_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_TYPE_PARAM_ERROR); + break; + case GIZ_PUSHAPI_ID_PARAM_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_ID_PARAM_ERROR); + break; + case GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID); + break; + case GIZ_PUSHAPI_CHANNELID_ERROR_INVALID: + errorString = (String) getText(R.string.GIZ_PUSHAPI_CHANNELID_ERROR_INVALID); + break; + case GIZ_PUSHAPI_PUSH_ERROR: + errorString = (String) getText(R.string.GIZ_PUSHAPI_PUSH_ERROR); + break; + case GIZ_SDK_SUBDEVICE_ADD_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_ADD_SUBDEVICE_FAILED); + break; + + case GIZ_SDK_SUBDEVICE_DELETE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_DELETE_SUBDEVICE_FAILED); + break; + + case GIZ_SDK_SUBDEVICE_LIST_UPDATE_FAILED: + errorString = (String) getText(R.string.GIZ_SDK_GET_SUBDEVICES_FAILED); + break; + default: + errorString = (String) getText(R.string.UNKNOWN_ERROR); + break; + } + return errorString; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceListAdapter.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceListAdapter.java new file mode 100644 index 0000000..c79b5cf --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceListAdapter.java @@ -0,0 +1,311 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Handler; +import android.os.Message; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.RelativeLayout; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizWifiCentralControlDevice; +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.sharingdevice.addSharedActivity; +import com.gizwits.opensource.appkit.utils.AssetsUtils; + +import java.util.List; +import java.util.Map; + +import static com.gizwits.gizwifisdk.enumration.GizWifiDeviceType.GizDeviceCenterControl; + + +@SuppressLint("InflateParams") +public class GosDeviceListAdapter extends BaseAdapter { + + private static final String TAG = "GosDeviceListAdapter"; + Handler handler = new Handler(); + SharedPreferences spf; + protected static final int UNBOUND = 99; + protected static final int SHARE = 100; + + public void setHandler(Handler handler) { + this.handler = handler; + } + + Context context; + List deviceList; + + public GosDeviceListAdapter(Context context, List deviceList) { + super(); + this.context = context; + this.deviceList = deviceList; + } + + public void setSpf(SharedPreferences spf) { + this.spf = spf; + } + + @Override + public int getCount() { + return deviceList.size(); + } + + @Override + public Object getItem(int position) { + return null; + } + + @Override + public long getItemId(int position) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + Holder holder; + + if (view == null) { + view = LayoutInflater.from(context).inflate( + R.layout.item_gos_device_list, null); + holder = new Holder(view); + view.setTag(holder); + } else { + holder = (Holder) view.getTag(); + } + final GizWifiDevice device = deviceList.get(position); + + String deviceAlias = device.getAlias(); + String devicePN = device.getProductName(); + + GizDeviceSharingUserRole role = device.getSharingRole(); + + if (role != null) { + if (role.name().equals("GizDeviceSharingSpecial") || role.name().equals("GizDeviceSharingOwner")) { + holder.getDelete2().setVisibility(View.VISIBLE); + holder.getDelete1().setVisibility(View.VISIBLE); + holder.getDevice().setPadding(0, 0, AssetsUtils.diptopx(context, -181), 0); + } else { + holder.getDelete1().setVisibility(View.GONE); + holder.getDelete2().setVisibility(View.VISIBLE); + holder.getDevice().setPadding(0, 0, AssetsUtils.diptopx(context, -91), 0); + } + } + GizWifiCentralControlDevice centralControlDevice = null; + holder.getTvDeviceMac().setVisibility(View.GONE); + holder.getTvDeviceMac().setVisibility(View.VISIBLE); + holder.getTvDeviceMac().setText(device.getMacAddress()); + + if (device.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline + || device.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled) { + + if (device.isLAN()) { + holder.getLlLeft().setImageResource(R.drawable.common_device_lan_online); + } else { + holder.getLlLeft().setImageResource(R.drawable.common_device_remote_online); + } + holder.getImgRight().setVisibility(View.VISIBLE); + + if (device.isBind()) {// 已绑定设备 + if (device.getProductType() == GizDeviceCenterControl) { + if (device instanceof GizWifiCentralControlDevice) { + centralControlDevice = (GizWifiCentralControlDevice) device; + } + } + if (centralControlDevice != null) { + if (centralControlDevice.getSubDeviceList().size() != 0) { + holder.getTvDeviceMac().setVisibility(View.VISIBLE); + if (AssetsUtils.isZh(context)) { + StringBuffer sb = new StringBuffer(); + sb.append("已连接"); + sb.append(centralControlDevice.getSubDeviceList().size()); + sb.append("个设备"); + holder.getTvDeviceMac().setText(sb.toString()); + } else { + StringBuffer sb = new StringBuffer(); + sb.append(centralControlDevice.getSubDeviceList().size()); + sb.append(" devices connected"); + holder.getTvDeviceMac().setText(sb.toString()); + } + if (AssetsUtils.isZh(context)) { + StringBuffer sb = new StringBuffer(); + sb.append(centralControlDevice.getMacAddress()); + sb.append(" 已连接"); + sb.append(centralControlDevice.getSubDeviceList().size()); + sb.append("个设备"); + holder.getTvDeviceMac().setText(sb.toString()); + } else { + StringBuffer sb = new StringBuffer(); + sb.append(centralControlDevice.getMacAddress()); + sb.append(" "); + sb.append(centralControlDevice.getSubDeviceList().size()); + sb.append(" devices connected"); + holder.getTvDeviceMac().setText(sb.toString()); + } + } + } + //这里会出现箭头不显示的状态 +// holder.getImgRight().setVisibility(View.VISIBLE); + + } else {// 未绑定设备 + holder.getDelete2().setVisibility(View.GONE); + holder.getDevice().setPadding(0, 0, AssetsUtils.diptopx(context, 0), 0); + } + } else {// 设备不在线 + holder.getSbDeviceStatus().setClickable(false); + holder.getImgRight().setVisibility(View.GONE); + if (device.isLAN()) { + holder.getLlLeft().setImageResource(R.drawable.common_device_lan_offline); + } else { + holder.getLlLeft().setImageResource(R.drawable.common_device_remote_offline); + } + } + if (TextUtils.isEmpty(deviceAlias)) { + List> list = GosDeploy.appConfig_DeviceInfo(); + boolean isName = true; + for (Map map : list) { + if (map.containsKey("productKey")) { + if (device.getProductKey().equals(map.get("productKey"))) { + if (AssetsUtils.isZh(context)) { + if (map.containsKey("productNameCH")) { + isName = false; + holder.getTvDeviceName().setText(map.get("productNameCH").toString()); + } + } else { + if (map.containsKey("productNameEN")) { + isName = false; + holder.getTvDeviceName().setText(map.get("productNameEN").toString()); + } + } + } + } + } + if (isName) { + holder.getTvDeviceName().setText(devicePN); + } + } else { + holder.getTvDeviceName().setText(deviceAlias); + } + holder.getDelete2().setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + Message message = new Message(); + message.what = UNBOUND; + message.obj = device.getDid().toString(); + handler.sendMessage(message); + + } + }); + holder.getDelete1().setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + Message message = new Message(); + message.what = SHARE; + message.obj = device.getDid().toString(); + handler.sendMessage(message); + + if (!TextUtils.isEmpty(spf.getString("UserName", "")) && !TextUtils.isEmpty(spf.getString("PassWord", ""))) { + Intent intent = new Intent(context, addSharedActivity.class); + intent.putExtra("productname", device.getProductName()); + intent.putExtra("did", device.getDid()); + context.startActivity(intent); + } else { + Toast.makeText(context, context.getString(R.string.please_login), 2000).show(); + } + } + }); + return view; + } + +} + +class Holder { + View view; + + public Holder(View view) { + this.view = view; + } + + private TextView tvDeviceMac, tvDeviceStatus, tvDeviceName; + + private RelativeLayout delete1, delete2, device; + + private ImageView imgRight; + + private ImageView lvLeft; + + private Switch sbDeviceStatus; + + public ImageView getLlLeft() { + if (null == lvLeft) { + lvLeft = (ImageView) view.findViewById(R.id.imgLeft); + } + return lvLeft; + } + + public ImageView getImgRight() { + if (null == imgRight) { + imgRight = (ImageView) view.findViewById(R.id.imgRight); + } + return imgRight; + } + + public RelativeLayout getDevice() { + if (null == device) { + device = (RelativeLayout) view.findViewById(R.id.rl_device); + } + return device; + } + + public RelativeLayout getDelete2() { + if (null == delete2) { + delete2 = (RelativeLayout) view.findViewById(R.id.delete2); + } + return delete2; + } + + public RelativeLayout getDelete1() { + if (null == delete1) { + delete1 = (RelativeLayout) view.findViewById(R.id.delete1); + } + return delete1; + } + + public TextView getTvDeviceMac() { + if (null == tvDeviceMac) { + tvDeviceMac = (TextView) view.findViewById(R.id.tvDeviceMac); + } + return tvDeviceMac; + } + + + public TextView getTvDeviceName() { + if (null == tvDeviceName) { + tvDeviceName = (TextView) view.findViewById(R.id.tvDeviceName); + } + return tvDeviceName; + } + + public Switch getSbDeviceStatus() { + if (null == sbDeviceStatus) { + sbDeviceStatus = (Switch) view.findViewById(R.id.sbDeviceStatus); + } + return sbDeviceStatus; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceListFragment.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceListFragment.java new file mode 100644 index 0000000..f515224 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceListFragment.java @@ -0,0 +1,847 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; +import android.text.TextUtils; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.ConfigModule.GosAirlinkChooseDeviceWorkWiFiActivity; +import com.gizwits.opensource.appkit.ConfigModule.GosChooseDeviceWorkWiFiActivity; +import com.gizwits.opensource.appkit.ControlModule.GosDeviceControlActivity; +import com.gizwits.opensource.appkit.PushModule.GosPushManager; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.view.SlideListView2; +import com.gizwits.opensource.appkit.view.VerticalSwipeRefreshLayout; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; + +// config-all-start +// config_airlink-false-start +// config_airlink-false-end +//config_softap-false-start +//config_softap-false-end +// config-all-end + + +@SuppressLint("HandlerLeak") +public class GosDeviceListFragment extends GosDeviceModuleBaseFragment implements OnRefreshListener { + + /** + * The ll NoDevice + */ + private ScrollView llNoDevice; + + SwipeRefreshLayout mSwipeLayout; + + /** + * The img NoDevice + */ + private ImageView imgNoDevice; + + /** + * The btn NoDevice + */ + private Button btnNoDevice; + + /** + * The ic BoundDevices + */ + private View icBoundDevices; + + /** + * The ic FoundDevices + */ + private View icFoundDevices; + + + /** + * The tv BoundDevicesListTitle + */ + private TextView tvBoundDevicesListTitle; + + /** + * The tv FoundDevicesListTitle + */ + private TextView tvFoundDevicesListTitle; + + + /** + * The ll NoBoundDevices + */ + private LinearLayout llNoBoundDevices; + + /** + * The ll NoFoundDevices + */ + private LinearLayout llNoFoundDevices; + + + /** + * The slv BoundDevices + */ + private SlideListView2 slvBoundDevices; + + /** + * The slv FoundDevices + */ + private SlideListView2 slvFoundDevices; + + + /** + * The sv ListGroup + */ + private ScrollView svListGroup; + + /** + * 适配器 + */ + private GosDeviceListAdapter myadapter; + + private GosDeviceListAdapter myadapter1; + + /** + * 设备列表分类 + */ + List boundDevicesList = new ArrayList(); + List foundDevicesList = new ArrayList(); + List offlineDevicesList = new ArrayList(); + + /** + * 设备热点名称列表 + */ + ArrayList softNameList; + + /** + * 与APP绑定的设备的ProductKey + */ + private List ProductKeyList; + + Intent intent; + + String softssid, uid, token; + + public static List boundMessage; + + /** + * 判断用户登录状态 0:未登录 1:实名用户登录 2:匿名用户登录 3:匿名用户登录中 4:匿名用户登录中断 + */ + public static int loginStatus; + + int threeSeconds = 3; + + /** + * 获取设备列表 + */ + protected static final int GETLIST = 0; + + /** + * 刷新设备列表 + */ + protected static final int UPDATALIST = 1; + + /** + * 订阅成功前往控制页面 + */ + protected static final int TOCONTROL = 2; + + /** + * 通知 + */ + protected static final int TOAST = 3; + + /** + * 设备绑定 + */ + protected static final int BOUND = 9; + + /** + * 设备解绑 + */ + protected static final int UNBOUND = 99; + + + private static final int PULL_TO_REFRESH = 888; + + private VerticalSwipeRefreshLayout mSwipeLayout1; + + /** + * 等待框 + */ + public ProgressDialog progressDialog; + + Handler handler = new Handler() { + private AlertDialog myDialog; + private TextView dialog_name; + + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case GETLIST: + Log.e(TAG, "handleMessage:GETLIST -----------------" + uid); + if (!uid.isEmpty() && !token.isEmpty()) { + // GizWifiSDK.sharedInstance().getBoundDevices(uid, token, ProductKeyList); + GizWifiSDK.sharedInstance().getBoundDevices(uid, token); + } + + //login_anonymous-false-start + if (loginStatus == 0 && GosDeploy.appConfig_Login_Anonymous()) { + loginStatus = 3; + GizWifiSDK.sharedInstance().userLoginAnonymous(); + } + //login_anonymous-false-end + break; + + case UPDATALIST: + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.cancel(); + } + UpdateUI(); + break; + + case BOUND: + + break; + + case UNBOUND: + if (progressDialog != null) { + progressDialog.show(); + } + GizWifiSDK.sharedInstance().unbindDevice(uid, token, msg.obj.toString()); + break; + + case TOCONTROL: + intent = null; + Bundle bundle = new Bundle(); + GizWifiDevice device = (GizWifiDevice) msg.obj; + if (intent == null) { + intent = new Intent(getContext(), GosDeviceControlActivity.class); + } + bundle.putParcelable("GizWifiDevice", device); + intent.putExtras(bundle); + startActivityForResult(intent, 1); + break; + + case TOAST: + Toast.makeText(getContext(), msg.obj.toString(), 2000).show(); + break; + + case PULL_TO_REFRESH: + handler.sendEmptyMessage(GETLIST); + mSwipeLayout.setRefreshing(false); + mSwipeLayout1.setRefreshing(false); + + break; + } + } + }; + private View allView; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + allView = inflater.inflate(R.layout.activity_gos_device_list, container, false); + //handler.sendEmptyMessage(GETLIST); + + GosMessageHandler.getSingleInstance().StartLooperWifi(getContext()); + setProgressDialog(); + softNameList = new ArrayList(); + initData(); + initView(); + initEvent(); + return allView; + } + + /* + * @Override public void onWindowFocusChanged(boolean hasFocus) { + * super.onWindowFocusChanged(hasFocus); if (hasFocus && isFrist) { + * progressDialog.show(); + * + * isFrist = false; } } + */ + @Override + public void onResume() { + super.onResume(); + Log.e(TAG, "onResume: -------------"); + handler.sendEmptyMessage(GETLIST); + GosDeviceModuleBaseFragment.deviceslist = GizWifiSDK.sharedInstance().getDeviceList(); + UpdateUI(); + // TODO GosMessageHandler.getSingleInstance().SetHandler(handler); + if (boundMessage.size() != 0) { + progressDialog.show(); + if (boundMessage.size() == 2) { + GizWifiSDK.sharedInstance().bindDevice(uid, token, boundMessage.get(0), boundMessage.get(1), null); + } else if (boundMessage.size() == 1) { + GizWifiSDK.sharedInstance().bindDeviceByQRCode(uid, token, boundMessage.get(0), false); + } else if (boundMessage.size() == 3) { + GizDeviceSharing.checkDeviceSharingInfoByQRCode(spf.getString("Token", ""), boundMessage.get(2)); + } else { + Log.i("Apptest", "ListSize:" + boundMessage.size()); + } + } + + } + + @Override + public void onPause() { + super.onPause(); + boundMessage.clear(); + // TODO GosMessageHandler.getSingleInstance().SetHandler(null); + + } + + private void initView() { + svListGroup = (ScrollView) allView.findViewById(R.id.svListGroup); + llNoDevice = (ScrollView) allView.findViewById(R.id.llNoDevice); + imgNoDevice = (ImageView) allView.findViewById(R.id.imgNoDevice); + btnNoDevice = (Button) allView.findViewById(R.id.btnNoDevice); + + icBoundDevices = allView.findViewById(R.id.icBoundDevices); + icFoundDevices = allView.findViewById(R.id.icFoundDevices); + + slvBoundDevices = (SlideListView2) icBoundDevices.findViewById(R.id.slideListView1); + slvFoundDevices = (SlideListView2) icFoundDevices.findViewById(R.id.slideListView1); + + llNoBoundDevices = (LinearLayout) icBoundDevices.findViewById(R.id.llHaveNotDevice); + llNoFoundDevices = (LinearLayout) icFoundDevices.findViewById(R.id.llHaveNotDevice); + + tvBoundDevicesListTitle = (TextView) icBoundDevices.findViewById(R.id.tvListViewTitle); + tvFoundDevicesListTitle = (TextView) icFoundDevices.findViewById(R.id.tvListViewTitle); + String boundDevicesListTitle = null; + String foundDevicesListTitle = null; + boundDevicesListTitle = (String) getText(R.string.my_device); + foundDevicesListTitle = (String) getText(R.string.found_devices); + + tvBoundDevicesListTitle.setText(boundDevicesListTitle); + + tvFoundDevicesListTitle.setText(foundDevicesListTitle); + + // 下拉刷新 + + mSwipeLayout = (VerticalSwipeRefreshLayout) allView.findViewById(R.id.id_swipe_ly); + + mSwipeLayout.setOnRefreshListener(this); + mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, + android.R.color.holo_orange_light, android.R.color.holo_red_light); + + mSwipeLayout1 = (VerticalSwipeRefreshLayout) allView.findViewById(R.id.id_swipe_ly1); + mSwipeLayout1.setOnRefreshListener(this); + mSwipeLayout1.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, + android.R.color.holo_orange_light, android.R.color.holo_red_light); +// setActionBar(true, true, ""); +// actionBar.setIcon(getResources().getDrawable(R.drawable.qr_code)); + } + + private void initEvent() { + myadapter = new GosDeviceListAdapter(getContext(), foundDevicesList); + myadapter.setHandler(handler); + myadapter.setSpf(spf); + slvFoundDevices.setAdapter(myadapter); + myadapter1 = new GosDeviceListAdapter(getContext(), boundDevicesList); + myadapter1.setHandler(handler); + myadapter1.setSpf(spf); + slvBoundDevices.setAdapter(myadapter1); + // config-all-start + imgNoDevice.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + addDevice(); + } + }); + btnNoDevice.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + addDevice(); + } + }); + // config-all-end + slvFoundDevices.initSlideMode(SlideListView2.MOD_FORBID); + slvFoundDevices.setFocusable(false); + slvBoundDevices.initSlideMode(SlideListView2.MOD_RIGHT); + slvBoundDevices.setFocusable(false); + slvFoundDevices.setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, final View view, int position, long id) { + + slvFoundDevices.setEnabled(false); + slvFoundDevices.postDelayed(new Runnable() { + @Override + public void run() { + slvFoundDevices.setEnabled(true); + } + }, 1000); + final GizWifiDevice device = foundDevicesList.get(position); + device.setListener(getGizWifiDeviceListener(device)); + if (device.getNetStatus() != GizWifiDeviceNetStatus.GizDeviceOffline) { + boolean isAuto = false; + + List> list2 = GosDeploy.appConfig_ProductList(); + for (Map map2 : list2) { + String productkey = device.getProductKey(); + Iterator it1 = map2.entrySet().iterator(); + while (it1.hasNext()) { + Map.Entry entry1 = (Map.Entry) it1.next(); + if (productkey.equals(entry1.getKey())) { + isAuto = true; + device.setSubscribe(entry1.getValue().toString(), true); + progressDialog.show(); + break; + } + } + } + + if (device.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline + && !TextUtils.isEmpty(device.getDid()) && !device.isBind() + && device.getProductType() == GizWifiDeviceType.GizDeviceSub) { + + if (!isAuto) { + final Dialog dialog = new AlertDialog.Builder(getContext(), R.style.alert_dialog_style) + .setView(new EditText(getContext())).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_edit_name); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + TextView title = (TextView) window.findViewById(R.id.tvTitle); + final EditText remarkname = (EditText) window.findViewById(R.id.remarkname); + title.setText(getString(R.string.pleaseenterps)); + LinearLayout llyes = (LinearLayout) window.findViewById(R.id.llSure); + LinearLayout llno = (LinearLayout) window.findViewById(R.id.llNo); + remarkname.setHint(getResources().getString(R.string.pleaseenter32ps)); + llno.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + dialog.dismiss(); + } + }); + llyes.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + String ps = remarkname.getText().toString(); + if (TextUtils.isEmpty(ps) || ps.length() != 32) { + Toast.makeText(getContext(), + getResources().getString(R.string.psiserror), 0).show(); + } else { + device.setSubscribe(remarkname.getText().toString(), true); + //device.setSubscribe(true); + progressDialog.show(); + /**隐藏软键盘**/ + View view = getActivity().getWindow().peekDecorView(); + if (view != null) { + InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); + inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + dialog.dismiss(); + } + } + }); + } + } else { +// device.setSubscribe(null, true); + if (!isAuto) { + device.setSubscribe(null, true); + progressDialog.show(); + } + } + } + + } + }); + + slvBoundDevices.setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, final View view, int position, long id) { + if (position < boundDevicesList.size()) { + + slvBoundDevices.setEnabled(false); + slvBoundDevices.postDelayed(new Runnable() { + @Override + public void run() { + slvBoundDevices.setEnabled(true); + } + }, 1000); + + final GizWifiDevice device = boundDevicesList.get(position); + device.setListener(getGizWifiDeviceListener(device)); + if (device.getNetStatus() != GizWifiDeviceNetStatus.GizDeviceOffline) { + String productKey = device.getProductKey(); + List> list2 = GosDeploy.appConfig_ProductList(); + boolean isSubscribe = false; + for (Map map2 : list2) { + Iterator it1 = map2.entrySet().iterator(); + while (it1.hasNext()) { + Map.Entry entry1 = (Map.Entry) it1.next(); + if (productKey.equals(entry1.getKey())) { + isSubscribe = true; + device.setSubscribe(entry1.getValue().toString(), true); + } + } + } + if (!isSubscribe) { + device.setSubscribe(null, true); + progressDialog.show(); + } + } + } + + } + }); + } + + + private void initData() { + boundMessage = new ArrayList(); + // ProductKeyList = GosDeploy.setProductKeyList(); + ProductKeyList = null; + uid = spf.getString("Uid", ""); + token = spf.getString("Token", ""); + if (uid.isEmpty() && token.isEmpty()) { + loginStatus = 0; + } + } + + protected void didDiscovered(GizWifiErrorCode result, List deviceList) { + Log.e(TAG, "didDiscovered: 更新数据---------------"); + GosDeviceModuleBaseFragment.deviceslist.clear(); + for (GizWifiDevice gizWifiDevice : deviceList) { + GosDeviceModuleBaseFragment.deviceslist.add(gizWifiDevice); + } + handler.sendEmptyMessage(UPDATALIST); + } + + protected void didUserLogin(GizWifiErrorCode result, String uid, String token) { + Log.e(TAG, "didUserLogin: -----------"); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) { + loginStatus = 2; + this.uid = uid; + this.token = token; + spf.edit().putString("Uid", this.uid).commit(); + spf.edit().putString("Token", this.token).commit(); + handler.sendEmptyMessage(GETLIST); + // TODO 绑定推送 + //GosPushManager.pushBindService(token); + if (GosDeploy.appConfig_Push_BaiDu()) { + GosPushManager.pushBindService(uid, token); + } + if (GosDeploy.appConfig_Push_JiGuang()) { + GosPushManager.pushBindService(uid, token); + } + } else { + loginStatus = 0; + if (GosDeploy.appConfig_Login_Anonymous()) { + tryUserLoginAnonymous(); + } + } + } + + protected void didUnbindDevice(GizWifiErrorCode result, String did) { + if (progressDialog != null) { + progressDialog.cancel(); + } + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + // String unBoundFailed = (String) getText(R.string.unbound_failed); + Toast.makeText(getContext(), toastError(result), 2000).show(); + } + } + + @Override + protected void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + // TODO 控制页面跳转 + if (progressDialog != null) { + progressDialog.cancel(); + } + Message msg = new Message(); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) { + msg.what = TOCONTROL; + msg.obj = device; + } else { + if (device.isBind()) { + msg.what = TOAST; + // String setSubscribeFail = (String) + // getText(R.string.setsubscribe_failed); + msg.obj = toastError(result);// setSubscribeFail + "\n" + arg0; + } + } + handler.sendMessage(msg); + } + + /** + * 推送绑定回调 + * + * @param result + */ + @Override + protected void didChannelIDBind(GizWifiErrorCode result) { + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + Toast.makeText(getContext(), toastError(result), 2000).show(); + } + } + + /** + * 设备绑定回调(旧) + * + * @param error + * @param errorMessage + * @param did + */ + protected void didBindDevice(int error, String errorMessage, String did) { + if (progressDialog != null) { + progressDialog.cancel(); + } + if (error != 0) { + + String toast = getResources().getString(R.string.bound_failed) + "\n" + errorMessage; + Toast.makeText(getContext(), toast, 2000).show(); + // Toast.makeText(this, R.string.bound_failed + "\n" + errorMessage, + // 2000).show(); + } else { + + Toast.makeText(getContext(), R.string.bound_successful, 2000).show(); + } + + } + + private static final String TAG = "GosDeviceListFragment"; + + /** + * 设备绑定回调 + * + * @param result + * @param did + */ + protected void didBindDevice(GizWifiErrorCode result, String did) { + if (progressDialog != null) { + progressDialog.cancel(); + + } + if (result != GizWifiErrorCode.GIZ_SDK_SUCCESS) { + Toast.makeText(getContext(), toastError(result), 2000).show(); + } else { + + Toast.makeText(getContext(), R.string.add_successful, 2000).show(); + } + } + + + private void UpdateUI() { + + if (GosDeviceModuleBaseFragment.deviceslist.isEmpty()) { + svListGroup.setVisibility(View.GONE); + llNoDevice.setVisibility(View.VISIBLE); + mSwipeLayout1.setVisibility(View.VISIBLE); + return; + } else { + llNoDevice.setVisibility(View.GONE); + mSwipeLayout1.setVisibility(View.GONE); + svListGroup.setVisibility(View.VISIBLE); + } + + if (boundDevicesList == null) { + boundDevicesList = new ArrayList(); + } else { + boundDevicesList.clear(); + } + if (foundDevicesList == null) { + foundDevicesList = new ArrayList(); + } else { + foundDevicesList.clear(); + } + if (offlineDevicesList == null) { + offlineDevicesList = new ArrayList(); + } else { + offlineDevicesList.clear(); + } + + for (GizWifiDevice gizWifiDevice : GosDeviceModuleBaseFragment.deviceslist) { + if (gizWifiDevice.isBind()) { + boundDevicesList.add(gizWifiDevice); + } else { + foundDevicesList.add(gizWifiDevice); + } + } + if (foundDevicesList.isEmpty()) { + slvFoundDevices.setVisibility(View.GONE); + llNoFoundDevices.setVisibility(View.VISIBLE); + } else { + if (myadapter == null) { + myadapter = new GosDeviceListAdapter(getContext(), foundDevicesList); + myadapter.setHandler(handler); + myadapter.setSpf(spf); + slvFoundDevices.setAdapter(myadapter); + } else { + myadapter.notifyDataSetChanged(); + } + llNoFoundDevices.setVisibility(View.GONE); + slvFoundDevices.setVisibility(View.VISIBLE); + } + if (boundDevicesList.isEmpty()) { + slvBoundDevices.setVisibility(View.GONE); + llNoBoundDevices.setVisibility(View.VISIBLE); + } else { + if (myadapter1 == null) { + myadapter1 = new GosDeviceListAdapter(getContext(), boundDevicesList); + myadapter1.setHandler(handler); + myadapter1.setSpf(spf); + slvBoundDevices.setAdapter(myadapter1); + } else { + if (slvBoundDevices.isSlided()) { + slvBoundDevices.slideBack(); + } + myadapter1.notifyDataSetChanged(); + } + llNoBoundDevices.setVisibility(View.GONE); + slvBoundDevices.setVisibility(View.VISIBLE); + } + } + + private void addDevice() { + if (GosDeploy.appConfig_Config_Softap()) { + if (!checkNetwork(getContext())) { + Toast.makeText(getContext(), R.string.network_error, 2000).show(); + return; + } + if (GosDeploy.appConfig_Config_Airlink()) { + final Dialog dialog = new AlertDialog.Builder(getContext(), R.style.alert_dialog_style) + .setView(new EditText(getContext())).create(); + dialog.setCanceledOnTouchOutside(true); + dialog.show(); + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_overflow); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llAirlink; + LinearLayout llSoftap; + llAirlink = (LinearLayout) window.findViewById(R.id.llAirlink); + llSoftap = (LinearLayout) window.findViewById(R.id.llSoftap); + llAirlink.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + intent = new Intent(getContext(), GosAirlinkChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + dialog.dismiss(); + } + }); + llSoftap.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + intent = new Intent(getContext(), GosChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + dialog.dismiss(); + } + }); + } else { + Intent intent = new Intent(getContext(), GosChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + } + } else { + if (GosDeploy.appConfig_Config_Airlink()) { + if (!checkNetwork(getContext())) { + Toast.makeText(getContext(), R.string.network_error, 2000).show(); + return; + } + Intent intent = new Intent(getContext(), GosAirlinkChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + } + } + } + + private void tryUserLoginAnonymous() { + threeSeconds = 3; + final Timer tsTimer = new Timer(); + tsTimer.schedule(new TimerTask() { + + @Override + public void run() { + threeSeconds--; + if (threeSeconds <= 0) { + tsTimer.cancel(); + handler.sendEmptyMessage(GETLIST); + } else { + if (loginStatus == 4) { + tsTimer.cancel(); + } + } + } + }, 1000, 1000); + } + + @Override + public void onRefresh() { + handler.sendEmptyMessageDelayed(PULL_TO_REFRESH, 2000); + } + + @Override + public void onDestroy() { + super.onDestroy(); + progressDialog = null; + } + + /** + * 设置ProgressDialog + */ + public void setProgressDialog() { + progressDialog = new ProgressDialog(getContext()); + String loadingText = getString(R.string.loadingtext); + progressDialog.setMessage(loadingText); + progressDialog.setCanceledOnTouchOutside(false); + } + + /** + * 检查网络连通性(工具方法) + * + * @param context + * @return + */ + public boolean checkNetwork(Context context) { + ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo net = conn.getActiveNetworkInfo(); + if (net != null && net.isConnected()) { + return true; + } + return false; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceModuleBaseActivity.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceModuleBaseActivity.java new file mode 100644 index 0000000..e84e3d5 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceModuleBaseActivity.java @@ -0,0 +1,210 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import com.gizwits.gizwifisdk.api.GizWifiCentralControlDevice; +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizWifiCentralControlDeviceListener; +import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener; +import com.gizwits.gizwifisdk.listener.GizWifiSDKListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +public class GosDeviceModuleBaseActivity extends GosBaseActivity { + + /** + * 设备列表 + */ + protected static List deviceslist = new ArrayList(); + + private GizWifiSDKListener gizWifiSDKListener = new GizWifiSDKListener() { + + /** 用于设备列表 */ + public void didDiscovered(GizWifiErrorCode result, List deviceList) { + GosDeviceModuleBaseActivity.this.didDiscovered(result, deviceList); + } + + /** 用于用户匿名登录 */ + public void didUserLogin(GizWifiErrorCode result, String uid, String token) { + GosDeviceModuleBaseActivity.this.didUserLogin(result, uid, token); + } + + /** 用于设备解绑 */ + public void didUnbindDevice(GizWifiErrorCode result, String did) { + GosDeviceModuleBaseActivity.this.didUnbindDevice(result, did); + } + + /** 用于设备绑定 */ + public void didBindDevice(GizWifiErrorCode result, String did) { + GosDeviceModuleBaseActivity.this.didBindDevice(result, did); + } + + /** 用于设备绑定(旧) */ + public void didBindDevice(int error, String errorMessage, String did) { + GosDeviceModuleBaseActivity.this.didBindDevice(error, errorMessage, did); + } + + ; + + /** 用于绑定推送 */ + public void didChannelIDBind(GizWifiErrorCode result) { + GosDeviceModuleBaseActivity.this.didChannelIDBind(result); + } + + }; + + /** + * 设备列表回调 + * + * @param result + * @param deviceList + */ + protected void didDiscovered(GizWifiErrorCode result, List deviceList) { + } + + /** + * 用户匿名登录回调 + * + * @param result + * @param uid + * @param token + */ + protected void didUserLogin(GizWifiErrorCode result, String uid, String token) { + } + + /** + * 设备解绑回调 + * + * @param result + * @param did + */ + protected void didUnbindDevice(GizWifiErrorCode result, String did) { + } + + /** + * 设备绑定回调(旧) + * + * @param error + * @param errorMessage + * @param did + */ + protected void didBindDevice(int error, String errorMessage, String did) { + } + + ; + + /** + * 设备绑定回调 + * + * @param result + * @param did + */ + protected void didBindDevice(GizWifiErrorCode result, String did) { + } + + /** + * 绑定推送回调 + * + * @param result + */ + protected void didChannelIDBind(GizWifiErrorCode result) { + } + + /** + * 设备监听 + */ + protected GizWifiDeviceListener gizWifiDeviceListener = new GizWifiDeviceListener() { + + // 用于设备订阅 + public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + GosDeviceModuleBaseActivity.this.didSetSubscribe(result, device, isSubscribed); + } + + ; + + }; + + protected GizWifiCentralControlDeviceListener gizWifisubDeviceListener = new GizWifiCentralControlDeviceListener() { + + // 用于设备订阅 + public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + GosDeviceModuleBaseActivity.this.didSetSubscribe(result, device, isSubscribed); + } + + //同步更新子设备列表 + @Override + public void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result, List subDeviceList) { + GosDeviceModuleBaseActivity.this.didUpdateSubDevices(device, result, subDeviceList); + } + + //设备网络状态变化通知 + @Override + public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + GosDeviceModuleBaseActivity.this.didUpdateNetStatus(device, netStatus); + } + + ; + + }; + + public GizWifiDeviceListener getGizWifiDeviceListener(GizWifiDevice device) { + + if (device.getProductType() == GizWifiDeviceType.GizDeviceNormal) { + return gizWifiDeviceListener; + } else { + return gizWifisubDeviceListener; + } + + } + + /** + * 设备网络状态变化通知 + * + * @param device + * @param netStatus + */ + protected void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + } + + /** + * 同步更新子设备列表 + * + * @param device + * @param result + * @param subDeviceList + */ + protected void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result, List subDeviceList) { + } + + + /** + * 设备订阅回调 + * + * @param result + * @param device + * @param isSubscribed + */ + protected void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + } + + @Override + protected void onResume() { + super.onResume(); + // 每次返回activity都要注册一次sdk监听器,保证sdk状态能正确回调 + GizWifiSDK.sharedInstance().setListener(gizWifiSDKListener); + } + + /** + * @param result + * @param cloudServiceInfo + */ + protected void didGetCurrentCloudService(GizWifiErrorCode result, + ConcurrentHashMap cloudServiceInfo) { + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceModuleBaseFragment.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceModuleBaseFragment.java new file mode 100644 index 0000000..335d0c9 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosDeviceModuleBaseFragment.java @@ -0,0 +1,214 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.util.Log; + +import com.gizwits.gizwifisdk.api.GizWifiCentralControlDevice; +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus; +import com.gizwits.gizwifisdk.enumration.GizWifiDeviceType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizWifiCentralControlDeviceListener; +import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener; +import com.gizwits.gizwifisdk.listener.GizWifiSDKListener; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +public class GosDeviceModuleBaseFragment extends GosBaseFragment { + + /** + * 设备列表 + */ + protected static List deviceslist = new ArrayList(); + + private GizWifiSDKListener gizWifiSDKListener = new GizWifiSDKListener() { + + /** 用于设备列表 */ + public void didDiscovered(GizWifiErrorCode result, List deviceList) { + GosDeviceModuleBaseFragment.this.didDiscovered(result, deviceList); + Log.e("GosDeviceModuleBaseFragment", "didDiscovered=====----: 更新数据"); + } + + /** 用于用户匿名登录 */ + public void didUserLogin(GizWifiErrorCode result, String uid, String token) { + GosDeviceModuleBaseFragment.this.didUserLogin(result, uid, token); + } + + /** 用于设备解绑 */ + public void didUnbindDevice(GizWifiErrorCode result, String did) { + GosDeviceModuleBaseFragment.this.didUnbindDevice(result, did); + } + + /** 用于设备绑定 */ + public void didBindDevice(GizWifiErrorCode result, String did) { + GosDeviceModuleBaseFragment.this.didBindDevice(result, did); + } + + /** 用于设备绑定(旧) */ + public void didBindDevice(int error, String errorMessage, String did) { + GosDeviceModuleBaseFragment.this.didBindDevice(error, errorMessage, did); + } + + ; + + /** 用于绑定推送 */ + public void didChannelIDBind(GizWifiErrorCode result) { + GosDeviceModuleBaseFragment.this.didChannelIDBind(result); + } + + }; + + /** + * 设备列表回调 + * + * @param result + * @param deviceList + */ + protected void didDiscovered(GizWifiErrorCode result, List deviceList) { + } + + /** + * 用户匿名登录回调 + * + * @param result + * @param uid + * @param token + */ + protected void didUserLogin(GizWifiErrorCode result, String uid, String token) { + } + + /** + * 设备解绑回调 + * + * @param result + * @param did + */ + protected void didUnbindDevice(GizWifiErrorCode result, String did) { + } + + /** + * 设备绑定回调(旧) + * + * @param error + * @param errorMessage + * @param did + */ + protected void didBindDevice(int error, String errorMessage, String did) { + } + + ; + + /** + * 设备绑定回调 + * + * @param result + * @param did + */ + protected void didBindDevice(GizWifiErrorCode result, String did) { + } + + /** + * 绑定推送回调 + * + * @param result + */ + protected void didChannelIDBind(GizWifiErrorCode result) { + } + + /** + * 设备监听 + */ + protected GizWifiDeviceListener gizWifiDeviceListener = new GizWifiDeviceListener() { + + // 用于设备订阅 + public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + GosDeviceModuleBaseFragment.this.didSetSubscribe(result, device, isSubscribed); + } + + ; + + }; + + protected GizWifiCentralControlDeviceListener gizWifisubDeviceListener = new GizWifiCentralControlDeviceListener() { + + // 用于设备订阅 + public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + GosDeviceModuleBaseFragment.this.didSetSubscribe(result, device, isSubscribed); + } + + //同步更新子设备列表 + @Override + public void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result, List subDeviceList) { + GosDeviceModuleBaseFragment.this.didUpdateSubDevices(device, result, subDeviceList); + } + + //设备网络状态变化通知 + @Override + public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + GosDeviceModuleBaseFragment.this.didUpdateNetStatus(device, netStatus); + } + + ; + + }; + + public GizWifiDeviceListener getGizWifiDeviceListener(GizWifiDevice device) { + + if (device.getProductType() == GizWifiDeviceType.GizDeviceNormal) { + return gizWifiDeviceListener; + } else { + return gizWifisubDeviceListener; + } + + } + + /** + * 设备网络状态变化通知 + * + * @param device + * @param netStatus + */ + protected void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) { + } + + /** + * 同步更新子设备列表 + * + * @param device + * @param result + * @param subDeviceList + */ + protected void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result, List subDeviceList) { + } + + + /** + * 设备订阅回调 + * + * @param result + * @param device + * @param isSubscribed + */ + protected void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) { + } + + @Override + public void onResume() { + super.onResume(); + // 每次返回activity都要注册一次sdk监听器,保证sdk状态能正确回调 + GizWifiSDK.sharedInstance().setListener(gizWifiSDKListener); + Log.e("TAG", "GosDeviceModuleBaseFragment ----onResume: ---"); + } + + + /** + * @param result + * @param cloudServiceInfo + */ + protected void didGetCurrentCloudService(GizWifiErrorCode result, + ConcurrentHashMap cloudServiceInfo) { + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosMainActivity.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosMainActivity.java new file mode 100644 index 0000000..a6ce368 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosMainActivity.java @@ -0,0 +1,403 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.ColorStateList; +import android.graphics.PorterDuff; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.support.design.widget.BottomNavigationView; +import android.support.v4.app.ActivityCompat; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentPagerAdapter; +import android.support.v4.view.ViewPager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.style.ForegroundColorSpan; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.CommonModule.NoScrollViewPager; +import com.gizwits.opensource.appkit.CommonModule.TipsDialog; +//config-all-start +// config_airlink-false-start +import com.gizwits.opensource.appkit.ConfigModule.GosAirlinkChooseDeviceWorkWiFiActivity; +// config_airlink-false-end +//config_softap-false-start +import com.gizwits.opensource.appkit.ConfigModule.GosChooseDeviceWorkWiFiActivity; +//config_softap-false-end +//config-all-end +//push-all-start +import com.gizwits.opensource.appkit.PushModule.GosPushManager; +//push-all-end + +import com.gizwits.opensource.appkit.utils.ToolUtils; + +import java.util.Timer; +import java.util.TimerTask; + +import zxing.CaptureActivity; + + +public class GosMainActivity extends GosDeviceModuleBaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener { + + Context context = null; + @SuppressWarnings("deprecation") + + private int viewPagerSelected = 0; + private Intent intent; + + public static Activity instance = null; + private BottomNavigationView navigation; + private NoScrollViewPager viewPager; + + private static final int REQUEST_EXTERNAL_STORAGE = 22; + private static String[] PERMISSIONS_STORAGE = {"android.permission.CAMERA"}; + + @Override + public boolean onNavigationItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.navigation_device: + if (GosDeploy.appConfig_BindDevice_Qrcode()) { + int color = GosDeploy.appConfig_Contrast(); + final Drawable upArrow = getResources().getDrawable(R.drawable.common_qrcode_button); + upArrow.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); + mToolbar.setNavigationIcon(upArrow); + SpannableString ssTitle = new SpannableString(this.getString(R.string.devicelist_title)); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvTitle.setText(ssTitle); + } else { + mToolbar.setNavigationIcon(null); + SpannableString ssTitle = new SpannableString(this.getString(R.string.devicelist_title)); + ssTitle.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvTitle.setText(ssTitle); + } + break; + case R.id.navigation_message: + mToolbar.setNavigationIcon(null); + SpannableString ssTitle1 = new SpannableString(this.getString(R.string.messagecenter)); + ssTitle1.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle1.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvTitle.setText(ssTitle1); + break; + case R.id.navigation_user: + mToolbar.setNavigationIcon(null); + SpannableString ssTitle2 = new SpannableString(this.getString(R.string.personal_center)); + ssTitle2.setSpan(new ForegroundColorSpan(GosDeploy.appConfig_Contrast()), 0, ssTitle2.length(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + tvTitle.setText(ssTitle2); + break; + } + viewPager.setCurrentItem(TabFragment.form(item.getItemId()).ordinal()); + return true; + } + + private enum TabFragment { + + device(R.id.navigation_device, GosDeviceListFragment.class), + message(R.id.navigation_message, MessageCenterFragment.class), + user(R.id.navigation_user, GosSettiingsFragment.class); + + private int menuId; + private Class mClass; + private Fragment fragment; + + TabFragment(int menuId, Class mClass) { + this.menuId = menuId; + this.mClass = mClass; + } + + private Fragment fragment() { + if (fragment == null) { + try { + fragment = mClass.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + fragment = new Fragment(); + } + } + return fragment; + } + + public static TabFragment form(int menuId) { + for (TabFragment fragment : values()) { + if (fragment.menuId == menuId) { + return fragment; + } + } + return user; + } + + public static void onDestroy() { + for (TabFragment fragment : values()) { + fragment.fragment = null; + } + } + } + + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_main); + context = GosMainActivity.this; + if (GosDeploy.appConfig_BindDevice_Qrcode()) { + setToolBar(true, R.string.devicelist_title); + } else { + setToolBar(false, R.string.devicelist_title); + } + initView(); + } + + private void initView() { + navigation = (BottomNavigationView) findViewById(R.id.navigation); + setThemeColor(GosDeploy.appConfig_Background()); + navigation.setOnNavigationItemSelectedListener(this); + viewPager = (NoScrollViewPager) findViewById(R.id.content); + viewPager.setNoScroll(true); + viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { + @Override + public Fragment getItem(int position) { + return TabFragment.values()[position].fragment(); + } + + @Override + public int getCount() { + return TabFragment.values().length; + } + }); + + viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { + @Override + public void onPageSelected(int position) { + super.onPageSelected(position); + viewPagerSelected = position; + supportInvalidateOptionsMenu(); + navigation.setSelectedItemId(TabFragment.values()[position].menuId); + } + }); + } + + //config-all-start + @Override + public boolean onCreateOptionsMenu(Menu menu) { + switch (viewPagerSelected) { + case 0: + if (GosDeploy.appConfig_Config_Airlink()) { + if (GosDeploy.appConfig_Config_Softap()) { + getMenuInflater().inflate(R.menu.gosdeviceconfig, menu); + } else { + getMenuInflater().inflate(R.menu.gosnull, menu); + MenuItem menuItem = menu.findItem(R.id.add); + menuItem.setIcon(ToolUtils.editIcon(getResources(), R.drawable.deviceonboarding_add)); + } + } else { + if (GosDeploy.appConfig_Config_Softap()) { + getMenuInflater().inflate(R.menu.gosnull, menu); + MenuItem menuItem = menu.findItem(R.id.add); + menuItem.setIcon(ToolUtils.editIcon(getResources(), R.drawable.deviceonboarding_add)); + } + } + break; + } + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + //bindDevice_qrcode-false-start + case android.R.id.home: + if (GosDeploy.appConfig_BindDevice_Qrcode()) { + int permission = ActivityCompat.checkSelfPermission(GosMainActivity.this, + "android.permission.CAMERA"); + if (permission != PackageManager.PERMISSION_GRANTED) { + try { + // 没有写的权限,去申请写的权限,会弹出对话框 + ActivityCompat.requestPermissions(GosMainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + intent = new Intent(GosMainActivity.this, CaptureActivity.class); + startActivity(intent); + overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); + } + } + break; + //bindDevice_qrcode-false-end + //config_airlink-false-start config_softap-false-start + case R.id.airlink_config: + if (!checkNetwork(GosMainActivity.this)) { + Toast.makeText(GosMainActivity.this, R.string.network_error, 2000).show(); + } else { + intent = new Intent(GosMainActivity.this, GosAirlinkChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + } + break; + case R.id.softap_config: + if (!checkNetwork(GosMainActivity.this)) { + Toast.makeText(GosMainActivity.this, R.string.network_error, 2000).show(); + } else { + intent = new Intent(GosMainActivity.this, GosChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + } + break; + //config_softap-false-end config_airlink-false-end + case R.id.add: + if (GosDeploy.appConfig_Config_Airlink()) { + if (!checkNetwork(GosMainActivity.this)) { + Toast.makeText(GosMainActivity.this, R.string.network_error, 2000).show(); + } else { + intent = new Intent(GosMainActivity.this, GosAirlinkChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + } + } + if (GosDeploy.appConfig_Config_Softap()) { + if (!checkNetwork(GosMainActivity.this)) { + Toast.makeText(GosMainActivity.this, R.string.network_error, 2000).show(); + } else { + intent = new Intent(GosMainActivity.this, GosChooseDeviceWorkWiFiActivity.class); + startActivity(intent); + } + } + break; + } + return super.onOptionsItemSelected(item); + } + //config-all-end + + //bindDevice_qrcode-false-start + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + if (GosDeploy.appConfig_BindDevice_Qrcode()) { + if (requestCode == 22) { + intent = new Intent(GosMainActivity.this, CaptureActivity.class); + startActivity(intent); + overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); + } + } + } + //bindDevice_qrcode-false-end + + + /** + * 菜单、返回键响应 + */ + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + exitBy2Click(); // 调用双击退出函数 + } + return false; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == 666) { + finish(); + } else if (resultCode == 98765) { + TipsDialog dialog = new TipsDialog(GosMainActivity.this, + getResources().getString(R.string.devicedisconnected)); + dialog.show(); + } + } + + + public void exitBy2Click() { + Timer tExit = null; + if (isExit == false) { + isExit = true; // 准备退出; + String doubleClick; + if (!TextUtils.isEmpty(spf.getString("UserName", "")) + && !TextUtils.isEmpty(spf.getString("PassWord", ""))) { + doubleClick = (String) getText(R.string.doubleclick_logout); + } else { + if (getIntent().getBooleanExtra("ThredLogin", false)) { + doubleClick = (String) getText(R.string.doubleclick_logout); + } else { + doubleClick = (String) getText(R.string.doubleclick_back); + } + } + + Toast.makeText(this, doubleClick, 2000).show(); + tExit = new Timer(); + tExit.schedule(new TimerTask() { + @Override + public void run() { + isExit = false; // 取消退出 + } + }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务 + + } else { + logoutToClean(); + } + } + + /** + * 注销函数 + */ + void logoutToClean() { + spf.edit().putString("UserName", "").commit(); + spf.edit().putString("PassWord", "").commit(); + spf.edit().putString("Uid", "").commit(); + //push-all-start + GosPushManager.pushUnBindService(spf.getString("Token", "")); + //push-all-end + spf.edit().putString("Token", "").commit(); + + finish(); + if (GosDeviceListFragment.loginStatus == 1) { + GosDeviceListFragment.loginStatus = 0; + } else { + GosDeviceListFragment.loginStatus = 4; + } + } + + /** + * 双击退出函数 + */ + private static Boolean isExit = false; + + /** + * 更改主题 + * + * @param colorPrimary 标题栏背景颜色 + */ + private void setThemeColor(int colorPrimary) { + final Drawable add = getResources().getDrawable(R.drawable.deviceonboarding_add); + int color = GosDeploy.appConfig_Contrast(); + add.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); + mToolbar.setOverflowIcon(add); + // bindDevice_qrcode-false-start + if (GosDeploy.appConfig_BindDevice_Qrcode()) { + final Drawable upArrow = getResources().getDrawable(R.drawable.common_qrcode_button); + upArrow.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); + mToolbar.setNavigationIcon(upArrow); + } + // bindDevice_qrcode-false-end + //动态设置底部导航栏的颜色 + int[][] states = new int[][]{ + new int[]{-android.R.attr.state_checked}, + new int[]{android.R.attr.state_checked} + }; + + int[] colors = new int[]{ToolUtils.editTextAlpha(), color}; + ColorStateList csl = new ColorStateList(states, colors); + // 背景颜色 + navigation.setBackgroundColor(colorPrimary); + // 文字颜色 + navigation.setItemIconTintList(csl); + // 图片颜色 + navigation.setItemTextColor(csl); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosMessageHandler.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosMessageHandler.java new file mode 100644 index 0000000..41fcbbf --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosMessageHandler.java @@ -0,0 +1,108 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.net.wifi.ScanResult; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.os.Message; +import android.widget.RemoteViews; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.utils.NetUtils; + +import java.util.ArrayList; +import java.util.List; + +public class GosMessageHandler { + + NotificationManager nm; + + protected static final int SHOWDIALOG = 999; + + private Context mcContext; + + private ArrayList newDeviceList = new ArrayList(); + + private Handler mainHandler; + // 做一个单例 + private static GosMessageHandler mInstance = new GosMessageHandler(); + + public static GosMessageHandler getSingleInstance() { + return mInstance; + } + + public void SetHandler(Handler handler) { + this.mainHandler = handler; + } + + public void StartLooperWifi(Context context) { + this.mcContext = context; + HandlerThread looperwifi = new HandlerThread("looperwifi"); + looperwifi.start(); + looper = new MyLooperHandler(looperwifi.getLooper()); + looper.post(mRunnable); + } + + class MyLooperHandler extends Handler { + public MyLooperHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + } + + } + + /** + * 子线程实现 + */ + private Runnable mRunnable = new Runnable() { + + public void run() { + if (mcContext == null) { + return; + } + newDeviceList.clear(); + List currentWifiScanResult = NetUtils + .getCurrentWifiScanResult(mcContext); + GosConstant.ssidList = currentWifiScanResult; + int flog = 0; + if (currentWifiScanResult != null) { + for (ScanResult scanResult : currentWifiScanResult) { + String ssid = scanResult.SSID; + // 获取系统的NotificationManager服务 + nm = (NotificationManager) mcContext + .getSystemService(Context.NOTIFICATION_SERVICE); + if (ssid.contains(GosBaseActivity.SoftAP_Start) + && ssid.length() > GosBaseActivity.SoftAP_Start.length() + && !newDeviceList.toString().contains(ssid)) { + newDeviceList.add(ssid); + flog++; + } + } + } + + if (mainHandler != null && newDeviceList.size() > 0) { + mainHandler.sendEmptyMessage(SHOWDIALOG); + } + + looper.postDelayed(mRunnable, 2000); + } + }; + private MyLooperHandler looper; + + + public ArrayList getNewDeviceList() { + return newDeviceList; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosSettiingsFragment.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosSettiingsFragment.java new file mode 100644 index 0000000..81ca79f --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/GosSettiingsFragment.java @@ -0,0 +1,136 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.SettingsModule.GosAboutActivity; +import com.gizwits.opensource.appkit.UserModule.GosUserManager; +import com.gizwits.opensource.appkit.sharingdevice.SharedDeviceListAcitivity; + +public class GosSettiingsFragment extends GosBaseFragment implements OnClickListener { + + private static final int SETTINGS = 123; + /** + * The ll About + */ + private LinearLayout llAbout; + + /** + * The Intent + */ + Intent intent; + + private LinearLayout usermanager; + + private RelativeLayout lllogin; + private LinearLayout llDeviceShared; + + private TextView phoneusername; + private View allView; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + allView = inflater.inflate(R.layout.activity_gos_settings, container, false); + initView(); + initEvent(); + return allView; + } + + private void initView() { + llAbout = (LinearLayout) allView.findViewById(R.id.llAbout); + usermanager = (LinearLayout) allView.findViewById(R.id.usermanager); + lllogin = (RelativeLayout) allView.findViewById(R.id.lllogin); + phoneusername = (TextView) allView.findViewById(R.id.phoneusername); + llDeviceShared = (LinearLayout) allView.findViewById(R.id.deviceshared); + } + + private void initEvent() { + llAbout.setOnClickListener(this); + usermanager.setOnClickListener(this); + lllogin.setOnClickListener(this); + llDeviceShared.setOnClickListener(this); + + if (!TextUtils.isEmpty(spf.getString("UserName", "")) && !TextUtils.isEmpty(spf.getString("PassWord", ""))) { + usermanager.setVisibility(View.VISIBLE); + lllogin.setVisibility(View.GONE); + phoneusername.setText(spf.getString("UserName", "")); + } else if (TextUtils.isEmpty(spf.getString("UserName", "")) && TextUtils.isEmpty(spf.getString("PassWord", "")) + && !TextUtils.isEmpty(spf.getString("thirdUid", ""))) { + usermanager.setVisibility(View.VISIBLE); + String uid = spf.getString("thirdUid", ""); + + lllogin.setVisibility(View.GONE); + String myuid = uid.substring(0, 2) + "***" + uid.substring(uid.length() - 4, uid.length()); + phoneusername.setText(myuid); + } else { + usermanager.setVisibility(View.GONE); + lllogin.setVisibility(View.VISIBLE); + } + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.llAbout: + intent = new Intent(getContext(), GosAboutActivity.class); + startActivity(intent); + llAbout.setEnabled(false); + llAbout.postDelayed(new Runnable() { + @Override + public void run() { + llAbout.setEnabled(true); + } + }, 1000); + break; + + case R.id.usermanager: + intent = null; + if (intent == null) { + intent = new Intent(getContext(), GosUserManager.class); + } + startActivityForResult(intent, SETTINGS); + usermanager.setEnabled(false); + usermanager.postDelayed(new Runnable() { + @Override + public void run() { + usermanager.setEnabled(true); + } + }, 1000); + break; + case R.id.lllogin: + lllogin.setEnabled(false); + lllogin.postDelayed(new Runnable() { + @Override + public void run() { + lllogin.setEnabled(true); + } + }, 1000); + getActivity().finish(); + break; + case R.id.deviceshared: + Intent deviceshared1 = new Intent(getContext(), SharedDeviceListAcitivity.class); + startActivity(deviceshared1); + llDeviceShared.setEnabled(false); + llDeviceShared.postDelayed(new Runnable() { + @Override + public void run() { + llDeviceShared.setEnabled(true); + } + }, 1000); + break; + default: + break; + } + + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/DeviceModule/MessageCenterFragment.java b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/MessageCenterFragment.java new file mode 100644 index 0000000..6b309be --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/DeviceModule/MessageCenterFragment.java @@ -0,0 +1,136 @@ +package com.gizwits.opensource.appkit.DeviceModule; + +import android.content.Intent; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizMessage; +import com.gizwits.gizwifisdk.enumration.GizMessageStatus; +import com.gizwits.gizwifisdk.enumration.GizMessageType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.sharingdevice.MsgNoticeActivity; +import com.gizwits.opensource.appkit.sharingdevice.deviceSharedMessageActivity; + +import java.util.List; + +//personalCenter_deviceSharing-false-start +//personalCenter_deviceSharing-false-end + +public class MessageCenterFragment extends GosBaseFragment { + + + private LinearLayout llGizwitsmes; + //personalCenter_deviceSharing-false-start + private View redpoint; + private LinearLayout llDevicesShared; + //personalCenter_deviceSharing-false-end + private View allView; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + allView = inflater.inflate(R.layout.activity_gos_message, container, false); + initView(); + initEvent(); + return allView; + } + + //界面可见时再加载数据 + @Override + public void setUserVisibleHint(boolean isVisibleToUser) { + super.setUserVisibleHint(isVisibleToUser); + if (isVisibleToUser) { + //请求网络数据 + //personalCenter_deviceSharing-false-start + String token = spf.getString("Token", ""); + GizDeviceSharing.queryMessageList(token, GizMessageType.GizMessageSharing); + //GizDeviceSharing.queryMessageList(token, GizMessageType.GizMessageSystem); + + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didQueryMessageList(GizWifiErrorCode result, List messageList) { + super.didQueryMessageList(result, messageList); + + if (messageList.size() > 0) { + isShowRedPoint(messageList); + } else { + redpoint.setVisibility(View.GONE); + } + + if (result.ordinal() != 0) { + Toast.makeText(getContext(), toastError(result), 2).show(); + } + } + }); + //personalCenter_deviceSharing-false-end + } + } + + //personalCenter_deviceSharing-false-start + private void isShowRedPoint(List messageList) { + + boolean isshow = false; + redpoint.setVisibility(View.GONE); + for (int i = 0; i < messageList.size(); i++) { + + GizMessage gizMessage = messageList.get(i); + GizMessageStatus status = gizMessage.getStatus(); + if (status.ordinal() == 0) { + isshow = true; + redpoint.setVisibility(View.VISIBLE); + } + } + } + //personalCenter_deviceSharing-false-end + + private void initView() { + llGizwitsmes = (LinearLayout) allView.findViewById(R.id.gizwitsmes); + //personalCenter_deviceSharing-false-start + // 判断当前的view 是否需要显示这个红点 + redpoint = allView.findViewById(R.id.redpoint); + llDevicesShared = (LinearLayout) allView.findViewById(R.id.deviceshared); + //personalCenter_deviceSharing-false-end + } + + private void initEvent() { + llGizwitsmes.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + // 跳转到机智云公告页面 + Intent intent = new Intent(getContext(), MsgNoticeActivity.class); + startActivity(intent); + llGizwitsmes.setEnabled(false); + llGizwitsmes.postDelayed(new Runnable() { + @Override + public void run() { + llGizwitsmes.setEnabled(true); + } + }, 1000); + } + }); + //personalCenter_deviceSharing-false-start + llDevicesShared.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent tent = new Intent(getContext(), deviceSharedMessageActivity.class); + startActivity(tent); + llDevicesShared.setEnabled(false); + llDevicesShared.postDelayed(new Runnable() { + @Override + public void run() { + llDevicesShared.setEnabled(true); + } + }, 1000); + } + }); + //personalCenter_deviceSharing-false-end + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/GosApplication.java b/src/main/java/com/gizwits/opensource/appkit/GosApplication.java new file mode 100644 index 0000000..e2497d1 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/GosApplication.java @@ -0,0 +1,13 @@ +package com.gizwits.opensource.appkit; + +import android.app.Application; +public class GosApplication extends Application { + + public static int flag = 0; + + public void onCreate() { + super.onCreate(); + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/MessageCenter.java b/src/main/java/com/gizwits/opensource/appkit/MessageCenter.java new file mode 100644 index 0000000..b17da1a --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/MessageCenter.java @@ -0,0 +1,112 @@ +package com.gizwits.opensource.appkit; + +import android.content.Context; +import android.os.Handler; +import android.text.TextUtils; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizLogPrintLevel; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +public class MessageCenter { + private static MessageCenter mCenter; + int flag = 0; + + GosDeploy gosDeploy; + + private int SETCLOUD = 1111; + + private MessageCenter(Context c) { + if (mCenter == null) { + init(c); + } + } + + private void init(Context c) { + gosDeploy = new GosDeploy(c); + //config-all-start + if (GosDeploy.appConfig_UseOnboardingDeploy()) { + if (GosDeploy.appConfig_OnboardingBind()) { + GosConstant.mNew = 3; + } else { + GosConstant.mNew = 2; + } + } else { + if (GosDeploy.appConfig_OnboardingBind()) { + GosConstant.mNew = 1; + } else { + GosConstant.mNew = 0; + } + } + //config-all-end + String AppID = GosDeploy.appConfig_GizwitsInfoAppID(); + String AppSecret = GosDeploy.appConfig_GizwitsInfoAppSecret(); + List> productInfoList = GosDeploy.appConfig_ProductInfoList(); + if (productInfoList.size() == 0) { + productInfoList = null; + } + + if (AppID == null || AppSecret == null || TextUtils.isEmpty(AppID) || AppID.contains("BeJson") + || TextUtils.isEmpty(AppSecret) || AppSecret.contains("BeJson") + || AppID.length() != 32 || AppSecret.length() != 32) { + String AppID_Toast = c.getString(R.string.AppID_Toast); + if (flag == 0) { + Toast.makeText(c, AppID_Toast, Toast.LENGTH_LONG).show(); + } + flag++; + } else { + // 启动SDK + ConcurrentHashMap serverMap = new ConcurrentHashMap(); + ConcurrentHashMap appInfo = new ConcurrentHashMap(); + appInfo.put("appId", AppID); + appInfo.put("appSecret", AppSecret); + + String api = GosDeploy.appConfig_CloudServiceApi(); + String site = GosDeploy.appConfig_CloudServiceSite(); + String push = GosDeploy.appConfig_CloudServicePush(); + Pattern pattern = Pattern.compile("(^[a-zA-Z0-9\\-]{1,}\\.[a-zA-Z0-9]{1,}\\.[a-zA-Z0-9]{1,}\\:(\\d){1,}\\&(\\d){1,}$)|(^[a-zA-Z0-9\\-]{1,}\\.[a-zA-Z0-9]{1,}\\.[a-zA-Z0-9]{1,}$)"); + Pattern pattern1 = Pattern.compile("(^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}\\:(\\d){1,}\\&(\\d){1,}$)|(^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$)"); + if (api != null) { + if (pattern.matcher(api).matches() || pattern1.matcher(api).matches()) { + serverMap.put("openAPIInfo", api); + if (site != null) { + serverMap.put("siteInfo", site); + } + if (push != null && !push.isEmpty()) { + serverMap.put("pushInfo", GosDeploy.appConfig_CloudServicePush()); + } + GizWifiSDK.sharedInstance().startWithAppInfo(c, appInfo, productInfoList, serverMap, false); + } else { + GizWifiSDK.sharedInstance().startWithAppInfo(c, appInfo, + productInfoList, null, false); + } + } else { + GizWifiSDK.sharedInstance().startWithAppInfo(c, appInfo, + productInfoList, null, false); + } + } + hand.sendEmptyMessageDelayed(SETCLOUD, 3000); + } + + public static MessageCenter getInstance(Context c) { + if (mCenter == null) { + mCenter = new MessageCenter(c); + } + return mCenter; + } + + Handler hand = new Handler() { + public void handleMessage(android.os.Message msg) { + GizWifiSDK.sharedInstance().setLogLevel( + GizLogPrintLevel.GizLogPrintAll); + + } + }; + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/PushModule/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/PushModule/.DS_Store new file mode 100644 index 0000000..c657f76 Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/PushModule/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/PushModule/BaiDuPushReceiver.java b/src/main/java/com/gizwits/opensource/appkit/PushModule/BaiDuPushReceiver.java new file mode 100644 index 0000000..97b27e0 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/PushModule/BaiDuPushReceiver.java @@ -0,0 +1,67 @@ +package com.gizwits.opensource.appkit.PushModule; + +import android.content.Context; +import android.util.Log; + +import com.baidu.android.pushservice.PushMessageReceiver; + +import java.util.List; + +public class BaiDuPushReceiver extends PushMessageReceiver { + + // BaiDuPush_Channel_ID(此处需要在百度推送的Receiver里赋值) + public static String BaiDuPush_Channel_ID; + + @Override + public void onBind(Context arg0, int arg1, String arg2, String arg3, String arg4, String arg5) { + // TODO Auto-generated method stub + BaiDuPush_Channel_ID = arg4; + Log.i("Apptest", BaiDuPush_Channel_ID + "---"); + } + + @Override + public void onDelTags(Context arg0, int arg1, List arg2, List arg3, String arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void onListTags(Context arg0, int arg1, List arg2, String arg3) { + // TODO Auto-generated method stub + + } + + @Override + public void onMessage(Context arg0, String arg1, String arg2) { + // TODO Auto-generated method stub + + } + + @Override + public void onNotificationArrived(Context arg0, String arg1, String arg2, String arg3) { + // TODO Auto-generated method stub + String notifyString = "通知到达 onNotificationArrived title=\"" + arg1 + + "\" description=\"" + arg2 + "\" customContent=" + + arg3; + Log.i(TAG, notifyString); + } + + @Override + public void onNotificationClicked(Context arg0, String arg1, String arg2, String arg3) { + // TODO Auto-generated method stub + + } + + @Override + public void onSetTags(Context arg0, int arg1, List arg2, List arg3, String arg4) { + // TODO Auto-generated method stub + + } + + @Override + public void onUnbind(Context arg0, int arg1, String arg2) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/PushModule/GosPushManager.java b/src/main/java/com/gizwits/opensource/appkit/PushModule/GosPushManager.java new file mode 100644 index 0000000..f4d12d5 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/PushModule/GosPushManager.java @@ -0,0 +1,136 @@ +package com.gizwits.opensource.appkit.PushModule; + +import android.content.Context; +import android.text.TextUtils; +import android.util.Log; +//push_baidu-false-start +import com.baidu.android.pushservice.PushConstants; +import com.baidu.android.pushservice.PushManager; +import com.baidu.android.pushservice.PushSettings; +//push_baidu-false-end +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizPushType; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +import java.util.Set; +//push_jiguang-false-start +import cn.jpush.android.api.JPushInterface; +import cn.jpush.android.api.TagAliasCallback; +//push_jiguang-false-end + + +public class GosPushManager { + + static GizPushType gizPushType; + + static Context context; + + public GosPushManager(int PushType, Context context) { + super(); + GosPushManager.context = context; + //push_jiguang-false-start + if (PushType == 1) { + GosPushManager.gizPushType = GizPushType.GizPushJiGuang; + jPush(); + } + //push_jiguang-false-end + //push_baidu-false-start + if (PushType == 2) { + GosPushManager.gizPushType = GizPushType.GizPushBaiDu; + bDPush(); + } + //push_baidu-false-end + } + + /** + * Channel_ID + */ + public static String Channel_ID; + + //push_jiguang-false-start + + /** + * 此方法完成了初始化JPush SDK等功能 但仍需在MainActivity的onResume和onPause添加相应方法 + * JPushInterface.onResume(context); JPushInterface.onPause(context); + */ + public void jPush() { + // 设置JPush调试模式 + JPushInterface.setDebugMode(true); + // 初始化JPushSDK + JPushInterface.init(context); + } + //push_jiguang-false-end + + //push_baidu-false-start + public void bDPush() { + final String BDPushAppKey = GosDeploy.appConfig_BpushAppKey(); + if (BDPushAppKey != null) { + if (TextUtils.isEmpty(BDPushAppKey) || BDPushAppKey.contains("your_bpush_api_key")) { + GosBaseActivity.noIDAlert(context, R.string.BDPushAppID_Toast); + } else { + PushManager.startWork(context, PushConstants.LOGIN_TYPE_API_KEY, BDPushAppKey); + PushSettings.enableDebugMode(context, true); + } + } + } + //push_baidu-false-end + + /** + * 向云端绑定推送 + * + * @param userId + * @param token + */ + public static void pushBindService(String userId, String token) { + //push_jiguang-false-start + if (GizPushType.GizPushJiGuang == gizPushType) { + // 获取JPush的RegistrationID,即Channel_ID + Channel_ID = JPushInterface.getRegistrationID(context); + // 设定JPush类型 + JPushInterface.setAlias(context, Channel_ID, new TagAliasCallback() { + @Override + public void gotResult(int arg0, String arg1, Set arg2) { + if (arg0 == 0) { + Log.i("Apptest", "Alias: " + arg1); + } else { + Log.i("Apptest", "Result: " + arg0); + } + } + }); + } + //push_jiguang-false-end + //push_baidu-false-start + if (GizPushType.GizPushBaiDu == gizPushType) { + // 获取BDPush的Channel_ID + Channel_ID = BaiDuPushReceiver.BaiDuPush_Channel_ID; + Log.e("Manager", "pushBindService----: " + Channel_ID); + } + //push_baidu-false-end + // TODO 绑定推送 + GizWifiSDK.sharedInstance().channelIDBind(token, Channel_ID, userId, gizPushType); + } + + public static void pushUnBindService(String token) { + if (token.isEmpty()) { + return; + } + //push_jiguang-false-start + if (GizPushType.GizPushJiGuang == gizPushType) { + // 获取JPush的RegistrationID,即Channel_ID + Channel_ID = JPushInterface.getRegistrationID(context); + } + //push_jiguang-false-end + //push_baidu-false-start + if (GizPushType.GizPushBaiDu == gizPushType) { + // 获取BDPush的Channel_ID + Channel_ID = BaiDuPushReceiver.BaiDuPush_Channel_ID; + } + //push_baidu-false-end + // TODO 绑定推送 + //Log.i("Apptest", Channel_ID + "\n" + gizPushType.toString() + "\n" + token); + GizWifiSDK.sharedInstance().channelIDUnBind(token, Channel_ID); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/PushModule/JPushReceiver.java b/src/main/java/com/gizwits/opensource/appkit/PushModule/JPushReceiver.java new file mode 100644 index 0000000..e775c21 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/PushModule/JPushReceiver.java @@ -0,0 +1,125 @@ +package com.gizwits.opensource.appkit.PushModule; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Iterator; + +import cn.jpush.android.api.JPushInterface; + +public class JPushReceiver extends BroadcastReceiver { + + private static final String TAG = "JPushReceiver"; + + @Override + public void onReceive(Context context, Intent intent) { + + try { + Bundle bundle = intent.getExtras(); + Log.i(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle)); + + if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { + String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID); + Log.i(TAG, "[MyReceiver] 接收Registration Id : " + regId); + //send the Registration Id to your server... + + } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { + Log.i(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)); + //processCustomMessage(context, bundle); + + } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { + Log.i(TAG, "[MyReceiver] 接收到推送下来的通知"); + int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); + Log.i(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId); + String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE); + String content = bundle.getString(JPushInterface.EXTRA_ALERT); + Log.i(TAG, "Title 标题:: " + title + " " + "Content : 内容:" + content); + } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { +// Log.d(TAG, "[MyReceiver] 用户点击打开了通知"); +// +// //打开自定义的Activity +// Intent i = new Intent(context, TestActivity.class); +// i.putExtras(bundle); +// //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); +// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP ); +// context.startActivity(i); + + } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) { + Log.i(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)); + //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等.. + + } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) { + boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false); + Log.i(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected); + } else { + Log.i(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction()); + } + } catch (Exception e) { + + } + } + + // 打印所有的 intent extra 数据 + private static String printBundle(Bundle bundle) { + StringBuilder sb = new StringBuilder(); + for (String key : bundle.keySet()) { + if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { + sb.append("\nkey:" + key + ", value:" + bundle.getInt(key)); + } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) { + sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key)); + } else if (key.equals(JPushInterface.EXTRA_EXTRA)) { + if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) { + Log.i(TAG, "This message has no Extra data"); + continue; + } + + try { + JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA)); + Iterator it = json.keys(); + + while (it.hasNext()) { + String myKey = it.next(); + sb.append("\nkey:" + key + ", value: [" + + myKey + " - " + json.optString(myKey) + "]"); + } + } catch (JSONException e) { + Log.i(TAG, "Get message extra JSON error!"); + } + + } else { + sb.append("\nkey:" + key + ", value:" + bundle.getString(key)); + } + } + return sb.toString(); + } + + //send msg to MainActivity +// private void processCustomMessage(Context context, Bundle bundle) { +// if (MainActivity.isForeground) { +// String message = bundle.getString(JPushInterface.EXTRA_MESSAGE); +// String extras = bundle.getString(JPushInterface.EXTRA_EXTRA); +// Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION); +// msgIntent.putExtra(MainActivity.KEY_MESSAGE, message); +// if (!ExampleUtil.isEmpty(extras)) { +// try { +// JSONObject extraJson = new JSONObject(extras); +// if (extraJson.length() > 0) { +// msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras); +// } +// } catch (JSONException e) { +// +// } +// +// } +// LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent); +// } +// } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/SettingsModule/GosAboutActivity.java b/src/main/java/com/gizwits/opensource/appkit/SettingsModule/GosAboutActivity.java new file mode 100644 index 0000000..6abc361 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/SettingsModule/GosAboutActivity.java @@ -0,0 +1,135 @@ +package com.gizwits.opensource.appkit.SettingsModule; + +import android.app.ActionBar; +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.util.Log; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.utils.AssetsUtils; + +public class GosAboutActivity extends GosBaseActivity { + + /** + * The tv SDKVersion. + */ + TextView tv_SDKVersion; + + /** + * the tv appCode + */ + TextView tv_AppVersion; + + /** + * The ActionBar + */ + ActionBar actionBar; + private LinearLayout llApp; + private LinearLayout llSDK; + private LinearLayout llAbout; + private TextView tvAbout; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_about); + // 设置ActionBar + setToolBar(true, R.string.about); + + initView(); + initEvent(); + } + + private void initEvent() { + if (!GosDeploy.appConfig_ShowAPPVersion() && !GosDeploy.appConfig_ShowSDKVersion()) { + llApp.setVisibility(View.VISIBLE); + llSDK.setVisibility(View.VISIBLE); + llAbout.setVisibility(View.VISIBLE); + } else { + if (!GosDeploy.appConfig_ShowAPPVersion()) { + llApp.setVisibility(View.GONE); + } + if (!GosDeploy.appConfig_ShowSDKVersion()) { + llSDK.setVisibility(View.GONE); + } + if (GosDeploy.appConfig_AboutInfoCH() != null) { + if (GosDeploy.appConfig_AboutInfoEN() != null) { + if (AssetsUtils.isZh(this)) { + tvAbout.setText(GosDeploy.appConfig_AboutInfoCH()); + } else { + tvAbout.setText(GosDeploy.appConfig_AboutInfoEN()); + } + } else { + tvAbout.setText(GosDeploy.appConfig_AboutInfoCH()); + } + llAbout.setVisibility(View.VISIBLE); + } else { + if (GosDeploy.appConfig_AboutInfoEN() != null) { + tvAbout.setText(GosDeploy.appConfig_AboutInfoEN()); + llAbout.setVisibility(View.VISIBLE); + } else { + llAbout.setVisibility(View.GONE); + } + } + } + } + + /** + * Inits the view. + */ + private void initView() { + llApp = (LinearLayout) findViewById(R.id.llAPP); + llSDK = (LinearLayout) findViewById(R.id.llSDK); + llAbout = (LinearLayout) findViewById(R.id.llAbout); + tvAbout = (TextView) findViewById(R.id.tvAbout); + tv_SDKVersion = (TextView) findViewById(R.id.versionCode); + tv_AppVersion = (TextView) findViewById(R.id.appCode); + + } + + @Override + public void onResume() { + super.onResume(); + tv_SDKVersion.setText(GizWifiSDK.sharedInstance().getVersion().toString()); + tv_AppVersion.setText(getAppVersionName(this)); + } + + /** + * 返回当前程序版本名 + */ + public static String getAppVersionName(Context context) { + String versionName = ""; + try { + // ---get the package info--- + PackageManager pm = context.getPackageManager(); + PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0); + versionName = pi.versionName; + if (versionName == null || versionName.length() <= 0) { + return ""; + } + } catch(Exception e) { + Log.i("Apptest", "Exception", e); + } + return versionName; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return super.onOptionsItemSelected(item); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/ThirdAccountModule/BaseUiListener.java b/src/main/java/com/gizwits/opensource/appkit/ThirdAccountModule/BaseUiListener.java new file mode 100644 index 0000000..175cfc5 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/ThirdAccountModule/BaseUiListener.java @@ -0,0 +1,28 @@ +package com.gizwits.opensource.appkit.ThirdAccountModule; + +import com.tencent.tauth.IUiListener; +import com.tencent.tauth.UiError; + +import org.json.JSONObject; + +public class BaseUiListener implements IUiListener { + + @Override + public void onCancel() { + // TODO Auto-generated method stub + } + + @Override + public void onComplete(Object arg0) { + doComplete((JSONObject)arg0); + } + + protected void doComplete(JSONObject values) { + } + + @Override + public void onError(UiError arg0) { + // TODO Auto-generated method stu + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosChangeUserPasswordActivity.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosChangeUserPasswordActivity.java new file mode 100644 index 0000000..713b0a3 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosChangeUserPasswordActivity.java @@ -0,0 +1,226 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.os.Bundle; +import android.text.TextUtils; +import android.text.method.HideReturnsTransformationMethod; +import android.text.method.PasswordTransformationMethod; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.listener.GizWifiSDKListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +public class GosChangeUserPasswordActivity extends GosBaseActivity { + + private EditText oldpass; + private EditText newpass; + private EditText confrimpass; + private Button btnConfirm; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_gos_change_password); + setToolBar(true, R.string.edit_password); + initView(); + } + + @Override + protected void onResume() { + // TODO Auto-generated method stub + super.onResume(); + + GizWifiSDK.sharedInstance().setListener(listener); + } + + GizWifiSDKListener listener = new GizWifiSDKListener() { + + public void didChangeUserPassword( + com.gizwits.gizwifisdk.enumration.GizWifiErrorCode result) { + + if (result.getResult() == 0) { + Toast.makeText(GosChangeUserPasswordActivity.this, + getResources().getString(R.string.passsuccess), 2000) + .show(); + + finish(); + + spf.edit().putString("PassWord", newpass.getText().toString()) + .commit(); + } else { + + if (result.getResult() == 9020) { + Toast.makeText(GosChangeUserPasswordActivity.this, + getResources().getString(R.string.oldpasserror), + 2000).show(); + } else { + Toast.makeText(GosChangeUserPasswordActivity.this, + getResources().getString(R.string.passerror), 2000) + .show(); + } + + } + + } + + ; + }; + private CheckBox oldcheck; + private CheckBox newcheck; + private CheckBox concheck; + + private void initView() { + btnConfirm = (Button) findViewById(R.id.btnLogin); + oldpass = (EditText) findViewById(R.id.oldpass); + newpass = (EditText) findViewById(R.id.newpass); + confrimpass = (EditText) findViewById(R.id.confrimpass); + confrimpass.setTransformationMethod(PasswordTransformationMethod + .getInstance()); + oldpass.setTransformationMethod(PasswordTransformationMethod + .getInstance()); + newpass.setTransformationMethod(PasswordTransformationMethod + .getInstance()); + + oldcheck = (CheckBox) findViewById(R.id.oldcheck); + newcheck = (CheckBox) findViewById(R.id.newcheck); + concheck = (CheckBox) findViewById(R.id.concheck); +// 配置文件部署 + oldcheck.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + String psw = oldpass.getText().toString(); + + if (isChecked) { + // oldpass.setInputType(0x90); + oldpass.setTransformationMethod(HideReturnsTransformationMethod + .getInstance()); + } else { + // oldpass.setInputType(0x81); + oldpass.setTransformationMethod(PasswordTransformationMethod + .getInstance()); + } + oldpass.setSelection(psw.length()); + } + }); + + newcheck.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + String psw = newpass.getText().toString(); + + if (isChecked) { + // newpass.setInputType(0x90); + newpass.setTransformationMethod(HideReturnsTransformationMethod + .getInstance()); + } else { + // newpass.setInputType(0x81); + newpass.setTransformationMethod(PasswordTransformationMethod + .getInstance()); + } + newpass.setSelection(psw.length()); + } + }); + + concheck.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + String psw = confrimpass.getText().toString(); + + if (isChecked) { + // confrimpass.setInputType(0x90); + confrimpass + .setTransformationMethod(HideReturnsTransformationMethod + .getInstance()); + } else { + // confrimpass.setInputType(0x81); + confrimpass + .setTransformationMethod(PasswordTransformationMethod + .getInstance()); + } + confrimpass.setSelection(psw.length()); + } + }); + } + + public void confirm(View v) { + + if (TextUtils.isEmpty(oldpass.getText().toString()) + || TextUtils.isEmpty(newpass.getText().toString()) + || TextUtils.isEmpty(confrimpass.getText().toString())) { + + if (TextUtils.isEmpty(oldpass.getText().toString())) { + + Toast.makeText( + this, + getResources().getString( + R.string.enter_current_password), 2000).show(); + + return; + } + + if (TextUtils.isEmpty(newpass.getText().toString())) { + Toast.makeText(this, + getResources().getString(R.string.enter_new_password), + 2000).show(); + + return; + } + + if (TextUtils.isEmpty(confrimpass.getText().toString())) { + Toast.makeText( + this, + getResources() + .getString(R.string.re_enter_new_password), + 2000).show(); + return; + } + + } else { + //oldpass.getText().length() < 6 || + if (newpass.getText().length() < 6 || confrimpass.getText().length() < 6) { + Toast.makeText(this, + getResources().getString(R.string.toast_psw_short), + 2000).show(); + } + + String npass = newpass.getText().toString(); + String cpass = confrimpass.getText().toString(); + if (npass.equals(cpass)) { + GizWifiSDK.sharedInstance().changeUserPassword( + spf.getString("Token", ""), + oldpass.getText().toString(), npass); + } else { + Toast.makeText(this, + getResources().getString(R.string.nosamepass), 2000) + .show(); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + + finish(); + break; + } + return true; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosForgetPasswordActivity.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosForgetPasswordActivity.java new file mode 100644 index 0000000..3c3bf29 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosForgetPasswordActivity.java @@ -0,0 +1,385 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.graphics.drawable.GradientDrawable; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.text.InputType; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizUserAccountType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +import java.util.Timer; +import java.util.TimerTask; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +@SuppressLint("HandlerLeak") +public class GosForgetPasswordActivity extends GosUserModuleBaseActivity implements + OnClickListener { + + /** + * The et Name + */ + private EditText etName; + /** + * The ll phone + */ + private LinearLayout llPhone; + + /** + * The btn GetCode + */ + private TextView tvGetCode; + + /** + * The et Code + */ + private EditText etCode; + + /** + * The et Psw + */ + private EditText etPsw; + + /** + * The et ConfirmPsw + */ + private EditText etConfirmPsw; + /** + * 验证码重发倒计时 + */ + int secondleft = 60; + + /** + * The timer. + */ + Timer timer; + //resetPassword_phoneUser-false-end + /** + * The btn Register + */ + private Button btnReset; + + /** + * 数据变量 + */ + String name, code, psw, confirmpsw; + + + private enum handler_key { + //resetPassword_phoneUser-false-start + /** + * 获取验证码. + */ + GETCODE, + + /** + * 手机验证码发送成功. + */ + SENDSUCCESSFUL, + + /** + * 倒计时通知 + */ + TICK_TIME, + //resetPassword_phoneUser-false-end + + /** + * 提示信息 + */ + TOAST, + + /** + * 重置密码 + */ + RESET, + } + + Handler handler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + //resetPassword_phoneUser-false-start + case GETCODE: + progressDialog.show(); + String AppSecret = GosDeploy.appConfig_GizwitsInfoAppSecret(); + GizWifiSDK.sharedInstance().requestSendPhoneSMSCode(AppSecret, + msg.obj.toString()); + break; + case SENDSUCCESSFUL: + etName.setEnabled(false); + etName.setTextColor(getResources().getColor( + R.color.text_gray_light)); + isStartTimer(); + + break; + + case TICK_TIME: + String getCodeAgain = getString(R.string.getcode_again); + String timerMessage = getString(R.string.timer_message); + secondleft--; + if (secondleft <= 0) { + timer.cancel(); + tvGetCode.setTextColor(getResources().getColor(R.color.tomato)); + tvGetCode.setEnabled(true); + tvGetCode.setText(getCodeAgain); + } else { + tvGetCode.setText(secondleft + timerMessage); + } + break; + //resetPassword_phoneUser-false-end + case TOAST: + String successfulText = (String) getText(R.string.reset_successful); + Toast.makeText(GosForgetPasswordActivity.this, msg.obj + "", + toastTime).show(); + if (msg.obj.toString().equals(successfulText)) { + // spf.edit().putString("UserName", name).commit(); + // spf.edit().putString("PassWord", psw).commit(); + isclean = true; + //resetPassword_phoneUser-false-start + if (llPhone.getVisibility() == View.GONE) { + //resetPassword_phoneUser-false-end + Intent intent = new Intent(GosForgetPasswordActivity.this, GosSendEmailPasswordActivity.class); + startActivity(intent); + spf.edit().putString("Email", name).commit(); + //resetPassword_phoneUser-false-start + } else { + finish(); + } + //resetPassword_phoneUser-false-end + } + break; + case RESET: + progressDialog.show(); + GizWifiSDK.sharedInstance().resetPassword(name, code, psw, + GizUserAccountType.GizUserPhone); + break; + } + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_forget_password); + // 设置ActionBar + setToolBar(true, R.string.forget_pass); + + initView(); + initEvent(); + } + + private void initView() { + etName = (EditText) findViewById(R.id.etName); + //resetPassword_phoneUser-false-start + llPhone = (LinearLayout) findViewById(R.id.llPhone); + tvGetCode = (TextView) findViewById(R.id.tvGetCode); + etCode = (EditText) findViewById(R.id.etCode); + etPsw = (EditText) findViewById(R.id.etPsw); + etConfirmPsw = (EditText) findViewById(R.id.etConfirmPsw); + //resetPassword_phoneUser-false-end + btnReset = (Button) findViewById(R.id.btnReset); + setPhoneOrEmailIsVisable(); + } + + private void setPhoneOrEmailIsVisable() { + //resetPassword_phoneUser-true-start resetPassword_phoneUser-false-start + if (GosDeploy.appConfig_ResetPassword_PhoneUser()) { + //resetPassword_phoneUser-true-end + etName.setHint(getResources().getString(R.string.name_phone)); + llPhone.setVisibility(View.VISIBLE); + etName.setInputType(InputType.TYPE_CLASS_PHONE); + btnReset.setText(getResources().getString(R.string.reset)); + //resetPassword_phoneUser-true-start + } else { + //resetPassword_phoneUser-false-end + //resetPassword_phoneUser-false-start + } + //resetPassword_phoneUser-true-end resetPassword_phoneUser-false-end + } + + private void initEvent() { + + final Timer etTimer = new Timer(); + etTimer.schedule(new TimerTask() { + + @Override + public void run() { + etName.requestFocus(); + InputMethodManager imm = (InputMethodManager) etName + .getContext().getSystemService( + Context.INPUT_METHOD_SERVICE); + imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED); + etTimer.cancel(); + + } + }, 500); + //resetPassword_phoneUser-false-start + tvGetCode.setOnClickListener(this); + //resetPassword_phoneUser-false-end + btnReset.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + //resetPassword_phoneUser-false-start + case R.id.tvGetCode: + name = etName.getText().toString(); + if (TextUtils.isEmpty(name)) { + Toast.makeText(GosForgetPasswordActivity.this, + R.string.toast_name_wrong, toastTime).show(); + return; + } + Message msg = new Message(); + msg.obj = name; + msg.what = handler_key.GETCODE.ordinal(); + handler.sendMessage(msg); + break; + //resetPassword_phoneUser-false-end + case R.id.btnReset: + name = etName.getText().toString(); + //resetPassword_phoneUser-false-start + code = etCode.getText().toString(); + psw = etPsw.getText().toString(); + confirmpsw = etConfirmPsw.getText().toString(); + if (TextUtils.isEmpty(name)) { + Toast.makeText(GosForgetPasswordActivity.this, + R.string.toast_name_wrong, toastTime).show(); + return; + } + + if (llPhone.getVisibility() == View.VISIBLE) { + if (code.length() != 6) { + Toast.makeText(GosForgetPasswordActivity.this, R.string.no_getcode, toastTime).show(); + return; + } + if (TextUtils.isEmpty(psw)) { + Toast.makeText(GosForgetPasswordActivity.this, + R.string.toast_psw_wrong, toastTime).show(); + return; + } + if (psw.length() < 6) { + Toast.makeText(GosForgetPasswordActivity.this, + R.string.toast_psw_short, toastTime).show(); + return; + } + if (!psw.equals(confirmpsw)) { + Toast.makeText(GosForgetPasswordActivity.this, R.string.toast_psw_confirm_failed, toastTime).show(); + return; + } + } else { + //resetPassword_phoneUser-false-end + if (!name.contains("@")) { + Toast.makeText(GosForgetPasswordActivity.this, R.string.toase_name_email_fault, toastTime).show(); + return; + } + //resetPassword_phoneUser-false-start + } + //resetPassword_phoneUser-false-end + + /* + * if (psw.length() < 6) { + * Toast.makeText(GosForgetPasswordActivity.this, + * R.string.toast_psw_short, toastTime).show(); return; } + */ + handler.sendEmptyMessage(handler_key.RESET.ordinal()); + + break; + } + } + + + /** + * 倒计时 + */ + public void isStartTimer() { + tvGetCode.setEnabled(false); + tvGetCode.setTextColor(getResources().getColor(R.color.hint_color)); + secondleft = 60; + timer = new Timer(); + timer.schedule(new TimerTask() { + + @Override + public void run() { + handler.sendEmptyMessage(handler_key.TICK_TIME.ordinal()); + } + }, 1000, 1000); + } + + /** + * 手机验证码回调 + */ + @Override + protected void didRequestSendPhoneSMSCode(GizWifiErrorCode result, + String token) { + if (progressDialog != null) { + progressDialog.cancel(); + } + Message msg = new Message(); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + // String sendFailed = (String) getText(R.string.send_failed); + msg.what = handler_key.TOAST.ordinal(); + msg.obj = toastError(result);// sendFailed + "\n" + + // errorMessage;toastError(errorCode) + handler.sendMessage(msg); + } else { + handler.sendEmptyMessage(handler_key.SENDSUCCESSFUL.ordinal()); + msg.what = handler_key.TOAST.ordinal(); + String sendSuccessful = (String) getText(R.string.send_successful); + msg.obj = sendSuccessful; + handler.sendMessage(msg); + } + } + //resetPassword_phoneUser-false-end + + /** + * 重置密码回调 + */ + @Override + public void didChangeUserPassword(GizWifiErrorCode result) { + if (progressDialog != null) { + progressDialog.cancel(); + } + Message msg = new Message(); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + // String resetFailed = (String) getText(R.string.reset_failed); + msg.what = handler_key.TOAST.ordinal(); + msg.obj = toastError(result);// resetFailed + "\n" + errorMessage; + handler.sendMessage(msg); + } else { + msg.what = handler_key.TOAST.ordinal(); + String resetSuccessful = (String) getText(R.string.reset_successful); + msg.obj = resetSuccessful; + handler.sendMessage(msg); + } + } + + + @Override + protected void onDestroy() { + super.onDestroy(); + progressDialog = null; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosRegisterUserActivity.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosRegisterUserActivity.java new file mode 100644 index 0000000..9eab499 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosRegisterUserActivity.java @@ -0,0 +1,359 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.drawable.GradientDrawable; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.text.InputType; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.inputmethod.InputMethodManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizUserAccountType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +import java.util.Timer; +import java.util.TimerTask; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@SuppressLint("HandlerLeak") +public class GosRegisterUserActivity extends GosUserModuleBaseActivity implements OnClickListener, AdapterView.OnItemSelectedListener { + + /** + * The et Name + */ + private EditText etName; + //register_phoneUser-false-start + /** + * The ll code + */ + private LinearLayout llCode; + + /** + * The btn GetCode + */ + private TextView tvGetCode; + + /** + * The et Code + */ + private EditText etCode; + /** + * 验证码重发倒计时 + */ + int secondleft = 60; + + /** + * The timer. + */ + Timer timer; + + //register_phoneUser-false-end + /** + * The et Psw + */ + private EditText etPsw; + + /** + * The et ConfirmPsw + */ + private EditText etConfirmPsw; + + /** + * The btn Rrgister + */ + private Button btnRrgister; + + /** + * 数据变量 + */ + String name, code, psw, confirmpsw; + + private int usertype = 0; + + private enum handler_key { + //register_phoneUser-false-start + /** + * 获取验证码. + */ + GETCODE, + /** + * 手机验证码发送成功. + */ + SENDSUCCESSFUL, + //register_phoneUser-false-end + + /** + * 提示信息 + */ + TOAST, + /** + * 倒计时通知 + */ + TICK_TIME, + + /** + * 注册 + */ + REGISTER, + } + + Handler handler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + //register_phoneUser-false-start + case GETCODE: + progressDialog.show(); + String AppSecret = GosDeploy.appConfig_GizwitsInfoAppSecret(); + GizWifiSDK.sharedInstance().requestSendPhoneSMSCode(AppSecret, msg.obj.toString()); + break; + case SENDSUCCESSFUL: + etName.setEnabled(false); + etName.setTextColor(getResources().getColor(R.color.text_gray_light)); + isStartTimer(); + break; + case TICK_TIME: + String getCodeAgain = getString(R.string.getcode_again); + String timerMessage = getString(R.string.timer_message); + secondleft--; + if (secondleft <= 0) { + timer.cancel(); + tvGetCode.setTextColor(getResources().getColor(R.color.tomato)); + tvGetCode.setEnabled(true); + tvGetCode.setText(getCodeAgain); + } else { + tvGetCode.setText(secondleft + timerMessage); + } + break; + //register_phoneUser-false-end + case TOAST: + Toast.makeText(GosRegisterUserActivity.this, msg.obj.toString(), toastTime).show(); + String successfulText = (String) getText(R.string.register_successful); + + if (msg.obj.toString().equals(successfulText)) { + spf.edit().putString("UserName", name).commit(); + spf.edit().putString("PassWord", psw).commit(); + isclean = true; + finish(); + } + break; + case REGISTER: + progressDialog.show(); + GizWifiSDK.sharedInstance().registerUser(name, psw, code, GizUserAccountType.GizUserPhone); + break; + } + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_register_user); + // 设置ActionBar + setToolBar(true, R.string.register); + initView(); + initEvent(); + } + + private void initView() { + etName = (EditText) findViewById(R.id.etName); + //register_phoneUser-false-start + tvGetCode = (TextView) findViewById(R.id.tvGetCode); + etCode = (EditText) findViewById(R.id.etCode); + llCode = (LinearLayout) findViewById(R.id.llCode); + //register_phoneUser-false-end + etPsw = (EditText) findViewById(R.id.etPsw); + etConfirmPsw = (EditText) findViewById(R.id.etConfirmPsw); + btnRrgister = (Button) findViewById(R.id.btnRrgister); + setPhoneOrEmailOrNormalIsVisable(); + } + + private void setPhoneOrEmailOrNormalIsVisable() { + etName.setHint(getResources().getString(R.string.name_phone)); + usertype = 0; + } + + + private void initEvent() { + final Timer etTimer = new Timer(); + etTimer.schedule(new TimerTask() { + + @Override + public void run() { + etName.requestFocus(); + InputMethodManager imm = (InputMethodManager) etName.getContext() + .getSystemService(Context.INPUT_METHOD_SERVICE); + imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED); + etTimer.cancel(); + + } + }, 500); + //register_phoneUser-false-start + tvGetCode.setOnClickListener(this); + //register_phoneUser-false-end + btnRrgister.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + //register_phoneUser-false-start + case R.id.tvGetCode: + name = etName.getText().toString(); + if (TextUtils.isEmpty(name)) { + Toast.makeText(GosRegisterUserActivity.this, R.string.toast_name_wrong, toastTime).show(); + return; + } + Message msg = new Message(); + msg.obj = name; + msg.what = handler_key.GETCODE.ordinal(); + handler.sendMessage(msg); + break; + //register_phoneUser-false-end + case R.id.btnRrgister: + name = etName.getText().toString(); + //register_phoneUser-false-start + code = etCode.getText().toString(); + //register_phoneUser-false-end + psw = etPsw.getText().toString(); + confirmpsw = etConfirmPsw.getText().toString(); + if (TextUtils.isEmpty(name)) { + Toast.makeText(GosRegisterUserActivity.this, R.string.toast_name_wrong, toastTime).show(); + return; + } + if (usertype == 0) { + if (code.length() != 6) { + Toast.makeText(GosRegisterUserActivity.this, R.string.no_getcode, toastTime).show(); + return; + } + } + if (TextUtils.isEmpty(psw)) { + Toast.makeText(GosRegisterUserActivity.this, R.string.toast_psw_wrong, toastTime).show(); + return; + } + + if (psw.length() < 6) { + Toast.makeText(GosRegisterUserActivity.this, R.string.toast_psw_short, toastTime).show(); + return; + } + + if (TextUtils.isEmpty(confirmpsw)) { + Toast.makeText(GosRegisterUserActivity.this, R.string.toast_psw_confirm, toastTime).show(); + return; + } + if (!psw.equals(confirmpsw)) { + Toast.makeText(GosRegisterUserActivity.this, R.string.toast_psw_confirm_failed, toastTime).show(); + return; + } + + /* + * if (psw.length() < 6) { + * Toast.makeText(GosRegisterUserActivity.this, + * R.string.toast_psw_short, toastTime).show(); return; } + */ + handler.sendEmptyMessage(handler_key.REGISTER.ordinal()); + break; + } + } + + + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + etName.setText(""); + etName.setEnabled(true); + etName.setTextColor(getResources().getColor(R.color.text_color)); + //register_phoneUser-false-start + etCode.setText(""); + //register_phoneUser-false-end + etPsw.setText(""); + etConfirmPsw.setText(""); + etName.setHint(getResources().getString(R.string.name_phone)); + llCode.setVisibility(View.VISIBLE); + etName.setInputType(InputType.TYPE_CLASS_PHONE); + + } + + @Override + public void onNothingSelected(AdapterView parent) { + + } + //register_phoneUser-false-start + + /** + * 手机验证码回调 + */ + @Override + protected void didRequestSendPhoneSMSCode(GizWifiErrorCode result, String token) { + progressDialog.cancel(); + Message msg = new Message(); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + msg.what = handler_key.TOAST.ordinal(); + msg.obj = toastError(result); + handler.sendMessage(msg); + } else { + handler.sendEmptyMessage(handler_key.SENDSUCCESSFUL.ordinal()); + msg.what = handler_key.TOAST.ordinal(); + String sendSuccessful = (String) getText(R.string.send_successful); + msg.obj = sendSuccessful; + handler.sendMessage(msg); + } + } + + /** + * 倒计时 + */ + public void isStartTimer() { + tvGetCode.setEnabled(false); + tvGetCode.setTextColor(getResources().getColor(R.color.hint_color)); + secondleft = 60; + timer = new Timer(); + timer.schedule(new TimerTask() { + + @Override + public void run() { + handler.sendEmptyMessage(handler_key.TICK_TIME.ordinal()); + } + }, 1000, 1000); + } + //register_phoneUser-false-end + + /** + * 用户注册回调 + */ + @Override + protected void didRegisterUser(GizWifiErrorCode result, String uid, String token) { + progressDialog.cancel(); + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + Message msg = new Message(); + msg.what = handler_key.TOAST.ordinal(); + msg.obj = toastError(result); + handler.sendMessage(msg); + } else { + Message msg = new Message(); + msg.what = handler_key.TOAST.ordinal(); + String registerSuccessful = (String) getText(R.string.register_successful); + msg.obj = registerSuccessful; + handler.sendMessage(msg); + } + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosSendEmailPasswordActivity.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosSendEmailPasswordActivity.java new file mode 100644 index 0000000..b090248 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosSendEmailPasswordActivity.java @@ -0,0 +1,69 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.content.Intent; +import android.os.Bundle; +import android.text.SpannableString; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; + + +public class GosSendEmailPasswordActivity extends GosBaseActivity { + + private TextView tvEmail; + private Button btnReturn; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_send_email_password); + // 设置ActionBar + setToolBar(true, R.string.forget_pass); + initView(); + initEvent(); + } + + private static final String TAG = "GosSendEmailPasswordAct"; + + private void initView() { + tvEmail = (TextView) findViewById(R.id.tvEmail); + btnReturn = (Button) findViewById(R.id.btnReturn); + } + + private void initEvent() { + String email = spf.getString("Email", "xxx@xxx.xx"); + String s = getResources().getString(R.string.send_email_pass); + //字符串截取 + String bb = s.substring(10, 20); + //字符串替换 + String cc = s.replace(bb, email); + SpannableString spannableString = new SpannableString(cc); + spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.tomato)), 10, 10 + email.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + tvEmail.setText(spannableString); + btnReturn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(GosSendEmailPasswordActivity.this, GosUserLoginActivity.class); + startActivity(intent); + } + }); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return true; + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserLoginActivity.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserLoginActivity.java new file mode 100644 index 0000000..7825ee4 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserLoginActivity.java @@ -0,0 +1,626 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.annotation.SuppressLint; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.text.TextUtils; +import android.util.Log; +import android.view.KeyEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizThirdAccountType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosDeviceListFragment; +import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity; +//push-all-start +import com.gizwits.opensource.appkit.PushModule.GosPushManager; +//push_jiguang-false-start + +import cn.jpush.android.api.JPushInterface; +//push_jiguang-false-end +//push-all-end + +import com.gizwits.opensource.appkit.utils.ToolUtils; +//login_weChat-false-start +import com.tencent.mm.sdk.modelmsg.SendAuth; +import com.tencent.mm.sdk.openapi.IWXAPI; +import com.tencent.mm.sdk.openapi.WXAPIFactory; +//login_weChat-false-end +//login_qq-false-start +import com.gizwits.opensource.appkit.ThirdAccountModule.BaseUiListener; +import com.tencent.tauth.IUiListener; +import com.tencent.tauth.Tencent; +//login_qq-false-end +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Timer; +import java.util.TimerTask; + + +@SuppressLint("HandlerLeak") +public class GosUserLoginActivity extends com.gizwits.opensource.appkit.UserModule.GosUserModuleBaseActivity implements + OnClickListener { + + //GosPushManager gosPushManager; + + /** + * The et Name + */ + private static EditText etName; + + /** + * The et Psw + */ + private static EditText etPsw; + + /** + * The btn Login + */ + private Button btnLogin; + + /** + * The tv Register + */ + private TextView tvRegister; + + /** + * The tv Forget + */ + private TextView tvForget; + //login_anonymous-false-start + /** + * The tv Pass + */ + private TextView tvPass; + //login_anonymous-false-end + /** + * The cb Laws + */ + + private CheckBox cbLaws; + + /** + * The ll QQ + */ + private LinearLayout llQQ; + + /** + * The ll Wechat + */ + private LinearLayout llWechat; + + private LinearLayout llFacebook; + private LinearLayout llTwitter; + private LinearLayout llWechat1; + //login_qq-false-start + /** + * The Tencent + */ + private Tencent mTencent; + //login_qq-false-end + //login_weChat-false-start + /** + * The Wechat + */ + public static IWXAPI mIwxapi; + //login_weChat-false-end + + /** + * The Scope + */ + private String Scope = "get_user_info,add_t"; + //login_qq-false-start + /** + * The IUiListener + */ + IUiListener listener; + //login_qq-false-end + Intent intent; + + /** + * The GizThirdAccountType + */ + public static GizThirdAccountType gizThirdAccountType; + + /** + * The THRED_LOGIN UID&TOKEN + */ + public static String thirdUid, thirdToken; + private LinearLayout llInland; + private LinearLayout llForeign; + + + private View viewLine; + + + public static enum handler_key { + + /** + * 登录 + */ + LOGIN, + + /** + * 自动登录 + */ + AUTO_LOGIN, + + /** + * 第三方登录 + */ + THRED_LOGIN, + + /** + * 国外域名登录 + */ + FOREIGN + } + + /** + * 与WXEntryActivity共用Handler + */ + private Handler baseHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + // 登录 + case LOGIN: + progressDialog.show(); + GosDeviceListFragment.loginStatus = 0; + GizWifiSDK.sharedInstance() + .userLogin(etName.getText().toString(), + etPsw.getText().toString()); + break; + // 自动登录 + case AUTO_LOGIN: + progressDialog.show(); + GosDeviceListFragment.loginStatus = 0; + GizWifiSDK.sharedInstance().userLogin( + spf.getString("UserName", ""), + spf.getString("PassWord", "")); + break; + // 第三方登录 + case THRED_LOGIN: + progressDialog.show(); + GosDeviceListFragment.loginStatus = 0; + GizWifiSDK.sharedInstance().loginWithThirdAccount( + gizThirdAccountType, thirdUid, thirdToken); + spf.edit().putString("thirdUid", thirdUid).commit(); + break; + case FOREIGN: + llForeign.setVisibility(View.VISIBLE); + llInland.setVisibility(View.GONE); + break; + } + } + + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setTheme(R.style.AppTheme); +// requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 + setContentView(R.layout.activity_gos_user_login); + // 设置actionBaru + //setActionBar(false, false, R.string.app_company); + initView(); + initEvent(); + } + + @Override + protected void onResume() { + super.onResume(); + //push-all-start + //push_jiguang-false-start + JPushInterface.onResume(this); + //push_jiguang-false-end + //push-all-end + autoLogin(); + cleanuserthing(); + } + + + private void cleanuserthing() { + if (isclean) { + etName.setText(""); + etPsw.setText(""); + } + } + + private void autoLogin() { + if (TextUtils.isEmpty(spf.getString("UserName", "")) + || TextUtils.isEmpty(spf.getString("PassWord", ""))) { + return; + } + baseHandler.sendEmptyMessageDelayed(handler_key.AUTO_LOGIN.ordinal(), + 1000); + } + + private void initView() { + etName = (EditText) findViewById(R.id.etName); + etPsw = (EditText) findViewById(R.id.etPsw); + btnLogin = (Button) findViewById(R.id.btnLogin); + //register-all-start + tvRegister = (TextView) findViewById(R.id.tvRegister); + //register-all-end + //resetPassword-all-start + tvForget = (TextView) findViewById(R.id.tvForget); + //resetPassword-all-end + //login_anonymous-false-start + tvPass = (TextView) findViewById(R.id.tvPass); + //login_anonymous-false-end + cbLaws = (CheckBox) findViewById(R.id.cbLaws); + + llInland = (LinearLayout) findViewById(R.id.llInland); + llForeign = (LinearLayout) findViewById(R.id.llForeign); + + + //login_qq-false-start + llQQ = (LinearLayout) findViewById(R.id.llQQ); + //login_qq-false-end + //login_qq-false-start login_qq-true-start + viewLine = (View) findViewById(R.id.view_line); + //login_qq-false-end login_qq-true-end + //login_weChat-false-start + llWechat = (LinearLayout) findViewById(R.id.llWechat); + //login_weChat-false-end + //login_weChat-false-start + llWechat1 = (LinearLayout) findViewById(R.id.llWechat1); + //login_weChat-false-end + if (!GosDeploy.appConfig_Login_Anonymous()) { + tvPass.setVisibility(View.GONE); + } + if (!GosDeploy.appConfig_Register_PhoneUser()) { + tvRegister.setVisibility(View.GONE); + } + if (!GosDeploy.appConfig_ResetPassword_PhoneUser()) { + tvForget.setVisibility(View.GONE); + } + // 配置文件部署 + btnLogin.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + btnLogin.setTextColor(GosDeploy.appConfig_Contrast()); + //btnLogin.setTextColor( Color.argb(255, 0, 167, 186)); + } + + private void initEvent() { + btnLogin.setOnClickListener(this); + //register-all-start + tvRegister.setOnClickListener(this); + //register-all-end + //resetPassword-all-start + tvForget.setOnClickListener(this); + //resetPassword-all-end + //login_anonymous-false-start + tvPass.setOnClickListener(this); + //login_anonymous-false-end + //login_qq-false-start + llQQ.setOnClickListener(this); + //login_qq-false-end + //login_weChat-false-start + llWechat.setOnClickListener(this); + //login_weChat-false-end + //login_weChat-false-start + llWechat1.setOnClickListener(this); + //login_weChat-false-end + + //login_qq-true-start login_qq-false-start + if (!GosDeploy.appConfig_Login_QQ()) { + llQQ.setVisibility(View.GONE); + viewLine.setVisibility(View.GONE); + } + //login_qq-true-end login_qq-true-end + //login_weChat-true-start login_weChat-false-start + if (!GosDeploy.appConfig_Login_Wechat()) { + llWechat.setVisibility(View.GONE); + llWechat1.setVisibility(View.GONE); + viewLine.setVisibility(View.GONE); + } + //login_weChat-false-end login_weChat-true-end + + cbLaws.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, + boolean isChecked) { + String psw = etPsw.getText().toString(); + if (isChecked) { + etPsw.setInputType(0x90); + } else { + etPsw.setInputType(0x81); + } + etPsw.setSelection(psw.length()); + } + }); + GizWifiSDK.sharedInstance().getCurrentCloudService(); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btnLogin: + if (TextUtils.isEmpty(etName.getText().toString())) { + Toast.makeText(GosUserLoginActivity.this, + R.string.toast_name_wrong, toastTime).show(); + return; + } + if (TextUtils.isEmpty(etPsw.getText().toString())) { + Toast.makeText(GosUserLoginActivity.this, + R.string.toast_psw_wrong, toastTime).show(); + return; + } + baseHandler.sendEmptyMessage(handler_key.LOGIN.ordinal()); + break; + // register-all-start + case R.id.tvRegister: + if (ToolUtils.noDoubleClick()) { + intent = new Intent(GosUserLoginActivity.this, + com.gizwits.opensource.appkit.UserModule.GosRegisterUserActivity.class); + startActivity(intent); + } + break; + //register-all-end + //resetPassword-all-start + case R.id.tvForget: + if (ToolUtils.noDoubleClick()) { + intent = new Intent(GosUserLoginActivity.this, + com.gizwits.opensource.appkit.UserModule.GosForgetPasswordActivity.class); + startActivity(intent); + } + break; + //resetPassword-all-end + //login_anonymous-false-start + case R.id.tvPass: + intent = null; + if (GosDeploy.appConfig_GizwitsInfoAppID() != null && GosDeploy.appConfig_GizwitsInfoAppSecret() != null) { + } + if (intent == null) { + intent = new Intent(GosUserLoginActivity.this, GosMainActivity.class); + } + startActivity(intent); + break; + //login_anonymous-false-end + //login_qq-false-start + case R.id.llQQ: + if (ToolUtils.noDoubleClick()) { + //login_qq-true-start + if (GosDeploy.appConfig_Login_QQ()) { + // login_qq-true-end + String tencentAPPID = GosDeploy.appConfig_TencentAppID(); + if (TextUtils.isEmpty(tencentAPPID)) { + noIDAlert(this, R.string.TencentAPPID_Toast); + return; + } else { + // 启动QQ登录SDK + mTencent = Tencent.createInstance(GosDeploy.appConfig_TencentAppID(), + this.getApplicationContext()); + } + listener = new BaseUiListener() { + protected void doComplete(JSONObject values) { + Message msg = new Message(); + try { + if (values.getInt("ret") == 0) { + gizThirdAccountType = GizThirdAccountType.GizThirdQQ; + thirdUid = values.getString("openid").toString(); + thirdToken = values.getString("access_token") + .toString(); + msg.what = handler_key.THRED_LOGIN.ordinal(); + baseHandler.sendMessage(msg); + } else { + Toast.makeText(GosUserLoginActivity.this, + msg.obj.toString(), toastTime).show(); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + }; + //使用qq登录将此处放开 并且到AndroidManifest 放开activity service + mTencent.login(this, Scope, listener); + //login_qq-true-start + } + // login_qq-true-end + } + break; + //login_qq-false-end + //login_weChat-false-start + case R.id.llWechat: + if (ToolUtils.noDoubleClick()) { + // login_weChat-true-start + if (GosDeploy.appConfig_Login_Wechat()) { + // login_weChat-true-end + String wechatAppID = GosDeploy.appConfig_WechatAppID(); + String wechatAppSecret = GosDeploy.appConfig_WechatAppSecret(); + if (TextUtils.isEmpty(wechatAppID) + || TextUtils.isEmpty(wechatAppSecret) + || wechatAppID.contains("your_wechat_app_id") + || wechatAppSecret.contains("your_wechat_app_secret")) { + noIDAlert(this, R.string.WechatAppID_Toast); + return; + } else { + // 设置与WXEntryActivity共用Handler + setBaseHandler(baseHandler); + // 启动微信登录SDK + mIwxapi = WXAPIFactory.createWXAPI(this, wechatAppID, false); + // 将应用的AppID注册到微信 + mIwxapi.registerApp(wechatAppID); + } + if (!(mIwxapi.isWXAppInstalled() && mIwxapi.isWXAppSupportAPI())) { + noIDAlert(this, R.string.No_WXApp); + return; + } + SendAuth.Req req = new SendAuth.Req(); + req.scope = "snsapi_userinfo"; + req.state = "wechat_sdk_demo"; + mIwxapi.sendReq(req); + //login_weChat-true-start + } + // login_weChat-true-end + } + break; + //login_weChat-false-end + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + + //login_qq-false-start + if (requestCode == 11101) { + Tencent.onActivityResultData(requestCode, resultCode, data, listener); + } + //login_qq-false-end + } + + /** + * 设置云端服务回调 + */ + protected void didGetCurrentCloudService(GizWifiErrorCode result, + java.util.concurrent.ConcurrentHashMap cloudServiceInfo) { + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + Toast.makeText(this, toastError(result), toastTime).show(); + } else { + if (cloudServiceInfo != null) { + String api = cloudServiceInfo.get("openAPIDomain"); + if (api != null) { + if (api.equals("usapi.gizwits.com") || api.equals("euapi.gizwits.com")) { + baseHandler.sendEmptyMessage(handler_key.FOREIGN.ordinal()); + } + } + } + } + } + + /** + * 用户登录回调 + */ + @Override + protected void didUserLogin(GizWifiErrorCode result, String uid, + String token) { + progressDialog.cancel(); + Log.i("Apptest", GosDeviceListFragment.loginStatus + "\t" + "User"); + if (GosDeviceListFragment.loginStatus == 4 + || GosDeviceListFragment.loginStatus == 3) { + return; + } + + Log.i("Apptest", GosDeviceListFragment.loginStatus + "\t" + "UserLogin"); + + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {// 登录失败 + Toast.makeText(GosUserLoginActivity.this, toastError(result), + toastTime).show(); + } else {// 登录成功 + GosDeviceListFragment.loginStatus = 1; + Toast.makeText(GosUserLoginActivity.this, + R.string.toast_login_successful, toastTime).show(); + // TODO 绑定推送\ + //push-all-start + //push_baidu-false-start push_baidu-true-start + if (GosDeploy.appConfig_Push_BaiDu()) { + //push_baidu-true-end + GosPushManager.pushBindService(uid, token); + //push_baidu-true-start + } + //push_baidu-false-end push_baidu-true-end + //push_jiguang-false-start push_jiguang-true-start + if (GosDeploy.appConfig_Push_JiGuang()) { + //push_jiguang-true-end + GosPushManager.pushBindService(uid, token); + //push_jiguang-true-start + } + //push_jiguang-false-end push_jiguang-true-end + //push-all-end +// PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, "T45LbeyAo3muOzMHztipttr8"); + if (!TextUtils.isEmpty(etName.getText().toString()) + && !TextUtils.isEmpty(etPsw.getText().toString())) { + spf.edit().putString("UserName", etName.getText().toString()) + .commit(); + spf.edit().putString("PassWord", etPsw.getText().toString()) + .commit(); + } + spf.edit().putString("Uid", uid).commit(); + spf.edit().putString("Token", token).commit(); + + intent = null; + if (intent == null) { + intent = new Intent(GosUserLoginActivity.this, + GosMainActivity.class); + } + intent.putExtra("ThredLogin", true); + startActivity(intent); + } + } + + /** + * 解绑推送回调 + * + * @param result + */ + protected void didChannelIDUnBind(GizWifiErrorCode result) { + if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) { + Toast.makeText(this, toastError(result), toastTime).show(); + } + + Log.i("Apptest", "UnBind:" + result.toString()); + } + + ; + + /** + * 菜单、返回键响应 + */ + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + exitBy2Click(); // 调用双击退出函数 + } + return false; + } + + /** + * 双击退出函数 + */ + private static Boolean isExit = false; + + private void exitBy2Click() { + Timer tExit = null; + if (isExit == false) { + isExit = true; // 准备退出 + String doubleClick = (String) getText(R.string.double_click); + Toast.makeText(this, doubleClick, toastTime).show(); + tExit = new Timer(); + tExit.schedule(new TimerTask() { + @Override + public void run() { + isExit = false; // 取消退出 + } + }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务 + + } else { + this.finish(); + System.exit(0); + } + } + + @Override + public void onPause() { + super.onPause(); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserManager.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserManager.java new file mode 100644 index 0000000..10fffa0 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserManager.java @@ -0,0 +1,163 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.DeviceModule.GosDeviceListFragment; +import com.gizwits.opensource.appkit.PushModule.GosPushManager; +import com.gizwits.opensource.appkit.R; + +//push-all-start +//push-all-end + +public class GosUserManager extends GosBaseActivity { + + private static final int GOSUSERMANAGER = 234; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_usermanager); + setToolBar(true, R.string.user_management); + initView(); + } + + private void initView() { + TextView phoneusernumber = (TextView) findViewById(R.id.phoneusernumber); + //personalCenter_changePassword-false-start + LinearLayout changeuserpassword = (LinearLayout) findViewById(R.id.changeuserpassword); + if (!GosDeploy.appConfig_PersonalCenter_ChangePassword()) { + changeuserpassword.setVisibility(View.GONE); + } + //personalCenter_changePassword-false-end + if (!TextUtils.isEmpty(spf.getString("UserName", ""))) { + phoneusernumber.setText(spf.getString("UserName", "")); + } else { + //personalCenter_changePassword-false-start + String uid = spf.getString("thirdUid", ""); + if (!TextUtils.isEmpty(uid) && uid.length() != 0) { + String myuid = uid.substring(0, 2) + "***" + uid.substring(uid.length() - 4, uid.length()); + phoneusernumber.setText(myuid); + changeuserpassword.setVisibility(View.GONE); + } + //personalCenter_changePassword-false-end + } + + } + + public void userlogout(View v) { + setResult(GOSUSERMANAGER); + logoutToClean(); + + Intent intent = new Intent(GosUserManager.this, GosUserLoginActivity.class); + quitAlert(intent, getString(R.string.exit_login)); + + } + + //personalCenter_changePassword-false-start + public void changeuserpassword(View v) { + Intent tent = new Intent(this, GosChangeUserPasswordActivity.class); + startActivity(tent); + } + //personalCenter_changePassword-false-end + + private void logoutToClean() { + //push-all-start + GosPushManager.pushUnBindService(spf.getString("Token", "")); + //push-all-end + spf.edit().putString("UserName", "").commit(); + isclean = true; + spf.edit().putString("PassWord", "").commit(); + spf.edit().putString("Uid", "").commit(); + spf.edit().putString("Token", "").commit(); + + spf.edit().putString("thirdUid", "").commit(); + + if (GosDeviceListFragment.loginStatus == 1) { + GosDeviceListFragment.loginStatus = 0; + } else { + GosDeviceListFragment.loginStatus = 4; + } + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + isclean = false; + finish(); + break; + } + return true; + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + isclean = false; + finish(); + return true; + } + return false; + } + + /** + * 推出提示 + * + * @param + */ + protected void quitAlert(final Intent intent, String content) { + final Dialog dialog = new AlertDialog.Builder(this, R.style.alert_dialog_style) + .setView(new EditText(this)).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + TextView tvContent; + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + tvContent = (TextView) window.findViewById(R.id.tv_prompt); + + tvContent.setText(content); + + llNo.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + + dialog.cancel(); + + startActivity(intent); + + } + }); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserModuleBaseActivity.java b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserModuleBaseActivity.java new file mode 100644 index 0000000..275d9fd --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/UserModule/GosUserModuleBaseActivity.java @@ -0,0 +1,132 @@ +package com.gizwits.opensource.appkit.UserModule; + +import android.view.MenuItem; + +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizWifiSDKListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; + +public class GosUserModuleBaseActivity extends GosBaseActivity { + + private GizWifiSDKListener gizWifiSDKListener = new GizWifiSDKListener() { + + /** 用于用户登录 */ + public void didUserLogin(GizWifiErrorCode result, String uid, String token) { + GosUserModuleBaseActivity.this.didUserLogin(result, uid, token); + }; + + /** 用于手机验证码 */ + public void didRequestSendPhoneSMSCode(GizWifiErrorCode result, String token) { + GosUserModuleBaseActivity.this.didRequestSendPhoneSMSCode(result, token); + + }; + + /** 用于用户注册 */ + public void didRegisterUser(GizWifiErrorCode result, String uid, String token) { + GosUserModuleBaseActivity.this.didRegisterUser(result, uid, token); + }; + + /** 用于重置密码 */ + public void didChangeUserPassword(GizWifiErrorCode result) { + GosUserModuleBaseActivity.this.didChangeUserPassword(result); + }; + + /** 用于解绑推送 */ + public void didChannelIDUnBind(GizWifiErrorCode result) { + GosUserModuleBaseActivity.this.didChannelIDUnBind(result); + }; + + /** 用于设置云端服务环境 */ + public void didGetCurrentCloudService(GizWifiErrorCode result, + java.util.concurrent.ConcurrentHashMap cloudServiceInfo) { + GosUserModuleBaseActivity.this.didGetCurrentCloudService(result, cloudServiceInfo); + }; + + }; + + /** + * 用户登录回调 + * + * @param result + * 错误码 + * @param uid + * 用户ID + * @param token + * 授权令牌 + */ + protected void didUserLogin(GizWifiErrorCode result, String uid, String token) { + }; + + /** + * 手机验证码回调 + * + * @param result + * 错误码 + * @param token + * 口令 + */ + protected void didRequestSendPhoneSMSCode(GizWifiErrorCode result, String token) { + }; + + /** + * 用户注册回调 + * + * @param result + * 错误码 + * @param uid + * 用户ID + * @param token + * 授权令牌 + */ + protected void didRegisterUser(GizWifiErrorCode result, String uid, String token) { + }; + + /** + * 重置密码回调 + * + * @param result + * 错误码 + */ + protected void didChangeUserPassword(GizWifiErrorCode result) { + }; + + /** + * 解绑推送回调 + * + * @param result + * 错误码 + */ + protected void didChannelIDUnBind(GizWifiErrorCode result) { + }; + + /** + * 设置云端服务环境回调 + * + * @param result + * 错误码 + * @param cloudServiceInfo + * 云端服务信息 + */ + protected void didGetCurrentCloudService(GizWifiErrorCode result, + java.util.concurrent.ConcurrentHashMap cloudServiceInfo) { + } + + @Override + protected void onResume() { + super.onResume(); + // 每次返回activity都要注册一次sdk监听器,保证sdk状态能正确回调 + GizWifiSDK.sharedInstance().setListener(gizWifiSDKListener); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return super.onOptionsItemSelected(item); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/InvitedFragment.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/InvitedFragment.java new file mode 100644 index 0000000..474ccdc --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/InvitedFragment.java @@ -0,0 +1,272 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.TextView; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo; +import com.gizwits.gizwifisdk.api.GizUserInfo; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingStatus; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.DateUtil; + +public class InvitedFragment extends Fragment { + + // 定义俩个整形值用来区分当前要显示的是哪个view对象 + // 如果是1的话就共享列表, 2的话就是受邀列表 + private int mytpye = -1; + +// private List mydeviceSharingInfos = new ArrayList(); + + private String token; + + private myadapter myadapter; + + private TextView myview; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + initdata(); + // 动态找到布局文件,再从这个布局中find出TextView对象 + View contextView = inflater.inflate(R.layout.activity_gos_shared_list, container, false); + ListView mListView = (ListView) contextView.findViewById(R.id.mysharedlist); + myview = (TextView) contextView.findViewById(R.id.shareddeviceproductname); + myview.setText(getString(R.string.no_guest_users)); + if (GosConstant.newmydeviceSharingInfos != null) { + myadapter = new myadapter(); + mListView.setAdapter(myadapter); + } + + + return contextView; + } + + + public TextView getmyview() { + return myview; + } + + // 初始化接口数据 + private void initdata() { + SharedPreferences spf = getActivity().getSharedPreferences("set", Context.MODE_PRIVATE); + token = spf.getString("Token", ""); +// GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingToMe, null); +// +// GizDeviceSharing.setListener(new GizDeviceSharingListener() { +// +// @Override +// public void didGetDeviceSharingInfos(GizWifiErrorCode result, String deviceID, +// List deviceSharingInfos) { +// super.didGetDeviceSharingInfos(result, deviceID, deviceSharingInfos); +// mydeviceSharingInfos = deviceSharingInfos; +// +// if (mydeviceSharingInfos.size() == 0) { +// myview.setVisibility(View.VISIBLE); +// myview.setText(getResources().getString(R.string.you_have_no_invited_message)); +// } else { +// myview.setVisibility(View.GONE); +// } +// myadapter.notifyDataSetChanged(); +// } +// +// @Override +// public void didAcceptDeviceSharing(GizWifiErrorCode result, String sharingID) { +// super.didAcceptDeviceSharing(result, sharingID); +// +// SharedDeviceListAcitivity activity = (SharedDeviceListAcitivity) getActivity(); +// if (result.ordinal() != 0) { +// Toast.makeText(activity, activity.toastError(result), 2).show(); +// } +// +// GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingToMe, null); +// } +// +// }); + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + } + + // listview的adapter,通过刷新的bound对象的属性值来判断当前应该现实的是什么 + class myadapter extends BaseAdapter { + + @Override + public int getCount() { + return GosConstant.newmydeviceSharingInfos.size(); + } + + @Override + public Object getItem(int arg0) { + return null; + } + + @Override + public long getItemId(int arg0) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + View view = View.inflate(getActivity(), R.layout.gos_shared_to_me_activity, null); + + TextView mess = (TextView) view.findViewById(R.id.mess); + + View redpoint = view.findViewById(R.id.redpoint); + + TextView timemess = (TextView) view.findViewById(R.id.timemess); + + TextView mystatues = (TextView) view.findViewById(R.id.mystatues); + + LinearLayout buttionline = (LinearLayout) view.findViewById(R.id.buttionline); + + TextView accept = (TextView) view.findViewById(R.id.accept); + + TextView refuse = (TextView) view.findViewById(R.id.refuse); + + + final GizDeviceSharingInfo gizDeviceSharingInfo = GosConstant.newmydeviceSharingInfos.get(position); + + GizUserInfo userInfo = gizDeviceSharingInfo.getUserInfo(); + + String username = userInfo.getUsername(); + + String email = userInfo.getEmail(); + + String phone = userInfo.getPhone(); + + String remark = userInfo.getRemark(); + String uid = userInfo.getUid(); + + + accept.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.acceptDeviceSharing(token, gizDeviceSharingInfo.getId(), true); + } + }); + + refuse.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.acceptDeviceSharing(token, gizDeviceSharingInfo.getId(), false); + } + }); + String passs = getResources().getString(R.string.tomeshareddevice); + + String[] split = passs.split("xxx"); + + if (!TextUtils.isEmpty(uid) && !uid.equals("null")) { + uid = uid.substring(0, 3) + "***" + uid.substring(uid.length() - 4, uid.length()); + + if (split.length > 2) { + mess.setText(split[0] + uid + split[split.length - 1]); + } else { + + mess.setText(uid + split[split.length - 1]); + } + + } + if (!TextUtils.isEmpty(email) && !email.equals("null")) { + if (split.length > 2) { + mess.setText(split[0] + email + split[split.length - 1]); + } else { + mess.setText(email + split[split.length - 1]); + } + } + + if (!TextUtils.isEmpty(phone) && !phone.equals("null")) { + if (split.length > 2) { + mess.setText(split[0] + phone + split[split.length - 1]); + } else { + + mess.setText(phone + split[split.length - 1]); + } + } + + if (!TextUtils.isEmpty(username) && !username.equals("null")) { + if (split.length > 2) { + mess.setText(split[0] + username + split[split.length - 1]); + } else { + + mess.setText(username + split[split.length - 1]); + } + } + + if (!TextUtils.isEmpty(remark) && !remark.equals("null")) { + if (split.length > 2) { + mess.setText(split[0] + remark + split[split.length - 1]); + } else { + + mess.setText(remark + split[split.length - 1]); + } + } + + GizDeviceSharingStatus status = gizDeviceSharingInfo.getStatus(); + + String updatedAt = gizDeviceSharingInfo.getUpdatedAt(); + updatedAt = DateUtil.utc2Local(updatedAt); + + String expiredAt = gizDeviceSharingInfo.getExpiredAt(); + expiredAt = DateUtil.utc2Local(expiredAt); + + timemess.setText(updatedAt + " " + gizDeviceSharingInfo.getProductName()); + int myintstatus = status.ordinal(); + + + if (myintstatus == 0) { + String timeByFormat = DateUtil.getCurTimeByFormat("yyyy-MM-dd HH:mm:ss"); + long diff = DateUtil.getDiff(timeByFormat, expiredAt); + + if (diff > 0) { + redpoint.setVisibility(View.GONE); + mystatues.setVisibility(View.VISIBLE); + buttionline.setVisibility(View.GONE); + mystatues.setText(getResources().getString(R.string.requsettimeout)); + } else { + redpoint.setVisibility(View.VISIBLE); + buttionline.setVisibility(View.VISIBLE); + mystatues.setVisibility(View.GONE); + } + + } else { + redpoint.setVisibility(View.GONE); + mystatues.setVisibility(View.VISIBLE); + buttionline.setVisibility(View.GONE); + if (myintstatus == 1) { + mystatues.setText(getResources().getString(R.string.accept)); + } else if (myintstatus == 2) { + mystatues.setText(getResources().getString(R.string.refuse)); + } else if (myintstatus == 3) { + mystatues.setText(getResources().getString(R.string.cancelled)); + } + + } + + return view; + } + + } + + + public myadapter getmyadapter() { + return myadapter; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/MsgNoticeActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/MsgNoticeActivity.java new file mode 100644 index 0000000..03e45b9 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/MsgNoticeActivity.java @@ -0,0 +1,82 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.os.Bundle; +import android.view.MenuItem; +import android.widget.ListView; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.R; + + +/** + * Created by Sunny on 2015年6月25日 + * + * @author Sunny + */ +public class MsgNoticeActivity extends GosBaseActivity { + + private ListView lvNotice; + private TextView tvNoNotice; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_notice); + +// setActionBar(true, true, R.string.msg_xnotice); + initView(); +// initData(); + } + + private void initView(){ + lvNotice=(ListView) findViewById(R.id.lvNotice); + tvNoNotice=(TextView) findViewById(R.id.tvNoNotice); + } + +// private void initData(){ +// NoticeDBService dbService= new NoticeDBService(this); +// ArrayList lsNotice=dbService.getNoticeList(); +// +// if(lsNotice!=null&&lsNotice.size()>0){ +// lvNotice.setVisibility(View.VISIBLE); +// tvNoNotice.setVisibility(View.GONE); +// +// NoticeAdapter na=new NoticeAdapter(this, lsNotice); +// lvNotice.setAdapter(na); +// }else{ +// lvNotice.setVisibility(View.GONE); +// tvNoNotice.setVisibility(View.VISIBLE); +// } +// } + + @Override + public void onResume() { + super.onResume(); +// initData(); + } + + @Override + public void onPause() { + super.onPause(); + } + + public boolean onOptionsItemSelected(MenuItem menu) { + super.onOptionsItemSelected(menu); + switch (menu.getItemId()) { + case android.R.id.home: + finish(); + break; + default: + break; + } + + return true; + } + + @Override + public void onBackPressed() { + finish(); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceListAcitivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceListAcitivity.java new file mode 100644 index 0000000..5524467 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceListAcitivity.java @@ -0,0 +1,233 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentStatePagerAdapter; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.CommonModule.NoScrollViewPager; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.DateUtil; +import com.gizwits.opensource.appkit.view.ViewPagerIndicator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class SharedDeviceListAcitivity extends GosBaseActivity { + + private List tabList; + private List myfragmentlist; + private String token; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_gos_shared_device_list); + + setToolBar(true, R.string.sharedlist); + initData(); + initView(); + } + + // 初始化tab标签中应该显示的文字 + private void initData() { + + token = spf.getString("Token", ""); + + myfragmentlist = new ArrayList(); + + SharedFragment ment1 = new SharedFragment(); + + InvitedFragment ment2 = new InvitedFragment(); + + + myfragmentlist.add(ment1); + myfragmentlist.add(ment2); + + tabList = new ArrayList(); + tabList.add(getResources().getString(R.string.shared)); + tabList.add(getResources().getString(R.string.invited)); + } + + private void initView() { + + ViewPagerIndicator indicator = (ViewPagerIndicator) findViewById( + R.id.vpi_indicator); + + indicator.setVisibleTabCount(2); + indicator.setTabItemTitles(tabList); + NoScrollViewPager vp_shared = (NoScrollViewPager) findViewById(R.id.vp_shared_list); + + vp_shared.setNoScroll(true); + + vp_shared.setAdapter(new myFragmentAdapter(getSupportFragmentManager())); + + indicator.setViewPager(vp_shared, 0); + + indicator.setOnPageChangeListener(new ViewPagerIndicator.PageChangeListener() { + + @Override + public void onPageSelected(int position) { + GosConstant.nowPager = position; + + switch (GosConstant.nowPager) { + case 0: + + break; + + case 1: + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingToMe, null); + break; + + default: + break; + } + } + + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + + } + + @Override + public void onPageScrollStateChanged(int state) { + + } + }); + } + + class myFragmentAdapter extends FragmentStatePagerAdapter { + + public myFragmentAdapter(FragmentManager fm) { + super(fm); + } + + @Override + public Fragment getItem(int arg0) { + + if (arg0 == 0) { + SharedFragment shared = new SharedFragment(); + + return shared; + } else { + InvitedFragment shared = (InvitedFragment) myfragmentlist.get(arg0); + + return shared; + + } + + } + + @Override + public int getCount() { + return 2; + } + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + break; + + } + + return super.onOptionsItemSelected(item); + } + + @Override + protected void onResume() { + // TODO Auto-generated method stub + super.onResume(); + + initListener(); + } + + // 初始化接口数据 + private void initListener() { + + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didGetDeviceSharingInfos(GizWifiErrorCode result, String deviceID, + List deviceSharingInfos) { + super.didGetDeviceSharingInfos(result, deviceID, deviceSharingInfos); + + + if (deviceSharingInfos != null) { + Collections.sort(deviceSharingInfos, new Comparator() { + + @Override + public int compare(GizDeviceSharingInfo arg0, GizDeviceSharingInfo arg1) { + + String updatedAt = DateUtil.utc2Local(arg0.getUpdatedAt()); + String updatedAt2 = DateUtil.utc2Local(arg1.getUpdatedAt()); + + int diff = (int) DateUtil.getDiff(updatedAt2, updatedAt); + + return diff; + } + + }); + } + + GosConstant.newmydeviceSharingInfos = deviceSharingInfos; + + InvitedFragment fragment = (InvitedFragment) myfragmentlist.get(1); + TextView myview = fragment.getmyview(); + if (deviceSharingInfos.size() == 0) { + + myview.setVisibility(View.VISIBLE); + myview.setText(getResources().getString(R.string.no_guest_users)); + } else { + myview.setVisibility(View.GONE); + } + + InvitedFragment.myadapter getmyadapter = fragment.getmyadapter(); + getmyadapter.notifyDataSetChanged(); + + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceListAcitivity.this, toastError(result), 2).show(); + } + + + } + + @Override + public void didAcceptDeviceSharing(GizWifiErrorCode result, int sharingID) { + super.didAcceptDeviceSharing(result, sharingID); + + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceListAcitivity.this, toastError(result), 2).show(); + } + + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingToMe, null); + } + + }); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceManagerActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceManagerActivity.java new file mode 100644 index 0000000..d21fe3b --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceManagerActivity.java @@ -0,0 +1,282 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.os.Bundle; +import android.os.Message; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentStatePagerAdapter; +import android.view.MenuItem; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo; +import com.gizwits.gizwifisdk.api.GizUserInfo; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.CommonModule.NoScrollViewPager; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.DateUtil; +import com.gizwits.opensource.appkit.view.ViewPagerIndicator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class SharedDeviceManagerActivity extends GosBaseActivity { + + private List tabList; + private String productname; + private String deviceid; + private List myfragmentlist; + private int viewPagerSelected = 0; + private boolean isgetsharing; + private String token; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_gos_shared_device_list); + + setToolBar(true, R.string.sharedmanager); + GosConstant.isEdit = false; + initData(); + initView(); + token = spf.getString("Token", ""); + + } + + @Override + protected void onResume() { + super.onResume(); + + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didSharingDevice(GizWifiErrorCode result, String deviceID, int sharingID, Bitmap QRCodeImage) { + super.didSharingDevice(result, deviceID, sharingID, QRCodeImage); + + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceManagerActivity.this, toastError(result), 1).show(); + } + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingByMe, deviceid); + } + + + @Override + public void didModifySharingInfo(GizWifiErrorCode result, int sharingID) { + super.didModifySharingInfo(result, sharingID); + + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceManagerActivity.this, toastError(result), 1).show(); + } + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingByMe, deviceid); + + } + + @Override + public void didGetDeviceSharingInfos(GizWifiErrorCode result, String deviceID, + List deviceSharingInfos) { + super.didGetDeviceSharingInfos(result, deviceID, deviceSharingInfos); + + if (deviceSharingInfos != null) { + Collections.sort(deviceSharingInfos, new Comparator() { + + @Override + public int compare(GizDeviceSharingInfo arg0, GizDeviceSharingInfo arg1) { + + String updatedAt = DateUtil.utc2Local(arg0.getUpdatedAt()); + String updatedAt2 = DateUtil.utc2Local(arg1.getUpdatedAt()); + + int diff = (int) DateUtil.getDiff(updatedAt2, updatedAt); + + return diff; + } + + }); + } + GosConstant.mydeviceSharingInfos = deviceSharingInfos; + SharedStateFragment fragment = (SharedStateFragment) myfragmentlist.get(0); + Message msg = new Message(); + msg.what = 1; + fragment.handler.sendMessage(msg); + SharedUserFragment fragment1 = (SharedUserFragment) myfragmentlist.get(1); + Message msg1 = new Message(); + msg1.what = 1; + fragment1.handler.sendMessage(msg1); + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceManagerActivity.this, toastError(result), 1).show(); + } + + } + + @Override + public void didGetBindingUsers(GizWifiErrorCode result, String deviceID, List bindUsers) { + super.didGetBindingUsers(result, deviceID, bindUsers); + GosConstant.mybindUsers = bindUsers; + SharedUserFragment fragment = (SharedUserFragment) myfragmentlist.get(1); + SharedUserFragment.myadapter getmyadapter = fragment.getmyadapter(); + + if (getmyadapter != null) { + getmyadapter.notifyDataSetChanged(); + } + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceManagerActivity.this, toastError(result), 1).show(); + } + + } + + @Override + public void didUnbindUser(GizWifiErrorCode result, String deviceID, String guestUID) { + // TODO Auto-generated method stub + super.didUnbindUser(result, deviceID, guestUID); + + GizDeviceSharing.getBindingUsers(token, deviceid); + + if (result.ordinal() != 0) { + Toast.makeText(SharedDeviceManagerActivity.this, toastError(result), 1).show(); + } + } + + @Override + public void didRevokeDeviceSharing(GizWifiErrorCode result, int sharingID) { + // TODO Auto-generated method stub + super.didRevokeDeviceSharing(result, sharingID); + + if (result.ordinal() == 0) { + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingByMe, deviceid); + } else { + + Toast.makeText(SharedDeviceManagerActivity.this, toastError(result), 1).show(); + } + } + }); + + + } + + // 初始化tab标签中应该显示的文字 + private void initData() { + productname = getIntent().getStringExtra("productname"); + deviceid = getIntent().getStringExtra("deviceid"); + isgetsharing = getIntent().getBooleanExtra("isgetsharing", false); + + tabList = new ArrayList(); + tabList.add(getResources().getString(R.string.sharedstated)); + tabList.add(getResources().getString(R.string.boundusers)); + + SharedStateFragment shared = new SharedStateFragment(); + + SharedUserFragment shared1 = new SharedUserFragment(); + + myfragmentlist = new ArrayList(); + + myfragmentlist.add(shared); + myfragmentlist.add(shared1); + } + + private void initView() { + + ViewPagerIndicator indicator = (ViewPagerIndicator) findViewById( + R.id.vpi_indicator); + + indicator.setVisibleTabCount(2); + indicator.setTabItemTitles(tabList); + NoScrollViewPager vp_shared = (NoScrollViewPager) findViewById( + R.id.vp_shared_list); + + vp_shared.setNoScroll(true); + + vp_shared.setAdapter(new myFragmentAdapter(getSupportFragmentManager())); + + indicator.setViewPager(vp_shared, 0); + indicator.setOnPageChangeListener(new ViewPagerIndicator.PageChangeListener() { + + @Override + public void onPageSelected(int position) { + + viewPagerSelected = position; + + if (position == 0 && isgetsharing) { + SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE); + String token = spf.getString("Token", ""); + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingByMe, deviceid); + + } else if (position == 1 && isgetsharing) { + SharedStateFragment fragment3 = (SharedStateFragment) myfragmentlist.get(0); + Message msg = new Message(); + msg.what = 2; + fragment3.handler.sendMessage(msg); + SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE); + String token = spf.getString("Token", ""); + GizDeviceSharing.getBindingUsers(token, deviceid); + } + + } + + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + + } + + @Override + public void onPageScrollStateChanged(int state) { + + } + }); + } + + class myFragmentAdapter extends FragmentStatePagerAdapter { + + public myFragmentAdapter(FragmentManager fm) { + super(fm); + } + + @Override + public Fragment getItem(int arg0) { + + Bundle b = new Bundle(); + b.putString("productname", productname); + b.putString("deviceid", deviceid); + + Fragment fragment = myfragmentlist.get(arg0); + + fragment.setArguments(b); + + return fragment; + + } + + @Override + public int getCount() { + return myfragmentlist.size(); + } + + } + + + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + + finish(); + break; + + } + + return super.onOptionsItemSelected(item); + } + + // 刷新menu的方法 + private void refreshMenu() { + // 核心是Activity这个方法 + supportInvalidateOptionsMenu(); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedFragment.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedFragment.java new file mode 100644 index 0000000..1f4c85d --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedFragment.java @@ -0,0 +1,212 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Intent; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.BaseAdapter; +import android.widget.ListView; +import android.widget.TextView; + +import com.gizwits.gizwifisdk.api.GizWifiDevice; +import com.gizwits.gizwifisdk.api.GizWifiSDK; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.R; + +import java.util.ArrayList; +import java.util.List; + +public class SharedFragment extends Fragment { + + // 定义俩个整形值用来区分当前要显示的是哪个view对象 + // 如果是1的话就共享列表, 2的话就是受邀列表 + private int mytpye = -1; + private List list; + private TextView myview; + private myadapter myadapter1; + private ListView mListView; + + private View contextView; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + + // 动态找到布局文件,再从这个布局中find出TextView对象 + contextView = inflater.inflate(R.layout.activity_gos_shared_list, container, false); + + initView(); + initData(); + initEvent(); + return contextView; + } + + private void initView() { + mListView = (ListView) contextView.findViewById(R.id.mysharedlist); + myview = (TextView) contextView.findViewById(R.id.shareddeviceproductname); + } + + + private void initEvent() { + myadapter1 = new myadapter(); + + mListView.setAdapter(myadapter1); + + mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + + @Override + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { + + GizWifiDevice wifiDevice = list.get(arg2); + + GizDeviceSharingUserRole sharingRole = wifiDevice.getSharingRole(); + int role = sharingRole.ordinal(); + boolean isgetsharing = false; + + if (role == 2) { + isgetsharing = true; + } + + mListView.setEnabled(false); + mListView.postDelayed(new Runnable() { + @Override + public void run() { + mListView.setEnabled(true); + } + }, 1000); + + Intent tent = new Intent(getActivity(), SharedDeviceManagerActivity.class); + + GosConstant.mybindUsers.clear(); + GosConstant.mydeviceSharingInfos.clear(); + tent.putExtra("productname", wifiDevice.getProductName()); + tent.putExtra("deviceid", wifiDevice.getDid()); + tent.putExtra("isgetsharing", isgetsharing); + startActivity(tent); + } + }); + } + + // 获取当前的设备列表 + private void initData() { + + list = new ArrayList(); + List deviceList = GizWifiSDK.sharedInstance().getDeviceList(); + + for (GizWifiDevice gizWifiDevice : deviceList) { + + GizDeviceSharingUserRole sharingRole = gizWifiDevice.getSharingRole(); + + if (sharingRole != null) { + + if (sharingRole.ordinal() == 1 || sharingRole.ordinal() == 2) { + list.add(gizWifiDevice); + } + } + + } + + if (list.size() == 0) { + myview.setVisibility(View.VISIBLE); + myview.setText(getResources().getString(R.string.you_have_no_device)); + + } else { + myview.setVisibility(View.GONE); + } + + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + } + + // listview的adapter,通过刷新的bound对象的属性值来判断当前应该现实的是什么 + class myadapter extends BaseAdapter { + + @Override + public int getCount() { + return list.size(); + } + + @Override + public Object getItem(int arg0) { + return null; + } + + @Override + public long getItemId(int arg0) { + return 0; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + View view = convertView; + Holder holder; + + if (view == null) { + view = View.inflate(getActivity(), R.layout.item_gos_device_shared_list, null); + holder = new Holder(view); + view.setTag(holder); + } else { + holder = (Holder) view.getTag(); + } + + holder.getTvDeviceName().setText(list.get(position).getProductName()); + holder.getTvDeviceMac().setText(list.get(position).getMacAddress()); + GizDeviceSharingUserRole sharingRole = list.get(position).getSharingRole(); + if (sharingRole.ordinal() == 1) { + holder.getTvDeviceStatus().setVisibility(View.VISIBLE); + holder.getTvDeviceStatus().setText(getString(R.string.not_sharing)); + } else if (sharingRole.ordinal() == 2) { + holder.getTvDeviceStatus().setVisibility(View.GONE); + } + return view; + } + + } + + public myadapter getmyadapter() { + return myadapter1; + } + + // 设备列表对应的holder + class Holder { + View view; + + public Holder(View view) { + this.view = view; + } + + private TextView tvDeviceMac, tvDeviceStatus, tvDeviceName; + + + public TextView getTvDeviceMac() { + if (null == tvDeviceMac) { + tvDeviceMac = (TextView) view.findViewById(R.id.tvDeviceMac); + } + return tvDeviceMac; + } + + public TextView getTvDeviceStatus() { + if (null == tvDeviceStatus) { + tvDeviceStatus = (TextView) view.findViewById(R.id.tvDeviceStatus); + } + return tvDeviceStatus; + } + + public TextView getTvDeviceName() { + if (null == tvDeviceName) { + tvDeviceName = (TextView) view.findViewById(R.id.tvDeviceName); + } + return tvDeviceName; + } + + } +} + + diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedStateFragment.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedStateFragment.java new file mode 100644 index 0000000..daff47c --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedStateFragment.java @@ -0,0 +1,600 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.support.v4.app.Fragment; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.BaseAdapter; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo; +import com.gizwits.gizwifisdk.api.GizUserInfo; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingStatus; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingType; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingWay; +import com.gizwits.gizwifisdk.enumration.GizUserAccountType; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.AssetsUtils; +import com.gizwits.opensource.appkit.utils.DateUtil; +import com.gizwits.opensource.appkit.view.SlideListView2; + + +public class SharedStateFragment extends Fragment { + + // 定义俩个整形值用来区分当前要显示的是哪个view对象 + // 如果是1的话就共享列表, 2的话就是受邀列表 + private int mytpye = -1; + + + View contextView; + private String deviceID; + private myadapter myadapter; + + private String token; + + private LinearLayout addshared; + + private SlideListView2 mListView; + + private String productname; + + private TextView shareddeviceproductname; + private TextView tvSharedTo; + private LinearLayout llSharedTo; + private LinearLayout llAddShared; + private LinearLayout rename; + private SharedPreferences spf; + private LinearLayout cancel; + private RelativeLayout rlCancel; + + private static final String TAG = "mySharedFragment3"; + Handler handler = new Handler() { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + // 当GosConstant.mydeviceSharingInfos 在Activity中被赋值后执行 + case 1: + if (GosConstant.mydeviceSharingInfos.size() == 0) { + String s = getResources().getString(R.string.have_not_been_shared); + String ss = s.substring(3, s.length()); + StringBuilder sb = new StringBuilder(productname); + shareddeviceproductname.setText(sb.append(ss)); + shareddeviceproductname.setVisibility(View.VISIBLE); + llSharedTo.setVisibility(View.GONE); + rename.setVisibility(View.GONE); + llAddShared.setVisibility(View.VISIBLE); + } else { + tvSharedTo.setText(productname + getResources().getString(R.string.sharedto)); + llSharedTo.setVisibility(View.VISIBLE); + shareddeviceproductname.setVisibility(View.GONE); + if (rlCancel.getVisibility() == View.GONE) { + rename.setVisibility(View.VISIBLE); + llAddShared.setVisibility(View.VISIBLE); + } + + } + + if (myadapter == null) { + myadapter = new myadapter(true); + mListView.setAdapter(myadapter); + } else { + mListView.setAdapter(myadapter); + } + + break; + case 2: + mListView.initSlideMode(SlideListView2.MOD_RIGHT); + mListView.setOnItemClickListener(null); + rlCancel.setVisibility(View.GONE); + llAddShared.setVisibility(View.VISIBLE); + break; + } + } + }; + + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + + // 动态找到布局文件,再从这个布局中find出TextView对象 + contextView = inflater.inflate(R.layout.activity_gos_shared_manage, container, false); + initView(); + initData(); + initEvent(); + return contextView; + } + + private void initView() { + mListView = (SlideListView2) contextView.findViewById(R.id.mysharedlist); + mListView.initSlideMode(SlideListView2.MOD_RIGHT); + llAddShared = (LinearLayout) contextView.findViewById(R.id.llAddShared); + rlCancel = (RelativeLayout) contextView.findViewById(R.id.rlCancel); + addshared = (LinearLayout) contextView.findViewById(R.id.addshared); + rename = (LinearLayout) contextView.findViewById(R.id.rename); + cancel = (LinearLayout) contextView.findViewById(R.id.cancel); + shareddeviceproductname = (TextView) contextView.findViewById(R.id.shareddeviceproductname); + tvSharedTo = (TextView) contextView.findViewById(R.id.tvSharedTo); + llSharedTo = (LinearLayout) contextView.findViewById(R.id.llSharedTo); + + } + + private void initData() { + Bundle arguments = getArguments(); + productname = arguments.getString("productname"); + spf = getActivity().getSharedPreferences("set", Context.MODE_PRIVATE); + token = spf.getString("Token", ""); + deviceID = getArguments().getString("deviceid"); + } + + @Override + public void onResume() { + super.onResume(); + GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingByMe, deviceID); + } + + private void initEvent() { + addshared.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + if (!TextUtils.isEmpty(spf.getString("UserName", "")) && !TextUtils.isEmpty(spf.getString("PassWord", ""))) { + Intent tent = new Intent(getActivity(), addSharedActivity.class); + tent.putExtra("productname", productname); + tent.putExtra("did", deviceID); + startActivity(tent); + } else { + Toast.makeText(getContext(), getString(R.string.please_login), 2000).show(); + } + } + }); + rename.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + mListView.initSlideMode(SlideListView2.MOD_FORBID); + llAddShared.setVisibility(View.GONE); + rlCancel.setVisibility(View.VISIBLE); + myadapter = new myadapter(false); + mListView.setAdapter(myadapter); + mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, final int position, long id) { + TextView name = (TextView) view.findViewById(R.id.tvDeviceName); + + final Dialog dialog = new AlertDialog.Builder(getContext(), R.style.edit_dialog_style) + .setView(new EditText(getContext())).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_rename); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + final EditText remarkname = (EditText) window.findViewById(R.id.remarkname); + + remarkname.setText(name.getText().toString()); + remarkname.setSelection(name.getText().toString().length()); + RelativeLayout rlClear = (RelativeLayout) window.findViewById(R.id.rlClear); + LinearLayout llyes = (LinearLayout) window.findViewById(R.id.llSure); + LinearLayout llno = (LinearLayout) window.findViewById(R.id.llNo); + + llno.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + dialog.dismiss(); + } + }); + + rlClear.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + remarkname.setText(""); + } + }); + + llyes.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + String token = spf.getString("Token", ""); + GizDeviceSharingInfo gizDeviceSharingInfo = GosConstant.mydeviceSharingInfos.get(position); + GizDeviceSharing.modifySharingInfo(token, gizDeviceSharingInfo.getId(), + remarkname.getText().toString()); + dialog.dismiss(); + + } + }); + } + }); + } + }); + + cancel.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + mListView.initSlideMode(SlideListView2.MOD_RIGHT); + mListView.setOnItemClickListener(null); + rlCancel.setVisibility(View.GONE); + llAddShared.setVisibility(View.VISIBLE); + myadapter = new myadapter(true); + mListView.setAdapter(myadapter); + } + }); + + + } + + public myadapter getmyadapter() { + return myadapter; + } + + public RelativeLayout getRelativeLayout() { + return rlCancel; + } + + public SlideListView2 getListview() { + return mListView; + } + + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + } + + // listview的adapter,通过刷新的bound对象的属性值来判断当前应该现实的是什么 + class myadapter extends BaseAdapter { + + private String uid; + + private boolean isShow; + + @Override + public int getCount() { + return GosConstant.mydeviceSharingInfos.size(); + } + + public myadapter(boolean isShow) { + this.isShow = isShow; + } + + @Override + public Object getItem(int arg0) { + return null; + } + + @Override + public long getItemId(int arg0) { + return 0; + } + + @Override + public View getView(final int position, View convertView, ViewGroup parent) { + + ViewHolder holder; + + if (convertView == null) { + convertView = LayoutInflater.from(getContext()).inflate( + R.layout.gos_shared_by_me_activity, null); + holder = new ViewHolder(); + holder.rlmyhome = (RelativeLayout) convertView.findViewById(R.id.rlmyhome); + holder.tvDeviceName = (TextView) convertView.findViewById(R.id.tvDeviceName); + holder.tvDeviceMac = (TextView) convertView.findViewById(R.id.tvDeviceMac); + holder.tvDeviceStatus = (TextView) convertView.findViewById(R.id.tvDeviceStatus); + holder.delete2name = (TextView) convertView.findViewById(R.id.delete2name); + holder.delete3name = (TextView) convertView.findViewById(R.id.delete3name); + holder.delete2 = (LinearLayout) convertView.findViewById(R.id.delete2); + holder.delete3 = (LinearLayout) convertView.findViewById(R.id.delete3); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + + holder.delete2.setVisibility(View.INVISIBLE); + + holder.delete2name.setText(getResources().getString(R.string.cancel_sharing)); + + holder.delete3name.setText(getResources().getString(R.string.sharedagain)); + + GizDeviceSharingInfo gizDeviceSharingInfo = GosConstant.mydeviceSharingInfos.get(position); + + final int id = gizDeviceSharingInfo.getId(); + + final String myid = gizDeviceSharingInfo.getDeviceID(); + + GizUserInfo userInfo = gizDeviceSharingInfo.getUserInfo(); + + // 更新时间 + String updatedAt = gizDeviceSharingInfo.getUpdatedAt(); + + // 超时时间 + String expiredAt = gizDeviceSharingInfo.getExpiredAt(); + + uid = userInfo.getUid(); + + String email = userInfo.getEmail(); + + String phone = userInfo.getPhone(); + + String username = userInfo.getUsername(); + + String remark = userInfo.getRemark(); + + if (!TextUtils.isEmpty(uid) && !uid.equals("null")) { + String myuid = uid.substring(0, 3) + "***" + uid.substring(uid.length() - 4, uid.length()); + + holder.tvDeviceName.setText(myuid); + + } + + if (!TextUtils.isEmpty(email) && !email.equals("null")) { + + holder.tvDeviceName.setText(email); + + } + + if (!TextUtils.isEmpty(phone) && !phone.equals("null")) { + + holder.tvDeviceName.setText(phone); + + } + + if (!TextUtils.isEmpty(username) && !username.equals("null")) { + + holder.tvDeviceName.setText(username); + + } + + if (!TextUtils.isEmpty(remark) && !remark.equals("null")) { + + holder.tvDeviceName.setText(remark); + + } + + updatedAt = DateUtil.utc2Local(updatedAt); + + expiredAt = DateUtil.utc2Local(expiredAt); + + holder.tvDeviceMac.setText(updatedAt); + + GizDeviceSharingStatus status = gizDeviceSharingInfo.getStatus(); + + int ordinal = status.ordinal(); + if (isShow) { + holder.tvDeviceStatus.setVisibility(View.VISIBLE); + } else { + holder.tvDeviceStatus.setVisibility(View.GONE); + } + switch (ordinal) { + case 0: + + String timeByFormat = DateUtil.getCurTimeByFormat("yyyy-MM-dd HH:mm:ss"); + long diff = DateUtil.getDiff(timeByFormat, expiredAt); + + if (diff > 0) { + holder.delete3name.setText(getResources().getString(R.string.delete)); + + holder.delete2name.setText(getResources().getString(R.string.sharedagain)); + + holder.rlmyhome.setPadding(0, 0, AssetsUtils.diptopx(getContext(), -181), 0); + holder.delete2.setVisibility(View.VISIBLE); + holder.delete3.setVisibility(View.VISIBLE); + holder.delete2.setBackgroundColor(getResources().getColor(R.color.back_gray)); + holder.delete3.setBackgroundColor(getResources().getColor(R.color.unbind)); + + holder.delete2.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.sharingDevice(token, myid, GizDeviceSharingWay.GizDeviceSharingByNormal, + GosConstant.mydeviceSharingInfos.get(position).getUserInfo().getUid(), + GizUserAccountType.GizUserOther); + } + }); + + holder.delete3.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.revokeDeviceSharing(token, id); + } + }); + + holder.tvDeviceStatus.setText(getResources().getString(R.string.timeout)); + } else { + holder.delete3.setVisibility(View.GONE); + holder.rlmyhome.setPadding(0, 0, AssetsUtils.diptopx(getContext(), -91), 0); + holder.delete2.setVisibility(View.VISIBLE); + holder.delete2.setBackgroundColor(getResources().getColor(R.color.unbind)); + holder.delete2name.setText(getResources().getString(R.string.cancel_sharing)); + final String s = holder.tvDeviceName.getText().toString(); + holder.delete2.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + + quitAlert(getActivity(), s, id); + } + }); + holder.tvDeviceStatus.setText(getResources().getString(R.string.waitforaccept)); + } + break; + + case 1: + holder.tvDeviceStatus.setText(getResources().getString(R.string.accept)); + holder.delete3.setVisibility(View.GONE); + holder.rlmyhome.setPadding(0, 0, AssetsUtils.diptopx(getContext(), -91), 0); + holder.delete2.setVisibility(View.VISIBLE); + holder.delete2.setBackgroundColor(getResources().getColor(R.color.unbind)); + holder.delete2name.setText(getResources().getString(R.string.cancel_sharing)); + final String s = holder.tvDeviceName.getText().toString(); + holder.delete2.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + + quitAlert(getActivity(), s, id); + } + }); + + break; + + case 2: + holder.rlmyhome.setPadding(0, 0, AssetsUtils.diptopx(getContext(), -181), 0); + holder.delete2.setVisibility(View.VISIBLE); + holder.delete3.setVisibility(View.VISIBLE); + holder.delete2.setBackgroundColor(getResources().getColor(R.color.back_gray)); + holder.delete3.setBackgroundColor(getResources().getColor(R.color.unbind)); + holder.tvDeviceStatus.setText(getResources().getString(R.string.refuse)); + + holder.delete3name.setText(getResources().getString(R.string.delete)); + + holder.delete2name.setText(getResources().getString(R.string.sharedagain)); + + + holder.delete2.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.sharingDevice(token, myid, GizDeviceSharingWay.GizDeviceSharingByNormal, + GosConstant.mydeviceSharingInfos.get(position).getUserInfo().getUid(), + GizUserAccountType.GizUserOther); + } + }); + + holder.delete3.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.revokeDeviceSharing(token, id); + } + }); + + // tvDeviceStatus.setText(getResources().getString(R.string.timeout)); + + break; + + case 3: + holder.rlmyhome.setPadding(0, 0, AssetsUtils.diptopx(getContext(), -181), 0); + holder.delete2.setVisibility(View.VISIBLE); + holder.delete3.setVisibility(View.VISIBLE); + holder.delete2.setBackgroundColor(getResources().getColor(R.color.back_gray)); + holder.delete3.setBackgroundColor(getResources().getColor(R.color.unbind)); + holder.tvDeviceStatus.setText(getResources().getString(R.string.cancelled)); + + holder.delete3name.setText(getResources().getString(R.string.delete)); + + + holder.delete2name.setText(getResources().getString(R.string.sharedagain)); + + // delete2name.setGravity(Gravity.CENTER); + + holder.delete2.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.sharingDevice(token, myid, GizDeviceSharingWay.GizDeviceSharingByNormal, + GosConstant.mydeviceSharingInfos.get(position).getUserInfo().getUid(), + GizUserAccountType.GizUserOther); + } + }); + + holder.delete3.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + GizDeviceSharing.revokeDeviceSharing(token, id); + } + }); + + break; + + default: + break; + } + + + return convertView; + } + + } + + class ViewHolder { + TextView tvDeviceName; + TextView tvDeviceMac; + TextView tvDeviceStatus; + TextView delete2name; + TextView delete3name; + LinearLayout delete2; + LinearLayout delete3; + RelativeLayout rlmyhome; + } + + protected void quitAlert(Context context, String username, final int uid2) { + final Dialog dialog = new AlertDialog.Builder(getActivity(), R.style.alert_dialog_style) + .setView(new EditText(getActivity())).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + TextView view3 = (TextView) window.findViewById(R.id.textView3); + view3.setVisibility(View.VISIBLE); + TextView tv = (TextView) window.findViewById(R.id.tv_prompt); + + String userstring = getResources().getString(R.string.deleteuserpremiss); + String[] split = userstring.split("xxx"); + + tv.setText(split[0] + username + split[1]); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + // GizDeviceSharing.unbindGuestUser(token, deviceID, uid2); + + GizDeviceSharing.revokeDeviceSharing(token, uid2); + dialog.cancel(); + } + }); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedUserFragment.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedUserFragment.java new file mode 100644 index 0000000..1b42953 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/SharedUserFragment.java @@ -0,0 +1,275 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.support.v4.app.Fragment; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.BaseAdapter; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizUserInfo; +import com.gizwits.opensource.appkit.CommonModule.GosConstant; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.AssetsUtils; +import com.gizwits.opensource.appkit.utils.DateUtil; +import com.gizwits.opensource.appkit.view.SlideListView2; + + +public class SharedUserFragment extends Fragment { + + // 定义俩个整形值用来区分当前要显示的是哪个view对象 + // 如果是1的话就共享列表, 2的话就是受邀列表 + private int mytpye = -1; + private myadapter myadapter; + private String deviceID; + private String token; + private String uid; + private String productname; + private TextView shareddeviceproductname; + private SlideListView2 mListView; + + Handler handler = new Handler() { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case 1: + if (GosConstant.mydeviceSharingInfos.size() == 0) { + String s = getResources().getString(R.string.have_not_been_shared); + String ss = s.substring(3, s.length()); + StringBuilder sb = new StringBuilder(productname); + shareddeviceproductname.setText(sb.append(ss)); + shareddeviceproductname.setVisibility(View.VISIBLE); + llSharedTo.setVisibility(View.GONE); + } else { + tvSharedTo.setText(productname + getResources().getString(R.string.sharedto)); + llSharedTo.setVisibility(View.VISIBLE); + shareddeviceproductname.setVisibility(View.GONE); + } + myadapter = new myadapter(); + mListView.setAdapter(myadapter); + break; + } + } + }; + private TextView tvSharedTo; + private LinearLayout llSharedTo; + + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + + // 动态找到布局文件,再从这个布局中find出TextView对象 + View contextView = inflater.inflate(R.layout.activity_gos_shared_list, container, false); + mListView = (SlideListView2) contextView.findViewById(R.id.mysharedlist); + mListView.initSlideMode(SlideListView2.MOD_RIGHT); + + shareddeviceproductname = (TextView) contextView.findViewById(R.id.shareddeviceproductname); + tvSharedTo = (TextView) contextView.findViewById(R.id.tvSharedTo); + llSharedTo = (LinearLayout) contextView.findViewById(R.id.llSharedTo); + Bundle arguments = getArguments(); + productname = arguments.getString("productname"); + + + initdata(); + return contextView; + } + + public myadapter getmyadapter() { + return myadapter; + } + + private void initdata() { + SharedPreferences spf = getActivity().getSharedPreferences("set", Context.MODE_PRIVATE); + token = spf.getString("Token", ""); + uid = spf.getString("Uid", ""); + + deviceID = getArguments().getString("deviceid"); + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + } + + // listview的adapter,通过刷新的bound对象的属性值来判断当前应该现实的是什么 + class myadapter extends BaseAdapter { + + private String uid; + + @Override + public int getCount() { + return GosConstant.mybindUsers.size(); + } + + @Override + public Object getItem(int arg0) { + return null; + } + + @Override + public long getItemId(int arg0) { + return 0; + } + + @Override + public View getView(final int position, View convertView, ViewGroup parent) { + ViewHolder holder; + + if (convertView == null) { + convertView = LayoutInflater.from(getContext()).inflate( + R.layout.gos_shared_by_me_activity, null); + holder = new ViewHolder(); + holder.rlmyhome = (RelativeLayout) convertView.findViewById(R.id.rlmyhome); + holder.tvDeviceName = (TextView) convertView.findViewById(R.id.tvDeviceName); + holder.tvDeviceMac = (TextView) convertView.findViewById(R.id.tvDeviceMac); + holder.tvDeviceStatus = (TextView) convertView.findViewById(R.id.tvDeviceStatus); + holder.delete2name = (TextView) convertView.findViewById(R.id.delete2name); + holder.delete3name = (TextView) convertView.findViewById(R.id.delete3name); + holder.delete2 = (LinearLayout) convertView.findViewById(R.id.delete2); + holder.delete3 = (LinearLayout) convertView.findViewById(R.id.delete3); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + + holder.rlmyhome.setPadding(0, 0, AssetsUtils.diptopx(getContext(), -90), 0); + holder.delete3.setVisibility(View.GONE); + + holder.delete2name.setText(getResources().getString(R.string.cancel_sharing)); + + holder.delete2.setVisibility(View.VISIBLE); + + holder.delete2name.setText(getResources().getString(R.string.cancel_sharing)); + + holder.tvDeviceStatus.setVisibility(View.GONE); + + GizUserInfo userInfo = GosConstant.mybindUsers.get(position); + + uid = userInfo.getUid(); + + String email = userInfo.getEmail(); + + String phone = userInfo.getPhone(); + + String username = userInfo.getUsername(); + + String remark = userInfo.getRemark(); + String deviceBindTime = userInfo.getDeviceBindTime(); + + deviceBindTime = DateUtil.utc2Local(deviceBindTime); + holder.tvDeviceMac.setText(deviceBindTime); + + if (!TextUtils.isEmpty(uid) && !uid.equals("null")) { + String myuid = uid.substring(0, 3) + "***" + uid.substring(uid.length() - 4, uid.length()); + holder.tvDeviceName.setText(myuid); + + } + + if (!TextUtils.isEmpty(email) && !email.equals("null")) { + + holder.tvDeviceName.setText(email); + + } + + if (!TextUtils.isEmpty(phone) && !phone.equals("null")) { + + holder.tvDeviceName.setText(phone); + + } + + if (!TextUtils.isEmpty(username) && !username.equals("null")) { + + holder.tvDeviceName.setText(username); + + } + + if (!TextUtils.isEmpty(remark) && !remark.equals("null")) { + + holder.tvDeviceName.setText(remark); + + } + final String s = holder.tvDeviceName.getText().toString(); + holder.delete2name.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View arg0) { + + quitAlert(getActivity(), s, GosConstant.mybindUsers.get(position).getUid()); + } + }); + + return convertView; + } + + } + + class ViewHolder { + TextView tvDeviceName; + TextView tvDeviceMac; + TextView tvDeviceStatus; + TextView delete2name; + TextView delete3name; + LinearLayout delete2; + LinearLayout delete3; + RelativeLayout rlmyhome; + } + + protected void quitAlert(Context context, String username, final String uid2) { + final Dialog dialog = new AlertDialog.Builder(getActivity(),R.style.alert_dialog_style) + .setView(new EditText(getActivity())).create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + + Window window = dialog.getWindow(); + window.setContentView(R.layout.alert_gos_quit); + WindowManager.LayoutParams layoutParams = window.getAttributes(); + layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; + window.setAttributes(layoutParams); + LinearLayout llNo, llSure; + llNo = (LinearLayout) window.findViewById(R.id.llNo); + llSure = (LinearLayout) window.findViewById(R.id.llSure); + + TextView view3 = (TextView) window.findViewById(R.id.textView3); + view3.setVisibility(View.VISIBLE); + TextView tv = (TextView) window.findViewById(R.id.tv_prompt); + + String userstring = getResources().getString(R.string.deleteuserpremiss); + String[] split = userstring.split("xxx"); + + tv.setText(split[0] + username + split[1]); + + llNo.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + dialog.cancel(); + } + }); + + llSure.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + GizDeviceSharing.unbindUser(token, deviceID, uid2); + dialog.cancel(); + } + }); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/addSharedActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/addSharedActivity.java new file mode 100644 index 0000000..7577934 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/addSharedActivity.java @@ -0,0 +1,88 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Intent; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; + +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.R; + + +public class addSharedActivity extends GosBaseActivity { + + private String productname; + private String did; + private LinearLayout devicetwoshared; + private LinearLayout usershared; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_gos_addshared); + setToolBar(true, R.string.addshared); + + initData(); + initView(); + } + + private void initView() { + usershared = (LinearLayout) findViewById(R.id.usershared); + devicetwoshared = (LinearLayout) findViewById(R.id.devicetwoshared); + } + + private void initData() { + Intent tent = getIntent(); + productname = tent.getStringExtra("productname"); + did = tent.getStringExtra("did"); + } + + // personalCenter_deviceSharing_qrcode-false-start + // 二维码分享 + public void devicetwoshared(View v) { + Intent tent = new Intent(this, twoSharedActivity.class); + tent.putExtra("productname", productname); + tent.putExtra("did", did); + startActivity(tent); + + devicetwoshared.setEnabled(false); + devicetwoshared.postDelayed(new Runnable() { + @Override + public void run() { + devicetwoshared.setEnabled(true); + } + }, 1000); + + } + //personalCenter_deviceSharing_qrcode-false-end + + // 用户账号分享 + + public void usershared(View v) { + + Intent tent = new Intent(this, userSharedActivity.class); + tent.putExtra("productname", productname); + tent.putExtra("did", did); + startActivity(tent); + + usershared.setEnabled(false); + usershared.postDelayed(new Runnable() { + @Override + public void run() { + usershared.setEnabled(true); + } + }, 1000); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/deviceSharedMessageActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/deviceSharedMessageActivity.java new file mode 100644 index 0000000..bf04326 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/deviceSharedMessageActivity.java @@ -0,0 +1,276 @@ +package com.gizwits.opensource.appkit.sharingdevice; + + +import android.app.ProgressDialog; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.support.v4.widget.SwipeRefreshLayout; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.api.GizMessage; +import com.gizwits.gizwifisdk.enumration.GizMessageStatus; +import com.gizwits.gizwifisdk.enumration.GizMessageType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.DateUtil; +import com.gizwits.opensource.appkit.view.SlideListView2; +import com.gizwits.opensource.appkit.view.VerticalSwipeRefreshLayout; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class deviceSharedMessageActivity extends GosBaseActivity implements SwipeRefreshLayout.OnRefreshListener { + + private List mymessageList = new ArrayList(); + private myadapter myadapter; + private String token; + private String myid = ""; + private int myposition = -1; + // 删除时需要用到的对话框 + private ProgressDialog progressDialog; + private TextView tvNoMessage; + private VerticalSwipeRefreshLayout mSwipeLayout; + + Handler handler = new Handler() { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + switch (msg.what) { + case 1: + mSwipeLayout.setRefreshing(false); + GizDeviceSharing.queryMessageList(token, GizMessageType.GizMessageSharing); + break; + } + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_device_shared_message_list); + setToolBar(true, R.string.devicesharedmess); + initView(); + initData(); + initProgressBar(); + } + + private void initProgressBar() { + progressDialog = new ProgressDialog(this); + String loadingText = getString(R.string.loadingtext); + progressDialog.setMessage(loadingText); + progressDialog.setCanceledOnTouchOutside(false); + } + + // 初始化分享设备的数据 + private void initData() { + // + // GizDeviceSharing.setListener(new GizDeviceSharingListener() { + // + // @Override + // public void didQueryMessageList(GizWifiErrorCode result, + // List messageList) { + // super.didQueryMessageList(result, messageList); + // + // mymessageList = messageList; + // myadapter.notifyDataSetChanged(); + // } + // + // }); + token = spf.getString("Token", ""); + GizDeviceSharing.queryMessageList(token, GizMessageType.GizMessageSharing); + // GizDeviceSharing.queryMessageList(token, + // GizMessageType.GizMessageSystem); + + } + + private void initView() { + + SlideListView2 devicelist = (SlideListView2) findViewById(R.id.devicelist); + tvNoMessage = (TextView) findViewById(R.id.tvNoMessage); + devicelist.initSlideMode(SlideListView2.MOD_RIGHT); + + myadapter = new myadapter(); + devicelist.setAdapter(myadapter); + + // 下拉刷新 + + mSwipeLayout = (VerticalSwipeRefreshLayout) findViewById(R.id.id_swipe_ly); + + mSwipeLayout.setOnRefreshListener(this); + mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, + android.R.color.holo_orange_light, android.R.color.holo_red_light); + + devicelist.setOnItemClickListener(new OnItemClickListener() { + + @Override + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { + + View redpoint = arg1.findViewById(R.id.redpoint); + + if (redpoint.getVisibility() == 0) { + redpoint.setVisibility(View.GONE); + GizMessage gizMessage = mymessageList.get(arg2); + + GizDeviceSharing.markMessageStatus(token, gizMessage.getId(), GizMessageStatus.GizMessageRead); + } + + } + }); + + } + + @Override + public void onRefresh() { + Message msg = new Message(); + msg.what = 1; + handler.sendMessageDelayed(msg, 2000); + } + + class myadapter extends BaseAdapter { + + @Override + public int getCount() { + + return mymessageList.size(); + } + + @Override + public Object getItem(int arg0) { + return null; + } + + @Override + public long getItemId(int arg0) { + return 0; + } + + @Override + public View getView(final int arg0, View arg1, ViewGroup arg2) { + + View view = View.inflate(deviceSharedMessageActivity.this, R.layout.activity_device_item, null); + + TextView mess = (TextView) view.findViewById(R.id.mess); + TextView timemess = (TextView) view.findViewById(R.id.timemess); + + View redpoint = view.findViewById(R.id.redpoint); + + RelativeLayout delete2 = (RelativeLayout) view.findViewById(R.id.delete2); + + delete2.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View c) { + GizMessage gizMessage = mymessageList.get(arg0); + + String id = gizMessage.getId(); + myid = id; + myposition = arg0; + GizDeviceSharing.markMessageStatus(token, gizMessage.getId(), GizMessageStatus.GizMessageDeleted); + progressDialog.show(); + } + }); + + GizMessage gizMessage = mymessageList.get(arg0); + + mess.setText(gizMessage.getContent()); + + timemess.setText(DateUtil.utc2Local(gizMessage.getUpdatedAt())); + + int ordinal = gizMessage.getStatus().ordinal(); + + if (ordinal == 0) { + redpoint.setVisibility(View.VISIBLE); + } else { + redpoint.setVisibility(View.GONE); + } + + return view; + } + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + break; + + } + + return super.onOptionsItemSelected(item); + } + + @Override + protected void onResume() { + super.onResume(); + //GizDeviceSharing.queryMessageList + + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didMarkMessageStatus(GizWifiErrorCode result, String messageID) { + super.didMarkMessageStatus(result, messageID); + + if (result.ordinal() == 0 && myid.equals(messageID)) { + + if (mymessageList.size() > myposition && myposition != -1) { + + GizDeviceSharing.queryMessageList(token, GizMessageType.GizMessageSharing); + } + } else { + + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.cancel(); + } + } + } + + @Override + public void didQueryMessageList(GizWifiErrorCode result, List messageList) { + super.didQueryMessageList(result, messageList); + + if (messageList != null) { + Collections.sort(messageList, new Comparator() { + + @Override + public int compare(GizMessage arg0, GizMessage arg1) { + + String updatedAt = DateUtil.utc2Local(arg0.getUpdatedAt()); + String updatedAt2 = DateUtil.utc2Local(arg1.getUpdatedAt()); + + int diff = (int) DateUtil.getDiff(updatedAt2, updatedAt); + + return diff; + } + + }); + } + + if (progressDialog.isShowing()) { + progressDialog.cancel(); + } + mymessageList = messageList; + if (mymessageList.size() != 0) { + tvNoMessage.setVisibility(View.GONE); + } + myadapter.notifyDataSetChanged(); + } + + }); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/gosZxingDeviceSharingActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/gosZxingDeviceSharingActivity.java new file mode 100644 index 0000000..497019d --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/gosZxingDeviceSharingActivity.java @@ -0,0 +1,235 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.utils.DateUtil; + +public class gosZxingDeviceSharingActivity extends GosBaseActivity { + + private String code; + private int time = 15; + private String[] split2s; + private String tip; + private TextView tiptext; + private String token; + private Button yes; + private Button no; + private TextView zxingtext; + private String whoshared; + private String[] splits; + private String userName; + private String productName; + private String deviceAlias; + private String expiredAt; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.gos_devicesharing_zxing_activity); + setToolBar(true, R.string.QR_code); + initData(); + initView(); + } + + private void initView() { + + zxingtext = (TextView) findViewById(R.id.zxingtext); + + yes = (Button) findViewById(R.id.yes); + + no = (Button) findViewById(R.id.no); + + whoshared = getResources().getString(R.string.whoshared); + + splits = whoshared.split("xxx"); + // [, 向你共享, ,你接受并绑定设备吗?] + whoshared = userName + splits[1] + productName + splits[splits.length - 1]; + zxingtext.setText(whoshared); + + String timeByFormat = DateUtil.getCurTimeByFormat("yyyy-MM-dd HH:mm:ss"); + expiredAt = DateUtil.utc2Local(expiredAt); + long diff = DateUtil.getDiff(expiredAt, timeByFormat); + if (diff >= 0) { + double c = diff / 60.0; + time = (int) Math.ceil(c); + } else { + tiptext.setText(getResources().getString(R.string.requestoutoftime)); + yes.setClickable(false); + yes.setTextColor(getResources().getColor(R.color.gray)); + return; + } + tiptext = (TextView) findViewById(R.id.tiptext); + tip = getResources().getString(R.string.tipthings); + split2s = tip.split("xx"); + + tip = split2s[0] + time + split2s[1]; + + tiptext.setText(tip); + + hand.sendEmptyMessageDelayed(1, diff % 60 * 1000); + + yes.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + GizDeviceSharing.acceptDeviceSharingByQRCode(spf.getString("Token", ""), code); + } + }); + + no.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + finish(); + } + }); + } + + private void initData() { + + Intent intent = getIntent(); + code = intent.getStringExtra("code"); + userName = intent.getStringExtra("userName"); + productName = intent.getStringExtra("productName"); + deviceAlias = intent.getStringExtra("deviceAlias"); + expiredAt = intent.getStringExtra("expiredAt"); + + token = spf.getString("Token", ""); + + } + + @Override + protected void onResume() { + super.onResume(); + + if (time > 0) { + tip = split2s[0] + time + split2s[1]; + + tiptext.setText(tip); + } else { + tiptext.setText(getResources().getString(R.string.requestoutoftime)); + yes.setClickable(false); + yes.setTextColor(getResources().getColor(R.color.gray)); + } + + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didAcceptDeviceSharing(GizWifiErrorCode result, int sharingID) { + super.didAcceptDeviceSharing(result, sharingID); + if (result.ordinal() == 0) { + finish(); + } else { + Toast.makeText(gosZxingDeviceSharingActivity.this, toastError(result), 1).show(); + finish(); + } + } + + @Override + public void didAcceptDeviceSharingByQRCode(GizWifiErrorCode result) { + super.didAcceptDeviceSharingByQRCode(result); + if (result.ordinal() == 0) { + Toast.makeText(gosZxingDeviceSharingActivity.this, "success", 1).show(); + + finish(); + } else { + Toast.makeText(gosZxingDeviceSharingActivity.this, toastError(result), 1).show(); + + finish(); + } + } + + @Override + public void didCheckDeviceSharingInfoByQRCode(GizWifiErrorCode result, String userName, String productName, + String deviceAlias, String expiredAt) { + super.didCheckDeviceSharingInfoByQRCode(result, userName, productName, deviceAlias, expiredAt); + + int errorcode = result.ordinal(); + + if (8041 <= errorcode && errorcode <= 8050 || errorcode == 8308) { + tiptext.setVisibility(View.GONE); + yes.setClickable(false); + no.setClickable(false); + yes.setTextColor(getResources().getColor(R.color.gray)); + no.setTextColor(getResources().getColor(R.color.gray)); + zxingtext.setText(getResources().getString(R.string.sorry)); + } else if (errorcode != 0) { + tiptext.setVisibility(View.GONE); + yes.setClickable(false); + no.setClickable(false); + yes.setTextColor(getResources().getColor(R.color.gray)); + no.setTextColor(getResources().getColor(R.color.gray)); + zxingtext.setText(getResources().getString(R.string.verysorry)); + } else { + tiptext.setVisibility(View.VISIBLE); + yes.setClickable(true); + no.setClickable(true); + yes.setTextColor(getResources().getColor(R.color.text_color)); + no.setTextColor(getResources().getColor(R.color.text_color)); + + whoshared = userName + splits[1] + productName + splits[splits.length - 1]; + zxingtext.setText(whoshared); + + String timeByFormat = DateUtil.getCurTimeByFormat("yyyy-MM-dd HH:mm:ss"); + expiredAt = DateUtil.utc2Local(expiredAt); + long diff = DateUtil.getDiff(expiredAt, timeByFormat); + + if (diff >= 0) { + time = (int) Math.ceil(diff / 60); + } else { + + } + Toast.makeText(gosZxingDeviceSharingActivity.this, diff % 60 + "", 1).show(); + + } + } + }); + + } + + + Handler hand = new Handler() { + public void handleMessage(android.os.Message msg) { + + time = time - 1; + + if (time > 0) { + tip = split2s[0] + time + split2s[1]; + + tiptext.setText(tip); + hand.sendEmptyMessageDelayed(1, 60000); + } else { + tiptext.setText(getResources().getString(R.string.requestoutoftime)); + yes.setClickable(false); + yes.setTextColor(getResources().getColor(R.color.gray)); + } + + } + + ; + }; + + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + this.finish(); + break; + } + return super.onOptionsItemSelected(item); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/twoSharedActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/twoSharedActivity.java new file mode 100644 index 0000000..8494466 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/twoSharedActivity.java @@ -0,0 +1,175 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Intent; +import android.graphics.Bitmap; +import android.os.Bundle; +import android.os.Handler; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingWay; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.R; + +import java.util.Timer; +import java.util.TimerTask; + +public class twoSharedActivity extends GosBaseActivity { + + private String productname; + private String did; + private ImageView myimage; + private TextView timeout; + private TextView bottomtext; + private int time = 15; + + @Override + protected void onCreate(Bundle savedInstanceState) { + + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_gos_two_shared); + + setToolBar(true, R.string.scan_code_sharing); + + initData(); + initView(); + } + + private void initView() { + TextView usersharedtext = (TextView) findViewById(R.id.usersharedtext); + + myimage = (ImageView) findViewById(R.id.myimageview); + + timeout = (TextView) findViewById(R.id.timeout); + + timeout2 = splits[0] + time + splits[1]; + + timeout.setText(timeout2); + + bottomtext = (TextView) findViewById(R.id.bottomtext); + + usersharedtext.setText(getResources().getString(R.string.shared) + " " + productname + + getResources().getString(R.string.friends)); + } + + private void initData() { + + Intent tent = getIntent(); + productname = tent.getStringExtra("productname"); + did = tent.getStringExtra("did"); + + timeout2 = getResources().getString(R.string.zxingtimeout); + splits = timeout2.split("15"); + GizDeviceSharing.sharingDevice(spf.getString("Token", ""), did, GizDeviceSharingWay.GizDeviceSharingByQRCode, + null, null); + + } + + private void startTimer() { + timer = new Timer(); + timer.schedule(new TimerTask() { + + @Override + public void run() { + + time = time - 1; + hand.sendEmptyMessage(1); + } + }, 60000, 60000); + } + + @Override + protected void onResume() { + super.onResume(); + if (time > 0) { + timeout2 = splits[0] + time + splits[1]; + + timeout.setText(timeout2); + } else { + timeout.setText(getResources().getString(R.string.twofailed)); + } + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didSharingDevice(GizWifiErrorCode result, String deviceID, int sharingID, + Bitmap QRCodeImage) { + super.didSharingDevice(result, deviceID, sharingID, QRCodeImage); + + if (QRCodeImage != null) { + myimage.setImageBitmap(QRCodeImage); + bottomtext.setVisibility(View.VISIBLE); + + // hand.sendEmptyMessageDelayed(1, 60000); + startTimer(); + } else { + int errorcode = result.ordinal(); + + if (8041 <= errorcode && errorcode <= 8050 || errorcode == 8308) { + + timeout.setText(getResources().getString(R.string.twosharedtimeout)); + bottomtext.setVisibility(View.GONE); + + } else { + timeout.setText(getResources().getString(R.string.sharedfailed)); + bottomtext.setVisibility(View.GONE); + } + } + + } + }); + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + + finish(); + break; + + } + return super.onOptionsItemSelected(item); + } + + Handler hand = new Handler() { + public void handleMessage(android.os.Message msg) { + + // time = time - 1; + + if (time > 0) { + timeout2 = splits[0] + time + splits[1]; + + timeout.setText(timeout2); + // hand.sendEmptyMessageDelayed(1, 60000); + } else { + timeout.setText(getResources().getString(R.string.twofailed)); + } + + }; + }; + + @Override + protected void onDestroy() { + // TODO Auto-generated method stub + super.onDestroy(); + + time = 15; + + hand.removeMessages(1); + if (timer != null) { + timer.cancel(); + } + + } + + private String timeout2; + private String[] splits; + private Timer timer; +} diff --git a/src/main/java/com/gizwits/opensource/appkit/sharingdevice/userSharedActivity.java b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/userSharedActivity.java new file mode 100644 index 0000000..0323389 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/sharingdevice/userSharedActivity.java @@ -0,0 +1,145 @@ +package com.gizwits.opensource.appkit.sharingdevice; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.gizwifisdk.api.GizDeviceSharing; +import com.gizwits.gizwifisdk.enumration.GizDeviceSharingWay; +import com.gizwits.gizwifisdk.enumration.GizUserAccountType; +import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; +import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.CommonModule.TipsDialog; +import com.gizwits.opensource.appkit.R; + +public class userSharedActivity extends GosBaseActivity { + + private String productname; + private EditText username; + private int chooseitem = 0; + private String did; + + @Override + protected void onCreate(Bundle savedInstanceState) { + // TODO Auto-generated method stub + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_gos_user_shared); + + setToolBar(true, R.string.account_shared); + + initData(); + initView(); + } + + private void initView() { + TextView usersharedtext = (TextView) findViewById(R.id.usersharedtext); + Button button = (Button) findViewById(R.id.button); + button.setBackgroundDrawable(GosDeploy.appConfig_BackgroundColor()); + button.setTextColor(GosDeploy.appConfig_Contrast()); + + username = (EditText) findViewById(R.id.username); + usersharedtext.setText( + getResources().getString(R.string.shared) + productname + getResources().getString(R.string.friends)); + } + + private void initData() { + + Intent tent = getIntent(); + productname = tent.getStringExtra("productname"); + did = tent.getStringExtra("did"); + } + + public void usershared(View v) { + + final String usernametext = username.getText().toString(); + if (TextUtils.isEmpty(usernametext)) { + + // Toast.makeText(this, + // getResources().getString(R.string.toast_name_empet), 0).show(); + + TipsDialog dia = new TipsDialog(this, getResources().getString(R.string.toast_name_empet)); + dia.show(); + return; + } + + SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE); + String token = spf.getString("Token", ""); + if (usernametext.length() < 32) { + if (usernametext.matches("[0-9]+")) { + GizDeviceSharing.sharingDevice(token, did, GizDeviceSharingWay.GizDeviceSharingByNormal, usernametext, + GizUserAccountType.GizUserPhone); + return; + } + + } + if (usernametext.contains("@")) { + GizDeviceSharing.sharingDevice(token, did, GizDeviceSharingWay.GizDeviceSharingByNormal, usernametext, + GizUserAccountType.GizUserEmail); + return; + } + if (usernametext.length() == 32) { + if (usernametext.matches("[a-zA-Z0-9]+")) { + GizDeviceSharing.sharingDevice(token, did, GizDeviceSharingWay.GizDeviceSharingByNormal, usernametext, + GizUserAccountType.GizUserOther); + return; + } + + } + Toast.makeText(this, getString(R.string.account_incorrect), Toast.LENGTH_LONG).show(); + + + } + + @Override + protected void onResume() { + super.onResume(); + + GizDeviceSharing.setListener(new GizDeviceSharingListener() { + + @Override + public void didSharingDevice(GizWifiErrorCode result, String deviceID, int sharingID, + Bitmap QRCodeImage) { + super.didSharingDevice(result, deviceID, sharingID, QRCodeImage); + + if (result.ordinal() == 0) { + Toast.makeText(userSharedActivity.this, getResources().getString(R.string.alawyssend), 1).show(); + finish(); + } else if (result == GizWifiErrorCode.GIZ_OPENAPI_GUEST_ALREADY_BOUND) { + Toast.makeText(userSharedActivity.this, getResources().getString(R.string.account_shared2), toastTime).show(); + } else if (result == GizWifiErrorCode.GIZ_OPENAPI_NOT_FOUND_GUEST) { + Toast.makeText(userSharedActivity.this, getResources().getString(R.string.user_not_exist), toastTime).show(); + } else if (result == GizWifiErrorCode.GIZ_OPENAPI_CANNOT_SHARE_TO_SELF) { + Toast.makeText(userSharedActivity.this, getResources().getString(R.string.not_shared_self), toastTime).show(); + } else { + Toast.makeText(userSharedActivity.this, getResources().getString(R.string.send_failed1), 2).show(); + } + + } + + }); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + + finish(); + break; + + } + return super.onOptionsItemSelected(item); + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/utils/.DS_Store new file mode 100644 index 0000000..69a3990 Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/utils/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/AssetsUtils.java b/src/main/java/com/gizwits/opensource/appkit/utils/AssetsUtils.java new file mode 100644 index 0000000..62bcabe --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/AssetsUtils.java @@ -0,0 +1,111 @@ +package com.gizwits.opensource.appkit.utils; + +import android.content.Context; +import android.util.DisplayMetrics; +import android.view.WindowManager; + +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Locale; + +public class AssetsUtils { + + public static void assetsDataToSD(String fileOutPutName, + String fileInPutName, Context context) throws IOException { + InputStream myInput; + File file = new File(fileOutPutName); + if (!file.exists()) { + file.createNewFile(); + }else { + return; + } + OutputStream myOutput = new FileOutputStream(fileOutPutName); + myInput = context.getAssets().open(fileInPutName); + byte[] buffer = new byte[1024]; + int length = myInput.read(buffer); + while (length > 0) { + myOutput.write(buffer, 0, length); + length = myInput.read(buffer); + } + + myOutput.flush(); + myInput.close(); + myOutput.close(); + } + + + + public static void saveFile(String str) { + String filePath = null; + + + filePath = GosDeploy.fileOutName; + try { + if(filePath!=null){ + File file = new File(filePath); + if (!file.exists()) { + File dir = new File(file.getParent()); + dir.mkdirs(); + file.createNewFile(); + } + FileOutputStream outStream = new FileOutputStream(file); + outStream.write(str.getBytes()); + outStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } +} + /** + * 将dip或dp值转换为px值,保证尺寸大小不变 + * + * @param dipValue + * @param scale + * (DisplayMetrics类中属性density) + * @return + */ + public static int diptopx(Context context, float dipValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (dipValue * scale + 0.5f); + } + + + /** + * 将sp值转换为px值,保证文字大小不变 + * + * @param spValue + * @param fontScale + * (DisplayMetrics类中属性scaledDensity) + * @return + */ + public static int sptopx(Context context, float spValue) { + final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; + return (int) (spValue * fontScale + 0.5f); + } + + public static boolean isZh(Context context) { + Locale locale = context.getResources().getConfiguration().locale; + String language = locale.getLanguage(); + if (language.endsWith("zh")) + return true; + else + return false; + } + + public static int getScreenWidth(Context context) + { + WindowManager wm = (WindowManager) context + .getSystemService(Context.WINDOW_SERVICE ); + DisplayMetrics outMetrics = new DisplayMetrics(); + wm.getDefaultDisplay().getMetrics( outMetrics); + return outMetrics .widthPixels ; + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/DateUtil.java b/src/main/java/com/gizwits/opensource/appkit/utils/DateUtil.java new file mode 100644 index 0000000..a347d0e --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/DateUtil.java @@ -0,0 +1,1331 @@ +package com.gizwits.opensource.appkit.utils; + +import android.annotation.SuppressLint; + +import java.io.Serializable; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +/** + * 日期操作工具类,主要实现了日期的常用操作。 + *

+ * 在工具类中经常使用到工具类的格式化描述,这个主要是一个日期的操作类,所以日志格式主要使用 SimpleDateFormat的定义格式. + *

+ * 格式的意义如下: 日期和时间模式
+ * 日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 'A' 到 'Z' 和 'a' 到 'z' + * 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''" + * 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。 + *

+ * 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留):
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
字母日期或时间元素表示示例 + *
GEra标志符TextAD + *
yYear1996;96 + *
M年中的月份MonthJuly;Jul;07 + *
w年中的周数Number27 + *
W月份中的周数Number2 + *
D年中的天数Number189 + *
d月份中的天数Number10 + *
F月份中的星期Number2 + *
E星期中的天数TextTuesday;Tue + *
aAm/pm标记TextPM + *
H一天中的小时数(0-23)Number0 + *
k一天中的小时数(1-24)Number24 + *
Kam/pm中的小时数(0-11)Number0 + *
ham/pm中的小时数(1-12)Number12 + *
m小时中的分钟数Number30 + *
s分钟中的秒数Number55 + *
S毫秒数Number978 + *
z时区GeneraltimezonePacificStandardTime;PST;GMT-08:00 + *
Z时区RFC822timezone-0800 + *
+ * + * 模式字母通常是重复的,其数量确定其精确表示: + * + */ +public final class DateUtil implements Serializable { + /** + * + */ + private static final long serialVersionUID = -3098985139095632110L; + + private DateUtil() { + } + + /** + * 格式化日期显示格式yyyy-MM-dd + * + * @param sdate + * 原始日期格式 + * @return yyyy-MM-dd格式化后的日期显示 + */ + public static String dateFormat(String sdate) { + return dateFormat(sdate, "yyyy-MM-dd"); + } + + /** + * 格式化日期显示格式 + * + * @param sdate + * 原始日期格式 + * @param format + * 格式化后日期格式 + * @return 格式化后的日期显示 + */ + public static String dateFormat(String sdate, String format) { + SimpleDateFormat formatter = new SimpleDateFormat(format); + java.sql.Date date = java.sql.Date.valueOf(sdate); + String dateString = formatter.format(date); + + return dateString; + } + + /** + * 求两个日期相差天数 + * + * @param sd + * 起始日期,格式yyyy-MM-dd + * @param ed + * 终止日期,格式yyyy-MM-dd + * @return 两个日期相差天数 + */ + public static long getIntervalDays(String sd, String ed) { + return ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date.valueOf(sd)).getTime()) / (3600 * 24 * 1000); + } + + /** + * 起始年月yyyy-MM与终止月yyyy-MM之间跨度的月数 + * + * @return int + */ + public static int getInterval(String beginMonth, String endMonth) { + int intBeginYear = Integer.parseInt(beginMonth.substring(0, 4)); + int intBeginMonth = Integer.parseInt(beginMonth.substring(beginMonth.indexOf("-") + 1)); + int intEndYear = Integer.parseInt(endMonth.substring(0, 4)); + int intEndMonth = Integer.parseInt(endMonth.substring(endMonth.indexOf("-") + 1)); + + return ((intEndYear - intBeginYear) * 12) + (intEndMonth - intBeginMonth) + 1; + } + + public static Date getDate(String sDate, String dateFormat) { + SimpleDateFormat fmt = new SimpleDateFormat(dateFormat); + ParsePosition pos = new ParsePosition(0); + + return fmt.parse(sDate, pos); + } + + /** + * 取得当前日期的年份,以yyyy格式返回. + * + * @return 当年 yyyy + */ + public static String getCurrentYear() { + return getFormatCurrentTime("yyyy"); + } + + /** + * 自动返回上一年。例如当前年份是2007年,那么就自动返回2006 + * + * @return 返回结果的格式为 yyyy + */ + public static String getBeforeYear() { + String currentYear = getFormatCurrentTime("yyyy"); + int beforeYear = Integer.parseInt(currentYear) - 1; + return "" + beforeYear; + } + + /** + * 取得当前日期的月份,以MM格式返回. + * + * @return 当前月份 MM + */ + public static String getCurrentMonth() { + return getFormatCurrentTime("MM"); + } + + /** + * 取得当前日期的天数,以格式"dd"返回. + * + * @return 当前月中的某天dd + */ + public static String getCurrentDay() { + return getFormatCurrentTime("dd"); + } + + /** + * 返回当前时间字符串。 + *

+ * 格式:yyyy-MM-dd + * + * @return String 指定格式的日期字符串. + */ + public static String getCurrentDate() { + return getFormatDateTime(new Date(), "yyyy-MM-dd"); + } + + /** + * 返回给定时间字符串。 + *

+ * 格式:yyyy-MM-dd + * + * @param date + * 日期 + * @return String 指定格式的日期字符串. + */ + public static String getFormatDate(Date date) { + return getFormatDateTime(date, "yyyy-MM-dd"); + } + + /** + * 根据制定的格式,返回日期字符串。例如2007-05-05 + * + * @param format + * "yyyy-MM-dd" 或者 "yyyy/MM/dd" + * @return 指定格式的日期字符串。 + */ + public static String getFormatDate(String format) { + return getFormatDateTime(new Date(), format); + } + + /** + * 返回当前时间字符串。 + *

+ * 格式:yyyy-MM-dd HH:mm:ss + * + * @return String 指定格式的日期字符串. + */ + public static String getCurrentTime() { + return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 返回给定时间字符串。 + *

+ * 格式:yyyy-MM-dd HH:mm:ss + * + * @param date + * 日期 + * @return String 指定格式的日期字符串. + */ + public static String getFormatTime(Date date) { + return getFormatDateTime(date, "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 根据给定的格式,返回时间字符串。 + *

+ * 格式参照类描绘中说明. + * + * @param format + * 日期格式字符串 + * @return String 指定格式的日期字符串. + */ + public static String getFormatCurrentTime(String format) { + return getFormatDateTime(new Date(), format); + } + + /** + * 根据给定的格式与时间(Date类型的),返回时间字符串
+ * + * @param date + * 指定的日期 + * @param format + * 日期格式字符串 + * @return String 指定格式的日期字符串. + */ + public static String getFormatDateTime(Date date, String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(date); + } + + /** + * 取得指定年月日的日期对象. + * + * @param year + * 年 + * @param month + * 月注意是从1到12 + * @param day + * 日 + * @return 一个java.util.Date()类型的对象 + */ + public static Date getDateObj(int year, int month, int day) { + Calendar c = new GregorianCalendar(); + c.set(year, month - 1, day); + return c.getTime(); + } + + /** + * 取得指定分隔符分割的年月日的日期对象. + * + * @param args + * 格式为"yyyy-MM-dd" + * @param split + * 时间格式的间隔符,例如“-”,“/” + * @return 一个java.util.Date()类型的对象 + */ + public static Date getDateObj(String args, String split) { + String[] temp = args.split(split); + int year = new Integer(temp[0]).intValue(); + int month = new Integer(temp[1]).intValue(); + int day = new Integer(temp[2]).intValue(); + return getDateObj(year, month, day); + } + + /** + * 取得给定字符串描述的日期对象,描述模式采用pattern指定的格式. + * + * @param dateStr + * 日期描述 + * @param pattern + * 日期模式 + * @return 给定字符串描述的日期对象。 + */ + public static Date getDateFromString(String dateStr, String pattern) { + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + Date resDate = null; + try { + resDate = sdf.parse(dateStr); + } catch (Exception e) { + e.printStackTrace(); + } + return resDate; + } + + /** + * 取得当前Date对象. + * + * @return Date 当前Date对象. + */ + public static Date getDateObj() { + Calendar c = new GregorianCalendar(); + return c.getTime(); + } + + /** + * + * @return 当前月份有多少天; + */ + public static int getDaysOfCurMonth() { + int curyear = new Integer(getCurrentYear()).intValue(); // 当前年份 + int curMonth = new Integer(getCurrentMonth()).intValue();// 当前月份 + int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + // 判断闰年的情况 ,2月份有29天; + if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) { + mArray[1] = 29; + } + return mArray[curMonth - 1]; + // 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界; + // 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界; + } + + /** + * 根据指定的年月 返回指定月份(yyyy-MM)有多少天。 + * + * @param time + * yyyy-MM + * @return 天数,指定月份的天数。 + */ + public static int getDaysOfCurMonth(final String time) { + String[] timeArray = time.split("-"); + int curyear = new Integer(timeArray[0]).intValue(); // 当前年份 + int curMonth = new Integer(timeArray[1]).intValue();// 当前月份 + int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + // 判断闰年的情况 ,2月份有29天; + if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) { + mArray[1] = 29; + } + if (curMonth == 12) { + return mArray[0]; + } + return mArray[curMonth - 1]; + // 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界; + // 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界; + } + + /** + * 返回指定为年度为year月度为month的月份内,第weekOfMonth个星期的第dayOfWeek天。
+ * 00 00 00 01 02 03 04
+ * 05 06 07 08 09 10 11
+ * 12 13 14 15 16 17 18
+ * 19 20 21 22 23 24 25
+ * 26 27 28 29 30 31
+ * 2006年的第一个周的1到7天为:05 06 07 01 02 03 04
+ * 2006年的第二个周的1到7天为:12 13 14 08 09 10 11
+ * 2006年的第三个周的1到7天为:19 20 21 15 16 17 18
+ * 2006年的第四个周的1到7天为:26 27 28 22 23 24 25
+ * 2006年的第五个周的1到7天为:02 03 04 29 30 31 01 。本月没有就自动转到下个月了。 + * + * @param year + * 形式为yyyy
+ * @param month + * 形式为MM,参数值在[1-12]。
+ * @param weekOfMonth + * 在[1-6],因为一个月最多有6个周。
+ * @param dayOfWeek + * 数字在1到7之间,包括1和7。1表示星期天,7表示星期六
+ * -6为星期日-1为星期五,0为星期六
+ * @return int + */ + public static int getDayofWeekInMonth(String year, String month, String weekOfMonth, String dayOfWeek) { + Calendar cal = new GregorianCalendar(); + // 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。 + int y = new Integer(year).intValue(); + int m = new Integer(month).intValue(); + cal.clear();// 不保留以前的设置 + cal.set(y, m - 1, 1);// 将日期设置为本月的第一天。 + cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, new Integer(weekOfMonth).intValue()); + cal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue()); + // System.out.print(cal.get(Calendar.MONTH)+" "); + // System.out.print("当"+cal.get(Calendar.WEEK_OF_MONTH)+"\t"); + // WEEK_OF_MONTH表示当天在本月的第几个周。不管1号是星期几,都表示在本月的第一个周 + return cal.get(Calendar.DAY_OF_MONTH); + } + + /** + * 根据指定的年月日小时分秒,返回一个java.Util.Date对象。 + * + * @param year + * 年 + * @param month + * 月 0-11 + * @param date + * 日 + * @param hourOfDay + * 小时 0-23 + * @param minute + * 分 0-59 + * @param second + * 秒 0-59 + * @return 一个Date对象。 + */ + public static Date getDate(int year, int month, int date, int hourOfDay, int minute, int second) { + Calendar cal = new GregorianCalendar(); + cal.set(year, month, date, hourOfDay, minute, second); + return cal.getTime(); + } + + /** + * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。 + * + * @param year + * @param month + * month是从1开始的12结束 + * @param day + * @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。 + */ + public static int getDayOfWeek(String year, String month, String day) { + Calendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1, + new Integer(day).intValue()); + return cal.get(Calendar.DAY_OF_WEEK); + } + + /** + * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。 + * + * @param date + * "yyyy/MM/dd",或者"yyyy-MM-dd" + * @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。 + */ + public static int getDayOfWeek(String date) { + String[] temp = null; + if (date.indexOf("/") > 0) { + temp = date.split("/"); + } + if (date.indexOf("-") > 0) { + temp = date.split("-"); + } + return getDayOfWeek(temp[0], temp[1], temp[2]); + } + + /** + * 返回当前日期是星期几。例如:星期日、星期一、星期六等等。 + * + * @param date + * 格式为 yyyy/MM/dd 或者 yyyy-MM-dd + * @return 返回当前日期是星期几 + */ + public static String getChinaDayOfWeek(String date) { + String[] weeks = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; + int week = getDayOfWeek(date); + return weeks[week - 1]; + } + + /** + * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。 + * + * @param date + * + * @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。 + */ + public static int getDayOfWeek(Date date) { + Calendar cal = new GregorianCalendar(); + cal.setTime(date); + return cal.get(Calendar.DAY_OF_WEEK); + } + + /** + * 返回制定日期所在的周是一年中的第几个周。
+ * created by wangmj at 20060324.
+ * + * @param year + * @param month + * 范围1-12
+ * @param day + * @return int + */ + public static int getWeekOfYear(String year, String month, String day) { + Calendar cal = new GregorianCalendar(); + cal.clear(); + cal.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue()); + return cal.get(Calendar.WEEK_OF_YEAR); + } + + /** + * 取得给定日期加上一定天数后的日期对象. + * + * @param date + * 给定的日期对象 + * @param amount + * 需要添加的天数,如果是向前的天数,使用负数就可以. + * @return Date 加上一定天数以后的Date对象. + */ + public static Date getDateAdd(Date date, int amount) { + Calendar cal = new GregorianCalendar(); + cal.setTime(date); + cal.add(GregorianCalendar.DATE, amount); + return cal.getTime(); + } + + /** + * 取得给定日期加上一定天数后的日期对象. + * + * @param date + * 给定的日期对象 + * @param amount + * 需要添加的天数,如果是向前的天数,使用负数就可以. + * @param format + * 输出格式. + * @return Date 加上一定天数以后的Date对象. + */ + public static String getFormatDateAdd(Date date, int amount, String format) { + Calendar cal = new GregorianCalendar(); + cal.setTime(date); + cal.add(GregorianCalendar.DATE, amount); + return getFormatDateTime(cal.getTime(), format); + } + + /** + * 获得当前日期固定间隔天数的日期,如前60天dateAdd(-60) + * + * @param amount + * 距今天的间隔日期长度,向前为负,向后为正 + * @param format + * 输出日期的格式. + * @return java.lang.String 按照格式输出的间隔的日期字符串. + */ + public static String getFormatCurrentAdd(int amount, String format) { + + Date d = getDateAdd(new Date(), amount); + + return getFormatDateTime(d, format); + } + + /** + * 取得给定格式的昨天的日期输出 + * + * @param format + * 日期输出的格式 + * @return String 给定格式的日期字符串. + */ + public static String getFormatYestoday(String format) { + return getFormatCurrentAdd(-1, format); + } + + /** + * 返回指定日期的前一天。
+ * + * @param sourceDate + * @param format + * yyyy MM dd hh mm ss + * @return 返回日期字符串,形式和formcat一致。 + */ + public static String getYestoday(String sourceDate, String format) { + return getFormatDateAdd(getDateFromString(sourceDate, format), -1, format); + } + + /** + * 返回明天的日期,
+ * + * @param format + * @return 返回日期字符串,形式和formcat一致。 + */ + public static String getFormatTomorrow(String format) { + return getFormatCurrentAdd(1, format); + } + + /** + * 返回指定日期的后一天。
+ * + * @param sourceDate + * @param format + * @return 返回日期字符串,形式和formcat一致。 + */ + public static String getFormatDateTommorrow(String sourceDate, String format) { + return getFormatDateAdd(getDateFromString(sourceDate, format), 1, format); + } + + /** + * 根据主机的默认 TimeZone,来获得指定形式的时间字符串。 + * + * @param dateFormat + * @return 返回日期字符串,形式和formcat一致。 + */ + public static String getCurrentDateString(String dateFormat) { + Calendar cal = Calendar.getInstance(TimeZone.getDefault()); + SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); + sdf.setTimeZone(TimeZone.getDefault()); + + return sdf.format(cal.getTime()); + } + + /** + * @deprecated 不鼓励使用。 返回当前时间串 格式:yyMMddhhmmss,在上传附件时使用 + * + * @return String + */ + public static String getCurDate() { + GregorianCalendar gcDate = new GregorianCalendar(); + int year = gcDate.get(GregorianCalendar.YEAR); + int month = gcDate.get(GregorianCalendar.MONTH) + 1; + int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH); + int hour = gcDate.get(GregorianCalendar.HOUR_OF_DAY); + int minute = gcDate.get(GregorianCalendar.MINUTE); + int sen = gcDate.get(GregorianCalendar.SECOND); + String y; + String m; + String d; + String h; + String n; + String s; + y = new Integer(year).toString(); + + if (month < 10) { + m = "0" + new Integer(month).toString(); + } else { + m = new Integer(month).toString(); + } + + if (day < 10) { + d = "0" + new Integer(day).toString(); + } else { + d = new Integer(day).toString(); + } + + if (hour < 10) { + h = "0" + new Integer(hour).toString(); + } else { + h = new Integer(hour).toString(); + } + + if (minute < 10) { + n = "0" + new Integer(minute).toString(); + } else { + n = new Integer(minute).toString(); + } + + if (sen < 10) { + s = "0" + new Integer(sen).toString(); + } else { + s = new Integer(sen).toString(); + } + + return "" + y + m + d + h + n + s; + } + + /** + * 根据给定的格式,返回时间字符串。 和getFormatDate(String format)相似。 + * + * @param format + * yyyy MM dd hh mm ss + * @return 返回一个时间字符串 + */ + public static String getCurTimeByFormat(String format) { + Date newdate = new Date(System.currentTimeMillis()); + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(newdate); + } + + /** + * 获取两个时间串时间的差值,单位为秒 + * + * @param startTime + * 开始时间 yyyy-MM-dd HH:mm:ss + * @param endTime + * 结束时间 yyyy-MM-dd HH:mm:ss + * @return 两个时间的差值(秒) + */ + public static long getDiff(String startTime, String endTime) { + long diff = 0; + SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + Date startDate = ft.parse(startTime); + Date endDate = ft.parse(endTime); + diff = startDate.getTime() - endDate.getTime(); + diff = diff / 1000; + } catch (ParseException e) { + e.printStackTrace(); + } + return diff; + } + + /** + * 获取小时/分钟/秒 + * + * @param second + * 秒 + * @return 包含小时、分钟、秒的时间字符串,例如3小时23分钟13秒。 + */ + public static String getHour(long second) { + long hour = second / 60 / 60; + long minute = (second - hour * 60 * 60) / 60; + long sec = (second - hour * 60 * 60) - minute * 60; + + return hour + "小时" + minute + "分钟" + sec + "秒"; + + } + + /** + * 返回指定时间字符串。 + *

+ * 格式:yyyy-MM-dd HH:mm:ss + * + * @return String 指定格式的日期字符串. + */ + public static String getDateTime(long microsecond) { + return getFormatDateTime(new Date(microsecond), "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 返回当前时间加实数小时后的日期时间。 + *

+ * 格式:yyyy-MM-dd HH:mm:ss + * + * @return Float 加几实数小时. + */ + public static String getDateByAddFltHour(float flt) { + int addMinute = (int) (flt * 60); + Calendar cal = new GregorianCalendar(); + cal.setTime(new Date()); + cal.add(GregorianCalendar.MINUTE, addMinute); + return getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss"); + } + + /** + * 返回指定时间加指定小时数后的日期时间。 + *

+ * 格式:yyyy-MM-dd HH:mm:ss + * + * @return 时间. + */ + public static String getDateByAddHour(String datetime, int minute) { + String returnTime = null; + Calendar cal = new GregorianCalendar(); + SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date; + try { + date = ft.parse(datetime); + cal.setTime(date); + cal.add(GregorianCalendar.MINUTE, minute); + returnTime = getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss"); + } catch (ParseException e) { + e.printStackTrace(); + } + return returnTime; + + } + + /** + * 获取两个时间串时间的差值,单位为小时 + * + * @param startTime + * 开始时间 yyyy-MM-dd HH:mm:ss + * @param endTime + * 结束时间 yyyy-MM-dd HH:mm:ss + * @return 两个时间的差值(秒) + */ + public static int getDiffHour(String startTime, String endTime) { + long diff = 0; + SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + Date startDate = ft.parse(startTime); + Date endDate = ft.parse(endTime); + diff = startDate.getTime() - endDate.getTime(); + diff = diff / (1000 * 60 * 60); + } catch (ParseException e) { + e.printStackTrace(); + } + return new Long(diff).intValue(); + } + + /** + * 返回年份的下拉框。 + * + * @param selectName + * 下拉框名称 + * @param value + * 当前下拉框的值 + * @param startYear + * 开始年份 + * @param endYear + * 结束年份 + * @return 年份下拉框的html + */ + public static String getYearSelect(String selectName, String value, int startYear, int endYear) { + int start = startYear; + int end = endYear; + if (startYear > endYear) { + start = endYear; + end = startYear; + } + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 返回年份的下拉框。 + * + * @param selectName + * 下拉框名称 + * @param value + * 当前下拉框的值 + * @param startYear + * 开始年份 + * @param endYear + * 结束年份 + * 例如开始年份为2001结束年份为2005那么下拉框就有五个值。(2001、2002、2003、2004、2005)。 + * @return 返回年份的下拉框的html。 + */ + public static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank) { + int start = startYear; + int end = endYear; + if (startYear > endYear) { + start = endYear; + end = startYear; + } + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 返回年份的下拉框。 + * + * @param selectName + * 下拉框名称 + * @param value + * 当前下拉框的值 + * @param startYear + * 开始年份 + * @param endYear + * 结束年份 + * @param js + * 这里的js为js字符串。例如 " onchange=\"changeYear()\" " + * ,这样任何js的方法就可以在jsp页面中编写,方便引入。 + * @return 返回年份的下拉框。 + */ + public static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank, + String js) { + int start = startYear; + int end = endYear; + if (startYear > endYear) { + start = endYear; + end = startYear; + } + StringBuffer sb = new StringBuffer(""); + + sb.append(""); + return sb.toString(); + } + + /** + * 返回年份的下拉框。 + * + * @param selectName + * 下拉框名称 + * @param value + * 当前下拉框的值 + * @param startYear + * 开始年份 + * @param endYear + * 结束年份 + * @param js + * 这里的js为js字符串。例如 " onchange=\"changeYear()\" " + * ,这样任何js的方法就可以在jsp页面中编写,方便引入。 + * @return 返回年份的下拉框。 + */ + public static String getYearSelect(String selectName, String value, int startYear, int endYear, String js) { + int start = startYear; + int end = endYear; + if (startYear > endYear) { + start = endYear; + end = startYear; + } + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 获取月份的下拉框 + * + * @param selectName + * @param value + * @param hasBlank + * @return 返回月份的下拉框。 + */ + public static String getMonthSelect(String selectName, String value, boolean hasBlank) { + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 获取月份的下拉框 + * + * @param selectName + * @param value + * @param hasBlank + * @param js + * @return 返回月份的下拉框。 + */ + public static String getMonthSelect(String selectName, String value, boolean hasBlank, String js) { + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 获取天的下拉框,默认的为1-31。 注意:此方法不能够和月份下拉框进行联动。 + * + * @param selectName + * @param value + * @param hasBlank + * @return 获得天的下拉框 + */ + public static String getDaySelect(String selectName, String value, boolean hasBlank) { + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 获取天的下拉框,默认的为1-31 + * + * @param selectName + * @param value + * @param hasBlank + * @param js + * @return 获取天的下拉框 + */ + public static String getDaySelect(String selectName, String value, boolean hasBlank, String js) { + StringBuffer sb = new StringBuffer(""); + sb.append(""); + return sb.toString(); + } + + /** + * 计算两天之间有多少个周末(这个周末,指星期六和星期天,一个周末返回结果为2,两个为4,以此类推。) (此方法目前用于统计司机用车记录。) + * + * @param startDate + * 开始日期 ,格式"yyyy/MM/dd" + * @param endDate + * 结束日期 ,格式"yyyy/MM/dd" + * @return int + */ + public static int countWeekend(String startDate, String endDate) { + int result = 0; + Date sdate = null; + Date edate = null; + sdate = getDateObj(startDate, "/"); // 开始日期 + edate = getDateObj(endDate, "/");// 结束日期 + // 首先计算出都有那些日期,然后找出星期六星期天的日期 + int sumDays = Math.abs(getDiffDays(startDate, endDate)); + int dayOfWeek = 0; + for (int i = 0; i <= sumDays; i++) { + dayOfWeek = getDayOfWeek(getDateAdd(sdate, i)); // 计算每过一天的日期 + if (dayOfWeek == 1 || dayOfWeek == 7) { // 1 星期天 7星期六 + result++; + } + } + return result; + } + + /** + * 返回两个日期之间相差多少天。 + * + * @param startDate + * 格式"yyyy/MM/dd" + * @param endDate + * 格式"yyyy/MM/dd" + * @return 整数。 + */ + public static int getDiffDays(String startDate, String endDate) { + long diff = 0; + SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + try { + Date sDate = ft.parse(startDate + " 00:00:00"); + Date eDate = ft.parse(endDate + " 00:00:00"); + diff = eDate.getTime() - sDate.getTime(); + diff = diff / 86400000;// 1000*60*60*24; + } catch (ParseException e) { + e.printStackTrace(); + } + return (int) diff; + + } + + /** + * 返回两个日期之间的详细日期数组(包括开始日期和结束日期)。 例如:2007/07/01 到2007/07/03 ,那么返回数组 + * {"2007/07/01","2007/07/02","2007/07/03"} + * + * @param startDate + * 格式"yyyy/MM/dd" + * @param endDate + * 格式"yyyy/MM/dd" + * @return 返回一个字符串数组对象 + */ + public static String[] getArrayDiffDays(String startDate, String endDate) { + int LEN = 0; // 用来计算两天之间总共有多少天 + // 如果结束日期和开始日期相同 + if (startDate.equals(endDate)) { + return new String[] { startDate }; + } + Date sdate = null; + sdate = getDateObj(startDate, "/"); // 开始日期 + LEN = getDiffDays(startDate, endDate); + String[] dateResult = new String[LEN + 1]; + dateResult[0] = startDate; + for (int i = 1; i < LEN + 1; i++) { + dateResult[i] = getFormatDateTime(getDateAdd(sdate, i), "yyyy/MM/dd"); + } + + return dateResult; + } + + public static int getTimeZone() { + + TimeZone tz = TimeZone.getDefault(); + String displayName = tz.getDisplayName(); + int dstSavings = tz.getDSTSavings(); + String id = tz.getID(); + String displayName2 = tz.getDisplayName(false, TimeZone.SHORT); + + return 1; + } + + /* + * 当前时间组转换utc时间 + * + * @param time 当前时间的字符串 + * + * @param formart 需要转换的格式 + * + * @return 转换后的字符串 + */ + public static String getUtc(String time, String formart) { + // 1、获得当前所在的令时偏移量-(zoneOffset + dstOffset) + String date = null; + Calendar cal = Calendar.getInstance(); + int zoneOffset = cal.get(Calendar.ZONE_OFFSET); + int dstOffset = cal.get(Calendar.DST_OFFSET); + // 2、生成Calendar,并传入对应的时间 + // 使用GMT时区进行时间计算,防止令时切换导致的微调整 + Calendar cal1 = Calendar.getInstance(); + cal1.setTimeZone(TimeZone.getTimeZone("GMT")); + + Date stringToDate = stringToDate(time, formart); + if (stringToDate != null) { + cal1.setTime(stringToDate); + cal1.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset)); + // 3、获取对应的UTC时间 + + date = dateToString(cal1.getTime(), formart); + } + + return date; + + } + + @SuppressLint("SimpleDateFormat") + public static Date stringToDate(String str, String formart) { + DateFormat format = new SimpleDateFormat(formart); + Date date = null; + try { + // Fri Feb 24 00:00:00 CST 2012 + date = format.parse(str); + } catch (ParseException e) { + e.printStackTrace(); + } + // 2012-02-24 + // date = java.sql.Date.valueOf(str); + + return date; + } + + @SuppressLint("SimpleDateFormat") + public static String dateToString(Date date, String type) { + String str = null; + SimpleDateFormat format = new SimpleDateFormat(type); + + str = format.format(date); + + return str; + } + + // utc时间转换当地时间 + public static String utc2Local(String utcTime) { + + utcTime = utcTime.substring(0, utcTime.length()-1); + + String[] split = utcTime.split("T"); + + utcTime = split[0]+" "+split[1]; + + SimpleDateFormat utcFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));// 时区定义并进行时间获取 + Date gpsUTCDate = null; + try { + gpsUTCDate = utcFormater.parse(utcTime); + } catch (ParseException e) { + e.printStackTrace(); + } + SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + localFormater.setTimeZone(TimeZone.getDefault()); + String localTime = localFormater.format(gpsUTCDate.getTime()); + return localTime; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/HexStrUtils.java b/src/main/java/com/gizwits/opensource/appkit/utils/HexStrUtils.java new file mode 100644 index 0000000..6b53e54 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/HexStrUtils.java @@ -0,0 +1,58 @@ +package com.gizwits.opensource.appkit.utils; + +import java.util.Locale; + +public class HexStrUtils { + + public static byte[] hexStringToBytes(String hexString) { + if (hexString == null || hexString.equals("")) { + return null; + } + hexString = hexString.toUpperCase(Locale.getDefault()); + int length = hexString.length() / 2; + char[] hexChars = hexString.toCharArray(); + byte[] d = new byte[length]; + for (int i = 0; i < length; i++) { + int pos = i * 2; + d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); + } + return d; + } + + private static byte charToByte(char c) { + return (byte) "0123456789ABCDEF".indexOf(c); + } + + /** + * 数组转换成十六进制字符串 + * + * @param byte[] + * @return HexString + */ + public static final String bytesToHexString(byte[] bArray) { + if (bArray == null) { + return ""; + } + StringBuffer sb = new StringBuffer(bArray.length); + String sTemp; + for (int i = 0; i < bArray.length; i++) { + sTemp = Integer.toHexString(0xFF & bArray[i]); + if (sTemp.length() < 2) + sb.append(0); + sb.append(sTemp.toUpperCase(Locale.getDefault())); + } + return sb.toString(); + } + + public static final String splitBytesString(String byteString) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < byteString.length(); i++) { + sb.append(byteString.charAt(i)); + if (sb.length() % 3 == 0 && sb.charAt(sb.length() - 1) != ' ') { + sb.insert(sb.length() - 1, ' '); + } + } + return sb.toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/NetUtils.java b/src/main/java/com/gizwits/opensource/appkit/utils/NetUtils.java new file mode 100644 index 0000000..e0c6389 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/NetUtils.java @@ -0,0 +1,226 @@ +/** + * Project Name:Gokit + * File Name:NetUtils.java + * Package Name:com.xpg.gokit.utils + * Date:2014-11-18 10:06:37 + * Copyright (c) 2014~2015 Xtreme Programming Group, Inc. + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.gizwits.opensource.appkit.utils; + +import android.app.ActivityManager; +import android.app.ActivityManager.RunningAppProcessInfo; +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiInfo; +import android.net.wifi.WifiManager; +import android.text.TextUtils; +import android.util.Log; + +import java.util.List; + +/** + * 网络工具类. + * + * @author Sunny Ding + * + * * + */ +public class NetUtils { + + /** + * 判断当前手机是否连上Wifi. + * + * @param context + * 上下文 + * @return boolean 是否连上网络 + * + * * + */ + static public boolean isWifiConnected(Context context) { + if (context != null) { + ConnectivityManager mConnectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); + if (mWiFiNetworkInfo != null) { + if (mWiFiNetworkInfo.isAvailable()) { + return mWiFiNetworkInfo.isConnected(); + } else { + return false; + } + } + } + return false; + } + + /** + * 判断当前手机的网络是否可用. + * + * @param context + * 上下文 + * @return boolean 是否连上网络 + * + * * + */ + static public boolean isMobileConnected(Context context) { + if (context != null) { + ConnectivityManager mConnectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); + if (mMobileNetworkInfo != null) { + if (mMobileNetworkInfo.isAvailable()) { + return mMobileNetworkInfo.isConnected(); + } else { + return false; + } + } + } + return false; + } + + /** + * 判断当前网络是手机网络还是WIFI. + * + * @param context + * 上下文 + * @return ConnectedType 数据类型 + * + * * + */ + public static int getConnectedType(Context context) { + if (context != null) { + ConnectivityManager mConnectivityManager = (ConnectivityManager) context + .getSystemService(Context.CONNECTIVITY_SERVICE); + // 获取代表联网状态的NetWorkInfo对象 + NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); + // 判断NetWorkInfo对象是否为空;判断当前的网络连接是否可用 + if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { + return mNetworkInfo.getType(); + } + } + return -1; + } + + /** + * 获取当前WIFI的SSID. + * + * @param context + * 上下文 + * @return ssid + * + * * + */ + public static String getCurentWifiSSID(Context context) { + String ssid = ""; + if (context != null) { + WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); + WifiInfo wifiInfo = wifiManager.getConnectionInfo(); + + if (wifiInfo != null) { + ssid = wifiInfo.getSSID(); + + if (!TextUtils.isEmpty(ssid) && ssid.substring(0, 1).equals("\"") + && ssid.substring(ssid.length() - 1).equals("\"")) { + ssid = ssid.substring(1, ssid.length() - 1); + } + } + + } + return ssid; + } + + /** + * 用来获得手机扫描到的所有wifi的信息. + * + * @param c + * 上下文 + * @return the current wifi scan result + */ + public static List getCurrentWifiScanResult(Context c) { + WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE); + wifiManager.startScan(); + + return wifiManager.getScanResults(); + + } + + public interface WifiSsidList { + + public void ssidList(List list); + } + + static public String getConnectWifiSsid(Context c) { + String ssid = ""; + WifiManager wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE); + WifiInfo wifiInfo = wifiManager.getConnectionInfo(); + if (wifiInfo != null) { + ssid = wifiInfo.getSSID(); + } + return ssid; + } + + // 以下是获得版本信息的工具方法 + + // 版本名 + public static String getVersionName(Context context) { + return getPackageInfo(context).versionName; + } + + // 版本号 + public static int getVersionCode(Context context) { + return getPackageInfo(context).versionCode; + } + + private static PackageInfo getPackageInfo(Context context) { + PackageInfo pi = null; + + try { + PackageManager pm = context.getPackageManager(); + pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS); + + return pi; + } catch (Exception e) { + e.printStackTrace(); + } + + return pi; + } + + // 检测android 应用在前台还是后台 + + public static boolean isBackground(Context context) { + ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); + List appProcesses = activityManager.getRunningAppProcesses(); + for (RunningAppProcessInfo appProcess : appProcesses) { + if (appProcess.processName.equals(context.getPackageName())) { + /* + * BACKGROUND=400 EMPTY=500 FOREGROUND=100 GONE=1000 + * PERCEPTIBLE=130 SERVICE=300 ISIBLE=200 + */ + Log.i(context.getPackageName(), "此appimportace =" + appProcess.importance + + ",context.getClass().getName()=" + context.getClass().getName()); + if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { + Log.i(context.getPackageName(), "处于后台" + appProcess.processName); + return true; + } else { + Log.i(context.getPackageName(), "处于前台" + appProcess.processName); + return false; + } + } + } + return false; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/ReflectionUtils.java b/src/main/java/com/gizwits/opensource/appkit/utils/ReflectionUtils.java new file mode 100644 index 0000000..592b199 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/ReflectionUtils.java @@ -0,0 +1,138 @@ +package com.gizwits.opensource.appkit.utils; + +import android.text.TextUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Created by zhaopan on 2016/11/7. + * e-mail: kangqiao610@gmail.com + */ +public class ReflectionUtils { + + /** + * 循环向上转型, 获取对象的 DeclaredMethod + * + * @param object : 子类对象 + * @param methodName : 父类中的方法名 + * @param parameterTypes : 父类中的方法参数类型 + * @return 父类中的方法对象 + */ + + public static Method getDeclaredMethod(Object object, String methodName, Class... parameterTypes) { + Method method = null; + + for (Class clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + method = clazz.getDeclaredMethod(methodName, parameterTypes); + return method; + } catch (Exception e) { + //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + + return null; + } + + /** + * 直接调用对象方法, 而忽略修饰符(private, protected, default) + * + * @param object : 子类对象 + * @param methodName : 父类中的方法名 + * @param parameterTypes : 父类中的方法参数类型 + * @param parameters : 父类中的方法参数 + * @return 父类中方法的执行结果 + */ + + public static Object invokeMethod(Object object, String methodName, Class[] parameterTypes, + Object[] parameters) { + //根据 对象、方法名和对应的方法参数 通过反射 调用上面的方法获取 Method 对象 + Method method = getDeclaredMethod(object, methodName, parameterTypes); + + //抑制Java对方法进行检查,主要是针对私有方法而言 + method.setAccessible(true); + + try { + if (null != method) { + + //调用object 的 method 所代表的方法,其方法的参数是 parameters + return method.invoke(object, parameters); + } + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + + return null; + } + + /** + * 循环向上转型, 获取对象的 DeclaredField + * + * @param object : 子类对象 + * @param fieldName : 父类中的属性名 + * @return 父类中的属性对象 + */ + + public static Field getDeclaredField(Object object, String fieldName) { + Field field = null; + + Class clazz = object.getClass(); + + for (; clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + field = clazz.getDeclaredField(fieldName); + return field; + } catch (Exception e) { + //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + + return null; + } + + public static Object getFieldValue(Object obj, String fieldName) { + if (obj == null || TextUtils.isEmpty(fieldName)) { + return null; + } + + Class clazz = obj.getClass(); + while (clazz != Object.class) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(obj); + } catch (Exception e) { + } + clazz = clazz.getSuperclass(); + } + return null; + } + + public static void setFieldValue(Object obj, String fieldName, Object value) { + if (obj == null || TextUtils.isEmpty(fieldName)) { + return; + } + Class clazz = obj.getClass(); + while (clazz != Object.class) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(obj, value); + return; + } catch (Exception e) { + } + clazz = clazz.getSuperclass(); + } + } +} + diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/SkxDrawableHelper.java b/src/main/java/com/gizwits/opensource/appkit/utils/SkxDrawableHelper.java new file mode 100644 index 0000000..8545e03 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/SkxDrawableHelper.java @@ -0,0 +1,66 @@ +package com.gizwits.opensource.appkit.utils; + +import android.content.res.ColorStateList; +import android.graphics.drawable.Drawable; +import android.support.v4.graphics.drawable.DrawableCompat; + +public class SkxDrawableHelper { + + /** + * 对目标Drawable 进行着色 + * + * @param drawable 目标Drawable + * @param color 着色的颜色值 + * @return 着色处理后的Drawable + */ + public static Drawable tintDrawable(Drawable drawable, int color) { + // 获取此drawable的共享状态实例 + Drawable wrappedDrawable = getCanTintDrawable(drawable); + // 进行着色 + DrawableCompat.setTint(wrappedDrawable, color); + return wrappedDrawable; + } + + /** + * 对目标Drawable 进行着色。 + * 通过ColorStateList 指定单一颜色 + * + * @param drawable 目标Drawable + * @param color 着色值 + * @return 着色处理后的Drawable + */ + public static Drawable tintListDrawable(Drawable drawable, int color) { + return tintListDrawable(drawable, ColorStateList.valueOf(color)); + } + + /** + * 对目标Drawable 进行着色 + * + * @param drawable 目标Drawable + * @param colors 着色值 + * @return 着色处理后的Drawable + */ + public static Drawable tintListDrawable( Drawable drawable, ColorStateList colors) { + Drawable wrappedDrawable = getCanTintDrawable(drawable); + // 进行着色 + DrawableCompat.setTintList(wrappedDrawable, colors); + return wrappedDrawable; + } + + /** + * 获取可以进行tint 的Drawable + *

+ * 对原drawable进行重新实例化 newDrawable() + * 包装 warp() + * 可变操作 mutate() + * + * @param drawable 原始drawable + * @return 可着色的drawable + */ + private static Drawable getCanTintDrawable(Drawable drawable) { + // 获取此drawable的共享状态实例 + Drawable.ConstantState state = drawable.getConstantState(); + // 对drawable 进行重新实例化、包装、可变操作 + return DrawableCompat.wrap(state == null ? drawable : state.newDrawable()).mutate(); + } +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/utils/ToolUtils.java b/src/main/java/com/gizwits/opensource/appkit/utils/ToolUtils.java new file mode 100644 index 0000000..577e18a --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/utils/ToolUtils.java @@ -0,0 +1,146 @@ +package com.gizwits.opensource.appkit.utils; + +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Color; +import android.graphics.drawable.Drawable; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.R; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by admin on 2017/7/25. + */ + +public class ToolUtils { + public static float getHue(int color) { + float[] HSV = new float[3]; + Color.colorToHSV(color, HSV); + return (HSV[0] * 255 / 360); + } + + public static int getInnerColor(float hue) { + float[] HSV = new float[3]; + HSV[0] = hue * 360 / 255; + HSV[1] = 255; + HSV[2] = 255; + return Color.HSVToColor(HSV); + } + + private static long lastClickTime = 0; + public static final int MIN_CLICK_DELAY_TIME = 800; + + public static boolean noDoubleClick() { + long currentTime = Calendar.getInstance().getTimeInMillis(); + if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { + lastClickTime = currentTime; + return true; + } else { + return false; + } + } + + public static List> parseJson(Context context, String str) throws JSONException { + if (str == null || str.equals("")) { + Toast.makeText(context, context.getString(R.string.download_fail), Toast.LENGTH_SHORT).show(); + } + JSONObject uiJsonObject = new JSONObject(str); + JSONObject jsonObject = uiJsonObject.has("object") ? uiJsonObject.getJSONObject("object") : null; + List> list = new ArrayList>(); + if (uiJsonObject != null) { + JSONArray sessionJsonArrays = uiJsonObject.getJSONArray("sections"); + if (sessionJsonArrays != null) { + for (int i = 0; i < sessionJsonArrays.length(); i++) { + JSONObject session = sessionJsonArrays.getJSONObject(i); + JSONArray elementjJsonArray = session.getJSONArray("elements"); + if (elementjJsonArray != null) { + for (int j = 0; j < elementjJsonArray.length(); j++) { + Map map = new HashMap(); + JSONObject elementObject = elementjJsonArray.getJSONObject(j); + String type = elementObject.getString("type"); + String title = elementObject.has("title") ? elementObject.getString("title") : ""; + map.put("title", title); + map.put("type", type); + String value = null; + if (type.equals("QBooleanElement")) { + value = elementObject.has("boolValue") ? elementObject.getString("boolValue") : ""; + } else if (type.equals("QFloatElement")) { + value = elementObject.has("value") ? elementObject.getString("value") : ""; + } + map.put("value", value); + list.add(map); + } + } + } + + } + } + + return list; + } + + + public static Drawable editIconAlpha(Resources res, int id) { + int color = GosDeploy.appConfig_Contrast(); + Drawable drawable = SkxDrawableHelper.tintDrawable(res.getDrawable(id), color); + drawable.setAlpha(60); + return drawable; + } + + public static Drawable editIcon(Resources res, int id) { + int color = GosDeploy.appConfig_Contrast(); + return SkxDrawableHelper.tintDrawable(res.getDrawable(id), color); + } + + public static int editTextAlpha() { + int color = GosDeploy.appConfig_Contrast(); + int red = Color.red(color); + int green = Color.green(color); + int blue = Color.blue(color); + int color1 = Color.argb(160, red, green, blue); + return color1; + } + + public static int editStatusBarColor(int color) { + int red = Color.red(color); + int green = Color.green(color); + int blue = Color.blue(color); + int color1 = Color.argb(255, red, green, blue); + return color1; + } +// // 需要点击几次 就设置几 +// static long[] mHits = null; +// //public static boolean mShow = false; +// +// public static void onDisplaySettingButton() { +// if (mHits == null) { +// mHits = new long[5]; +// } +// System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);//把从第二位至最后一位之间的数字复制到第一位至倒数第一位 +// mHits[mHits.length - 1] = SystemClock.uptimeMillis();//记录一个时间 +// if (SystemClock.uptimeMillis() - mHits[0] <= 1000) {//一秒内连续点击。 +// mHits = null; //这里说明一下,我们在进来以后需要还原状态,否则如果点击过快,第六次,第七次 都会不断进来触发该效果。重新开始计数即可 +//// if (mShow) { +//// mShow = false; +//// } else { +//// mShow = true; +//// } +// mShow = true; +// Log.e("Tool", "onDisplaySettingButton: 连点五次进入deploy模式"); +// //这里一般会把mShow存储到sp中。 +// } +// } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/view/.DS_Store new file mode 100644 index 0000000..d3aa66b Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/view/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/view/BaseKeyboard.java b/src/main/java/com/gizwits/opensource/appkit/view/BaseKeyboard.java new file mode 100644 index 0000000..01a60c7 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/BaseKeyboard.java @@ -0,0 +1,210 @@ +package com.gizwits.opensource.appkit.view; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.inputmethodservice.Keyboard; +import android.inputmethodservice.KeyboardView; +import android.text.Editable; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.View; +import android.widget.EditText; + +/** + * Created by xud on 2017/3/2. + */ + +public abstract class BaseKeyboard extends Keyboard implements KeyboardView.OnKeyboardActionListener { + + private EditText mEditText; + + private View mNextFocusView; + + private KeyStyle mKeyStyle; + + protected Context mContext; + + public BaseKeyboard(Context context, int xmlLayoutResId) { + super(context, xmlLayoutResId); + mContext = context; + } + + public BaseKeyboard(Context context, int xmlLayoutResId, int modeId, int width, int height) { + super(context, xmlLayoutResId, modeId, width, height); + mContext = context; + } + + public BaseKeyboard(Context context, int xmlLayoutResId, int modeId) { + super(context, xmlLayoutResId, modeId); + mContext = context; + } + + public BaseKeyboard(Context context, int layoutTemplateResId, CharSequence characters, int columns, int horizontalPadding) { + super(context, layoutTemplateResId, characters, columns, horizontalPadding); + mContext = context; + } + + public void setEditText(EditText editText) { + mEditText = editText; + } + + public void setNextFocusView(View nextFocusView) { + mNextFocusView = nextFocusView; + } + + public void setKeyStyle(KeyStyle keyStyle) { + mKeyStyle = keyStyle; + } + + public EditText getEditText() { + return mEditText; + } + + public View getNextFocusView() { + return mNextFocusView; + } + + public KeyStyle getKeyStyle() { + return mKeyStyle; + } + + public int getKeyCode( int redId) { + return mContext.getResources().getInteger(redId); + } + + @Override + public void onPress(int primaryCode) { + + } + + @Override + public void onRelease(int primaryCode) { + + } + + @Override + public void onKey(int primaryCode, int[] keyCodes) { + if (null != mEditText && mEditText.hasFocus() && !handleSpecialKey(primaryCode)) { + Editable editable = mEditText.getText(); + int start = mEditText.getSelectionStart(); + int end = mEditText.getSelectionEnd(); + if (end > start) { + editable.delete(start, end); + } + if (primaryCode == KEYCODE_DELETE) { + if (!TextUtils.isEmpty(editable)) { + if (start > 0) { + editable.delete(start - 1, start); + } + } + } else if (primaryCode == KEYCODE_CANCEL) { + hideKeyboard(); + } else { + editable.insert(start, Character.toString((char) primaryCode)); + } + } + } + + @Override + public void onText(CharSequence text) { + + } + + @Override + public void swipeLeft() { + + } + + @Override + public void swipeRight() { + + } + + @Override + public void swipeDown() { + + } + + @Override + public void swipeUp() { + + } + + public void hideKeyboard() { + if (mNextFocusView != null) { + mNextFocusView.requestFocus(); + } + } + + /** + * @param primaryCode + * @return true if handle the key + * false no handle and dispatch + */ + public abstract boolean handleSpecialKey(int primaryCode); + + public interface KeyStyle { + + public Drawable getKeyBackound(Key key); + + public Float getKeyTextSize(Key key); + + public Integer getKeyTextColor(Key key); + + public CharSequence getKeyLabel(Key key); + } + + public Padding getPadding() { + return new Padding(0, 0, 0, 0); + } + + public static class DefaultKeyStyle implements KeyStyle { + + @Override + public Drawable getKeyBackound(Key key) { + return key.iconPreview; + } + + @Override + public Float getKeyTextSize(Key key) { + return null; + } + + @Override + public Integer getKeyTextColor(Key key) { + return null; + } + + @Override + public CharSequence getKeyLabel(Key key) { + return key.label; + } + } + + public static class Padding { + public int top; + public int left; + public int bottom; + public int right; + + /** + * px + * + * @param top + * @param left + * @param bottom + * @param right + */ + public Padding(int top, int left, int bottom, int right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + } + } + + public float convertSpToPixels(Context context, float sp) { + float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); + return px; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/BaseKeyboardView.java b/src/main/java/com/gizwits/opensource/appkit/view/BaseKeyboardView.java new file mode 100644 index 0000000..c8fc434 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/BaseKeyboardView.java @@ -0,0 +1,202 @@ +package com.gizwits.opensource.appkit.view; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.inputmethodservice.Keyboard; +import android.inputmethodservice.KeyboardView; +import android.os.Build; +import android.util.AttributeSet; +import android.widget.EditText; + +import com.gizwits.opensource.appkit.utils.ReflectionUtils; + +import java.util.List; + +/** + * Created by xud on 2017/3/2. + */ + +public class BaseKeyboardView extends KeyboardView { + + private static final String TAG = "BaseKeyboardView"; + private Drawable rKeyBackground; + private int rLabelTextSize; + private int rKeyTextSize; + private int rKeyTextColor; + private float rShadowRadius; + private int rShadowColor; + + private Rect rClipRegion; + private Keyboard.Key rInvalidatedKey; + + public BaseKeyboardView(Context context, AttributeSet attrs) { + super(context, attrs); + init(context, attrs, 0, 0); + } + + public BaseKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(context, attrs, defStyleAttr, 0); + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public BaseKeyboardView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + init(context, attrs, defStyleAttr, defStyleRes); + } + + private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + rKeyBackground = (Drawable) ReflectionUtils.getFieldValue(this, "mKeyBackground"); + rLabelTextSize = (Integer) ReflectionUtils.getFieldValue(this, "mLabelTextSize"); + rKeyTextSize = (Integer) ReflectionUtils.getFieldValue(this, "mKeyTextSize"); + rKeyTextColor = (Integer) ReflectionUtils.getFieldValue(this, "mKeyTextColor"); + rShadowColor = (Integer) ReflectionUtils.getFieldValue(this, "mShadowColor"); + rShadowRadius = (Float) ReflectionUtils.getFieldValue(this, "mShadowRadius"); + } + + @Override + public void onDraw(Canvas canvas) { + //说明CustomKeyboardView只针对CustomBaseKeyboard键盘进行重绘, + // 且CustomBaseKeyboard必需有设置CustomKeyStyle的回调接口实现, 才进行重绘, 这才有意义 + if (null == getKeyboard() || !(getKeyboard() instanceof BaseKeyboard) || null == ((BaseKeyboard) getKeyboard()).getKeyStyle()) { + super.onDraw(canvas); + return; + } + rClipRegion = (Rect) ReflectionUtils.getFieldValue(this, "mClipRegion"); + rInvalidatedKey = (Keyboard.Key) ReflectionUtils.getFieldValue(this, "mInvalidatedKey"); + super.onDraw(canvas); + onRefreshKey(canvas); + } + + /** + * onRefreshKey是对父类的private void onBufferDraw()进行的重写. 只是在对key的绘制过程中进行了重新设置. + * + * @param canvas + */ + private void onRefreshKey(Canvas canvas) { + final Paint paint = (Paint) ReflectionUtils.getFieldValue(this, "mPaint"); + final Rect padding = (Rect) ReflectionUtils.getFieldValue(this, "mPadding"); + + paint.setColor(rKeyTextColor); + final int kbdPaddingLeft = getPaddingLeft(); + final int kbdPaddingTop = getPaddingTop(); + Drawable keyBackground = null; + + final Rect clipRegion = rClipRegion; + final Keyboard.Key invalidKey = rInvalidatedKey; + boolean drawSingleKey = false; + if (invalidKey != null && canvas.getClipBounds(clipRegion)) { + // Is clipRegion completely contained within the invalidated key? + if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && + invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && + invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && + invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { + drawSingleKey = true; + } + } + + //拿到当前键盘被弹起的输入源 和 键盘为每个key的定制实现customKeyStyle + EditText etCur = ((BaseKeyboard) getKeyboard()).getEditText(); + BaseKeyboard.KeyStyle customKeyStyle = ((BaseKeyboard) getKeyboard()).getKeyStyle(); + + List keys = getKeyboard().getKeys(); + final int keyCount = keys.size(); + //canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); + for (int i = 0; i < keyCount; i++) { + final Keyboard.Key key = keys.get(i); + if (drawSingleKey && invalidKey != key) { + continue; + } + + //获取为Key自定义的背景, 若没有定制, 使用KeyboardView的默认属性keyBackground设置 + keyBackground = customKeyStyle.getKeyBackound(key); + if (null == keyBackground) { + keyBackground = rKeyBackground; + } + + int[] drawableState = key.getCurrentDrawableState(); + keyBackground.setState(drawableState); + + //获取为Key自定义的Label, 若没有定制, 使用xml布局中指定的 + CharSequence keyLabel = customKeyStyle.getKeyLabel(key); + if (null == keyLabel) { + keyLabel = key.label; + } + // Switch the character to uppercase if shift is pressed + String label = keyLabel == null ? null : adjustCase(keyLabel).toString(); + + final Rect bounds = keyBackground.getBounds(); + if (key.width != bounds.right || + key.height != bounds.bottom) { + keyBackground.setBounds(0, 0, key.width, key.height); + } + canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); + keyBackground.draw(canvas); + + if (label != null) { + //获取为Key的Label的字体大小, 若没有定制, 使用KeyboardView的默认属性keyTextSize设置 + Float customKeyTextSize = customKeyStyle.getKeyTextSize(key); + // For characters, use large font. For labels like "Done", use small font. + if (null != customKeyTextSize) { + paint.setTextSize(customKeyTextSize); + paint.setTypeface(Typeface.DEFAULT); + //paint.setTypeface(Typeface.DEFAULT_BOLD); + } else { + if (label.length() > 1 && key.codes.length < 2) { + paint.setTextSize(rLabelTextSize); + paint.setTypeface(Typeface.DEFAULT); + //paint.setTypeface(Typeface.DEFAULT_BOLD); + } else { + paint.setTextSize(rKeyTextSize); + paint.setTypeface(Typeface.DEFAULT); + //paint.setTypeface(Typeface.DEFAULT); + } + } + + //获取为Key的Label的字体颜色, 若没有定制, 使用KeyboardView的默认属性keyTextColor设置 + Integer customKeyTextColor = customKeyStyle.getKeyTextColor(key); + if (null != customKeyTextColor) { + paint.setColor(customKeyTextColor); + } else { + paint.setColor(rKeyTextColor); + } + // Draw a drop shadow for the text + paint.setShadowLayer(rShadowRadius, 0, 0, rShadowColor); + // Draw the text + canvas.drawText(label, + (key.width - padding.left - padding.right) / 2 + + padding.left, + (key.height - padding.top - padding.bottom) / 2 + + (paint.getTextSize() - paint.descent()) / 2 + padding.top, + paint); + // Turn off drop shadow + paint.setShadowLayer(0, 0, 0, 0); + } else if (key.icon != null) { + final int drawableX = (key.width - padding.left - padding.right + - key.icon.getIntrinsicWidth()) / 2 + padding.left; + final int drawableY = (key.height - padding.top - padding.bottom + - key.icon.getIntrinsicHeight()) / 2 + padding.top; + canvas.translate(drawableX, drawableY); + key.icon.setBounds(0, 0, + key.icon.getIntrinsicWidth(), key.icon.getIntrinsicHeight()); + key.icon.draw(canvas); + canvas.translate(-drawableX, -drawableY); + } + canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); + } + rInvalidatedKey = null; + } + + private CharSequence adjustCase(CharSequence label) { + if (getKeyboard().isShifted() && label != null && label.length() < 3 + && Character.isLowerCase(label.charAt(0))) { + label = label.toString().toUpperCase(); + } + return label; + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/CircleProgress.java b/src/main/java/com/gizwits/opensource/appkit/view/CircleProgress.java new file mode 100644 index 0000000..f793c4e --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/CircleProgress.java @@ -0,0 +1,130 @@ +package com.gizwits.opensource.appkit.view; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.View; +import com.gizwits.opensource.appkit.R; + + + +/** + * Created by qiaoning on 2017/8/9. + */ + +public class CircleProgress extends View { + + //小圆的个数 + private int numOfCircles; + //最大圆半径 + private int maxRadius; + //最小圆半径 + private int minRadius; + //旋转速度 + private int rotateSpeedInMillis; + //是否顺时针旋转 + private boolean isClockwise; + //小圆的颜色 + private int circleColor; + + private Paint paint; + + private float rotateDegrees; + private int numOfRotate; + + public CircleProgress(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + // TODO Auto-generated constructor stub + TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CircleProgress); + + numOfCircles = array.getInt(R.styleable.CircleProgress_numOfCircles, 10); + maxRadius = array.getDimensionPixelSize(R.styleable.CircleProgress_maxRadius, dp2px(10)); + minRadius = array.getDimensionPixelSize(R.styleable.CircleProgress_minRadius, dp2px(2)); + rotateSpeedInMillis = array.getInt(R.styleable.CircleProgress_rotateSpeedInMillis, 200); + isClockwise = array.getBoolean(R.styleable.CircleProgress_isClockwise, true); + circleColor = array.getColor(R.styleable.CircleProgress_circleColor, Color.BLACK); + + array.recycle(); + + paint = new Paint(); + paint.setStyle(Paint.Style.FILL); + paint.setAntiAlias(true); + paint.setColor(circleColor); + + //view每次旋转的角度 + rotateDegrees = 360 / numOfCircles; + //旋转的周期为小圆的个数 + numOfRotate = 0; + + } + + public CircleProgress(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public CircleProgress(Context context) { + this(context, null); + } + + @Override + protected void onDraw(Canvas canvas) { + + //按一定角度旋转画布canvas,当旋转周期==小圆个数时重置 + if (numOfRotate == numOfCircles) { + numOfRotate = 0; + } + + //根据旋转的方向旋转画布canvas,然后再画小圆 + if (isClockwise) { + canvas.rotate(rotateDegrees * numOfRotate, getWidth() / 2, getHeight() / 2); + } else { + canvas.rotate(-rotateDegrees * numOfRotate, getWidth() / 2, getHeight() / 2); + } + + //记录旋转的次数,下次invalidat()重绘时就可以使用新的角度旋转canvas,使小圆产生旋转的感觉 + numOfRotate++; + + //取View最短边,并减去最大圆的半径,得到所有圆所在的圆路径的半径 + int radius = (getWidth() > getHeight() ? getHeight() : getWidth()) / 2 - maxRadius; + //每个小圆的半径增量 + float radiusIncrement = (float) (maxRadius - minRadius) / numOfCircles; + //每隔多少度绘制一个小圆,弧度制 + double angle = 2 * Math.PI / numOfCircles; + + //按位置画小圆 + //每个小圆的位置可以由正弦余弦函数求出,并且每个小圆半径依次递增,若反方向则依次递减 + if (isClockwise) { + for (int i = 0; i < numOfCircles; i++) { + float x = (float) (getWidth() / 2 + Math.cos(i * angle) * radius); + float y = (float) (getHeight() / 2 - Math.sin(i * angle) * radius); + canvas.drawCircle(x, y, maxRadius - radiusIncrement * i, paint); + } + } else { + for (int i = 0; i < numOfCircles; i++) { + float x = (float) (getWidth() / 2 + Math.cos(i * angle) * radius); + float y = (float) (getHeight() / 2 - Math.sin(i * angle) * radius); + canvas.drawCircle(x, y, minRadius + radiusIncrement * i, paint); + } + } + + + //旋转间隔,即progressBar的旋转速度 + postDelayed(new Runnable() { + + @Override + public void run() { + // TODO Auto-generated method stub + invalidate(); + } + }, rotateSpeedInMillis); + } + + //dp转px函数 + private int dp2px(int dp) { + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/DotView.java b/src/main/java/com/gizwits/opensource/appkit/view/DotView.java new file mode 100644 index 0000000..d83123a --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/DotView.java @@ -0,0 +1,59 @@ +package com.gizwits.opensource.appkit.view; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Paint.Style; +import android.util.AttributeSet; +import android.view.View; + +import com.gizwits.opensource.appkit.R; + + +public class DotView extends View { + private Paint p; + private int width; + private int height; + private int dash; + + public DotView(Context context, AttributeSet attrs) { + super(context, attrs); + init(context); + } + + public DotView(Context context) { + super(context); + init(context); + } + private void init(Context context){ + p = new Paint(Paint.ANTI_ALIAS_FLAG); + p.setStyle(Style.FILL); + p.setColor(context.getResources().getColor(R.color.line_gray)); + + final float scale = context.getResources().getDisplayMetrics().density; + dash=(int) (3 * scale + 0.5f); + } + @Override + protected void onDraw(Canvas canvas) { + + if(width>10){ + for(int i=0;i= Build.VERSION_CODES.HONEYCOMB) { + setLayerType(View.LAYER_TYPE_SOFTWARE, null); + } + // 从描述文件中读出gif的值,创建出Movie实例 + final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.GifView, defStyle, + R.style.Widget_GifView); + mMovieResourceId = array.getResourceId(R.styleable.GifView_gif, -1); + mPaused = array.getBoolean(R.styleable.GifView_paused, false); + array.recycle(); + if (mMovieResourceId != -1) { + mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId)); + } + } + + /** + * 设置gif图资源 + * + * @param movieResId + */ + public void setMovieResource(int movieResId) { + this.mMovieResourceId = movieResId; + mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId)); + requestLayout(); + } + + public void setMovie(Movie movie) { + this.mMovie = movie; + requestLayout(); + } + + public Movie getMovie() { + return mMovie; + } + + public void setMovieTime(int time) { + mCurrentAnimationTime = time; + invalidate(); + } + + /** + * 设置暂停 + * + * @param paused + */ + public void setPaused(boolean paused) { + this.mPaused = paused; + if (!paused) { + mMovieStart = android.os.SystemClock.uptimeMillis() - mCurrentAnimationTime; + } + invalidate(); + } + + /** + * 判断gif图是否停止了 + * + * @return + */ + public boolean isPaused() { + return this.mPaused; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + if (mMovie != null) { + int movieWidth = mMovie.width(); + int movieHeight = mMovie.height(); + int maximumWidth = MeasureSpec.getSize(widthMeasureSpec); + float scaleW = (float) movieWidth / (float) maximumWidth; + mScale = 1f / scaleW; + mMeasuredMovieWidth = maximumWidth; + mMeasuredMovieHeight = (int) (movieHeight * mScale); + setMeasuredDimension(mMeasuredMovieWidth, mMeasuredMovieHeight); + } else { + setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight()); + } + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + mLeft = (getWidth() - mMeasuredMovieWidth) / 2f; + mTop = (getHeight() - mMeasuredMovieHeight) / 2f; + mVisible = getVisibility() == View.VISIBLE; + } + + @Override + protected void onDraw(Canvas canvas) { + if (mMovie != null) { + if (!mPaused) { + updateAnimationTime(); + drawMovieFrame(canvas); + invalidateView(); + } else { + drawMovieFrame(canvas); + } + } + } + + private void invalidateView() { + if (mVisible) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) { + postInvalidate(); + } else { + invalidate(); + } + } + } + + private void updateAnimationTime() { + long now = android.os.SystemClock.uptimeMillis(); + // 如果第一帧,记录起始时间 + if (mMovieStart == 0) { + mMovieStart = now; + } + // 取出动画的时长 + int dur = mMovie.duration(); + if (dur == 0) { + dur = DEFAULT_MOVIE_DURATION; + } + // 算出需要显示第几帧 + mCurrentAnimationTime = (int) ((now - mMovieStart) % dur); + } + + private void drawMovieFrame(Canvas canvas) { + // 设置要显示的帧,绘制即可 + mMovie.setTime(mCurrentAnimationTime); + canvas.saveLayer(0, 0, getWidth(), getHeight(), null); + canvas.scale(mScale, mScale); + mMovie.draw(canvas, mLeft / mScale, mTop / mScale); + canvas.restore(); + } + + public void onScreenStateChanged(int screenState) { + mVisible = screenState == DEFAULT_MOVIE_DURATION; + invalidateView(); + } + + @Override + protected void onVisibilityChanged(View changedView, int visibility) { + super.onVisibilityChanged(changedView, visibility); + mVisible = visibility == View.VISIBLE; + invalidateView(); + } + + @Override + protected void onWindowVisibilityChanged(int visibility) { + super.onWindowVisibilityChanged(visibility); + mVisible = visibility == View.VISIBLE; + invalidateView(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/view/HexWatcher.java b/src/main/java/com/gizwits/opensource/appkit/view/HexWatcher.java new file mode 100644 index 0000000..d911693 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/HexWatcher.java @@ -0,0 +1,63 @@ +package com.gizwits.opensource.appkit.view; + +import java.util.Locale; + +import android.text.Editable; +import android.text.TextWatcher; +import android.widget.EditText; + +public class HexWatcher implements TextWatcher { + private EditText _text; + + public HexWatcher(EditText _text) { + this._text = _text; + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + if (s == null || s.length() == 0) + return; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == ' ' && i < s.length() - 1) { + continue; + } else { + sb.append(s.charAt(i)); + if (sb.length() % 3 == 0 && sb.charAt(sb.length() - 1) != ' ') { + sb.insert(sb.length() - 1, ' '); + } + } + } + + if (!sb.toString().equals(s.toString())) { + int index = start + 1; + if (sb.charAt(start) == ' ') { + if (before == 0) { + index++; + } else { + index--; + } + } else { + if (before == 1) { + index--; + } + } + _text.setText(sb.toString().toUpperCase(Locale.getDefault())); + _text.setSelection(index); + } + + // _text.removeTextChangedListener(this); + // _text.setText(s.toString().toUpperCase(Locale.getDefault())); + // _text.addTextChangedListener(this); + + } + + @Override + public void afterTextChanged(Editable s) { + } + +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/view/KeyboardWithSearchView.java b/src/main/java/com/gizwits/opensource/appkit/view/KeyboardWithSearchView.java new file mode 100644 index 0000000..a004cd7 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/KeyboardWithSearchView.java @@ -0,0 +1,123 @@ +package com.gizwits.opensource.appkit.view; + +import android.annotation.TargetApi; +import android.content.Context; +import android.os.Build; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.LinearLayout; + +import com.gizwits.opensource.appkit.R; + + +/** + * Created by xud on 2017/3/9. + */ + +public class KeyboardWithSearchView extends LinearLayout { + + + private Context mContext; + + + private BaseKeyboardView mBaseKeyboardView; + + private LinearLayout mKeyboadViewContainer; + + //private OnSizeChangedListener mOnSizeChangedListener; + + + public KeyboardWithSearchView(Context context) { + super(context); + init(context); + } + + public KeyboardWithSearchView(Context context, AttributeSet attrs) { + super(context, attrs); + init(context); + } + + public KeyboardWithSearchView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(context); + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + public KeyboardWithSearchView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + init(context); + } + +// protected RecyclerView getRecyclerView() { +// return mRecyclerView; +// } + + public BaseKeyboardView getBaseKeyboardView() { + return mBaseKeyboardView; + } + + +// public void setOnSizeChangedListener(OnSizeChangedListener onSizeChangedListener) { +// mOnSizeChangedListener = onSizeChangedListener; +// } + + public LinearLayout getKeyboadViewContainer() { + return mKeyboadViewContainer; + } + + + private void init(Context context) { + mContext = context; + View view = LayoutInflater.from(context).inflate(R.layout.layout_recycler_keyboard_view, this, true); +// mRecyclerView = (RecyclerView) view.findViewById(R.id.search_recycler_view); + mBaseKeyboardView = (BaseKeyboardView) view.findViewById(R.id.keyboard_view); + mKeyboadViewContainer = (LinearLayout) view.findViewById(R.id.keyboard_container); + } + +// public void initRecyclerView(KeyboardSearchBaseAdapter adapter, RecyclerView.LayoutManager manager, RecyclerView.ItemDecoration itemDecoration) { +// mRecyclerView.setAdapter(adapter); +// mRecyclerView.setLayoutManager(manager); +// mRecyclerView.addItemDecoration(itemDecoration); +// } +// +// public void setSearchResult(List list, boolean hasFixedSize) { +// if(mRecyclerView.getAdapter() == null) { +// throw new RuntimeException("this view has not invoked init method"); +// } +// mRecyclerView.getLayoutManager().scrollToPosition(0); +// if(list == null || list.size() ==0) { +// mRecyclerView.setVisibility(GONE); +// } else { +// int height = AssetsUtils.diptopx(mContext, Math.min(3,list.size()) * 49) + +// Math.min(3,list.size()); +// ViewGroup.LayoutParams params = mRecyclerView.getLayoutParams(); +// if(params != null) { +// params.height = height; +// }else { +// LinearLayout.LayoutParams newParams = +// new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, +// height); +// mRecyclerView.setLayoutParams(newParams); +// } +// mRecyclerView.setVisibility(VISIBLE); +// } +// mRecyclerView.setHasFixedSize(hasFixedSize); +// +// KeyboardSearchBaseAdapter adapter = (KeyboardSearchBaseAdapter) mRecyclerView.getAdapter(); +// adapter.setAdapterData(list); +// adapter.notifyDataSetChanged(); +// } + +// @Override +// protected void onSizeChanged(int w, int h, int oldw, int oldh) { +// super.onSizeChanged(w, h, oldw, oldh); +// if(mOnSizeChangedListener != null) { +// mOnSizeChangedListener.sizeChanged(w,h,oldw,oldh); +// } +// } +// +// protected interface OnSizeChangedListener { +// void sizeChanged(int w, int h, int oldw, int oldh); +// } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/RoundProgressBar.java b/src/main/java/com/gizwits/opensource/appkit/view/RoundProgressBar.java new file mode 100644 index 0000000..b6d69f2 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/RoundProgressBar.java @@ -0,0 +1,266 @@ +package com.gizwits.opensource.appkit.view; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.RectF; +import android.graphics.Typeface; +import android.util.AttributeSet; +import android.view.View; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.utils.AssetsUtils; + + +/** + * 仿iphone带进度的进度条,线程安全的View,可直接在线程中更新进度 + * + * @author xiaanming + */ +public class RoundProgressBar extends View { + /** + * 画笔对象的引用 + */ + private Paint paint; + + /** + * 圆环的颜色 + */ + private int roundColor; + + /** + * 圆环进度的颜色 + */ + private int roundProgressColor; + + /** + * 中间进度百分比的字符串的颜色 + */ + private int textColor; + + /** + * 中间进度百分比的字符串的字体 + */ + private float textSize; + + /** + * 中间进度的字体 + */ + private String text; + + /** + * 圆环的宽度 + */ + private float roundWidth; + + /** + * 最大进度 + */ + private int max; + + + /** + * 当前进度 + */ + private float progress; + /** + * 是否显示中间的进度 + */ + private boolean textIsDisplayable; + + /** + * 进度的风格,实心或者空心 + */ + private int style; + + public static final int STROKE = 0; + public static final int FILL = 1; + + public RoundProgressBar(Context context) { + this(context, null); + } + + public RoundProgressBar(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public RoundProgressBar(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + + paint = new Paint(); + + TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar); + + // 获取自定义属性和默认值 + int color = GosDeploy.appConfig_Background(); + roundColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundColor, getResources().getColor(R.color.roundcolor)); + roundProgressColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundProgressColor, color); + textColor = mTypedArray.getColor(R.styleable.RoundProgressBar_textColor, getResources().getColor(R.color.text_state)); + textSize = mTypedArray.getDimension(R.styleable.RoundProgressBar_textSize, AssetsUtils.sptopx(context, 20)); + roundWidth = mTypedArray.getDimension(R.styleable.RoundProgressBar_roundWidth, 3); + max = mTypedArray.getInteger(R.styleable.RoundProgressBar_max, 100); + text = mTypedArray.getString(R.styleable.RoundProgressBar_text); + if (text == null) { + text = "%"; + } + textIsDisplayable = mTypedArray.getBoolean(R.styleable.RoundProgressBar_textIsDisplayable, true); + style = mTypedArray.getInt(R.styleable.RoundProgressBar_style, 0); + + mTypedArray.recycle(); + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + + /** + * 画最外层的大圆环 + */ + int centre = getWidth() / 2; // 获取圆心的x坐标 + int radius = (int) (centre - 1 - roundWidth / 2); // 圆环的半径 + paint.setColor(roundColor); // 设置圆环的颜色 + paint.setStyle(Paint.Style.STROKE); // 设置空心 + paint.setStrokeWidth(roundWidth); // 设置圆环的宽度 + paint.setAntiAlias(true); // 消除锯齿 + canvas.drawCircle(centre, centre, radius, paint); // 画出圆环 + + + /** + * 画进度百分比 + */ + paint.setStrokeWidth(0); + paint.setColor(textColor); + paint.setTextSize(textSize); + paint.setTypeface(Typeface.DEFAULT_BOLD); // 设置字体 + if (text.equals("s")) { + int percent = 180 - (int) progress; // 中间的进度百分比,先转换成float在进行除法运算,不然都为0 + + float textWidth = paint.measureText(percent + "s"); // 测量字体宽度,我们需要根据字体的宽度设置在圆环中间 + + if (textIsDisplayable && percent != 0 && style == STROKE) { + canvas.drawText(percent + "s", centre - textWidth / 2, centre + textSize / 2, paint); // 画出进度百分比 + } + } else { + int percent = (int) (((float) progress / (float) max) * 100); // 中间的进度百分比,先转换成float在进行除法运算,不然都为0 + float textWidth = paint.measureText(percent + "%"); // 测量字体宽度,我们需要根据字体的宽度设置在圆环中间 + + if (textIsDisplayable && percent != 0 && style == STROKE) { + canvas.drawText(percent + "%", centre - textWidth / 2, centre + textSize / 2, paint); // 画出进度百分比 + } + } + + + /** + * 画圆弧 ,画圆环的进度 + */ + + // 设置进度是实心还是空心 + paint.setStrokeWidth(roundWidth * 2); // 设置圆环的宽度 + paint.setColor(roundProgressColor); // 设置进度的颜色 + paint.setAntiAlias(true); // 消除锯齿 + RectF oval = new RectF(centre - radius + 1.5f, centre - radius + 1.5f, centre + radius - 1.5f, + centre + radius - 1.5f); // 用于定义的圆弧的形状和大小的界限 + + switch (style) { + case STROKE: { + paint.setStyle(Paint.Style.STROKE); + canvas.drawArc(oval, -90, 360 * progress / max, false, paint); // 根据进度画圆弧 + break; + } + case FILL: { + paint.setStyle(Paint.Style.FILL_AND_STROKE); + if (progress != 0) + canvas.drawArc(oval, -90, 360 * progress / max, true, paint); // 根据进度画圆弧 + break; + } + } + + } + + public synchronized int getMax() { + return max; + } + + /** + * 设置进度的最大值 + * + * @param max + */ + public synchronized void setMax(int max) { + if (max < 0) { + throw new IllegalArgumentException("max not less than 0"); + } + this.max = max; + } + + /** + * 获取进度.需要同步 + * + * @return + */ + public synchronized float getProgress() { + return progress; + } + + /** + * 设置进度,此为线程安全控件,由于考虑多线的问题,需要同步 刷新界面调用postInvalidate()能在非UI线程刷新 + * + * @param progress + */ + public synchronized void setProgress(double progress) { + if (progress < 0) { + throw new IllegalArgumentException("progress not less than 0"); + } + if (progress > max) { + progress = max; + } + if (progress <= max) { + this.progress = (float) progress; + postInvalidate(); + } + + } + + public int getCricleColor() { + return roundColor; + } + + public void setCricleColor(int cricleColor) { + this.roundColor = cricleColor; + } + + public int getCricleProgressColor() { + return roundProgressColor; + } + + public void setCricleProgressColor(int cricleProgressColor) { + this.roundProgressColor = cricleProgressColor; + } + + public int getTextColor() { + return textColor; + } + + public void setTextColor(int textColor) { + this.textColor = textColor; + } + + public float getTextSize() { + return textSize; + } + + public void setTextSize(float textSize) { + this.textSize = textSize; + } + + public float getRoundWidth() { + return roundWidth; + } + + public void setRoundWidth(float roundWidth) { + this.roundWidth = roundWidth; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/SlideListView2.java b/src/main/java/com/gizwits/opensource/appkit/view/SlideListView2.java new file mode 100644 index 0000000..671bba6 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/SlideListView2.java @@ -0,0 +1,309 @@ +package com.gizwits.opensource.appkit.view; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.widget.AdapterView; +import android.widget.ListView; +import android.widget.Scroller; + +/** + * 侧向滑出菜单的ListView 使用请注意与ListView的Item的布局配合, + * 该效果的实现是基于在Item的布局中通过设置PaddingLeft和PaddingRight来隐藏左右菜单的, + * 所以使用此ListView时,请务必在布局Item时使用PaddingLeft和PaddingRight; + * 或者自己改写此ListView,已达到想要的实现方式 + * + * @author zhangshuo + */ +@SuppressLint({"ClickableViewAccessibility", "Recycle"}) +public class SlideListView2 extends ListView { + + /** + * 禁止侧滑模式 + */ + public static int MOD_FORBID = 0; + /** + * 从左向右滑出菜单模式 + */ + public static int MOD_LEFT = 1; + /** + * 从右向左滑出菜单模式 + */ + public static int MOD_RIGHT = 2; + /** + * 左右均可以滑出菜单模式 + */ + public static int MOD_BOTH = 3; + /** + * 当前的模式 + */ + private int mode = MOD_FORBID; + /** + * 左侧菜单的长度 + */ + private int leftLength = 0; + /** + * 右侧菜单的长度 + */ + private int rightLength = 0; + + /** + * 当前滑动的ListView position + */ + private int slidePosition; + /** + * 手指按下X的坐标 + */ + private int downY; + /** + * 手指按下Y的坐标 + */ + private int downX; + /** + * ListView的item + */ + private View itemView; + /** + * 滑动类 + */ + private Scroller scroller; + /** + * 认为是用户滑动的最小距离 + */ + private int mTouchSlop; + + /** + * 判断是否可以侧向滑动 + */ + private boolean canMove = false; + /** + * 标示是否完成侧滑 + */ + private boolean isSlided = false; + + public SlideListView2(Context context) { + this(context, null); + } + + public SlideListView2(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public SlideListView2(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + scroller = new Scroller(context); + mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); + } + + /** + * 初始化菜单的滑出模式 + * + * @param mode + */ + public void initSlideMode(int mode) { + this.mode = mode; + } + + /** + * 处理我们拖动ListView item的逻辑 + */ + @Override + public boolean onTouchEvent(MotionEvent ev) { + + final int action = ev.getAction(); + int lastX = (int) ev.getX(); + + switch (action) { + case MotionEvent.ACTION_DOWN: + System.out.println("touch-->" + "down"); + + /* 当前模式不允许滑动,则直接返回,交给ListView自身去处理 */ + if (this.mode == MOD_FORBID) { + return super.onTouchEvent(ev); + } + + // 如果处于侧滑完成状态,侧滑回去,并直接返回 + if (isSlided) { + scrollBack(); + return false; + } + // 假如scroller滚动还没有结束,我们直接返回 + if (!scroller.isFinished()) { + return false; + } + downX = (int) ev.getX(); + downY = (int) ev.getY(); + + slidePosition = pointToPosition(downX, downY); + + // 无效的position, 不做任何处理 + if (slidePosition == AdapterView.INVALID_POSITION) { + return super.onTouchEvent(ev); + } + + // 获取我们点击的item view + itemView = getChildAt(slidePosition - getFirstVisiblePosition()); + + /* 此处根据设置的滑动模式,自动获取左侧或右侧菜单的长度 */ + if (this.mode == MOD_BOTH) { + this.leftLength = -itemView.getPaddingLeft(); + this.rightLength = -itemView.getPaddingRight(); + } else if (this.mode == MOD_LEFT) { + this.leftLength = -itemView.getPaddingLeft(); + } else if (this.mode == MOD_RIGHT) { + this.rightLength = -itemView.getPaddingRight(); + } + + break; + case MotionEvent.ACTION_MOVE: + System.out.println("touch-->" + "move"); + + if (!canMove && slidePosition != AdapterView.INVALID_POSITION + && (Math.abs(ev.getX() - downX) > mTouchSlop && Math.abs(ev.getY() - downY) < mTouchSlop)) { + int offsetX = downX - lastX; + if (offsetX > 0 && (this.mode == MOD_BOTH || this.mode == MOD_RIGHT)) { + /* 从右向左滑 */ + canMove = true; + } /* + * else if(offsetX < 0 && (this.mode == MOD_BOTH || + * this.mode == MOD_LEFT)){ 从左向右滑 canMove = true; } + */ else { + canMove = false; + } + /* 此段代码是为了避免我们在侧向滑动时同时出发ListView的OnItemClickListener时间 */ + MotionEvent cancelEvent = MotionEvent.obtain(ev); + cancelEvent.setAction( + MotionEvent.ACTION_CANCEL | (ev.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); + onTouchEvent(cancelEvent); + } + if (canMove) { + /* 设置此属性,可以在侧向滑动时,保持ListView不会上下滚动 */ + requestDisallowInterceptTouchEvent(true); + + // 手指拖动itemView滚动, deltaX大于0向左滚动,小于0向右滚 + int deltaX = downX - lastX; + if (deltaX < 0 && (this.mode == MOD_BOTH || this.mode == MOD_LEFT)) { + /* 向左滑 */ + itemView.scrollTo(deltaX, 0); + } else if (deltaX > 0 && (this.mode == MOD_BOTH || this.mode == MOD_RIGHT)) { + /* 向右滑 */ + itemView.scrollTo(deltaX, 0); + } else { + itemView.scrollTo(0, 0); + } + return true; // 拖动的时候ListView不滚动 + } + case MotionEvent.ACTION_UP: + System.out.println("touch-->" + "up"); + if (canMove) { + canMove = false; + scrollByDistanceX(); + } + break; + } + + // 否则直接交给ListView来处理onTouchEvent事件 + return super.onTouchEvent(ev); + } + + /** + * 根据手指滚动itemView的距离来判断是滚动到开始位置还是向左或者向右滚动 + */ + private void scrollByDistanceX() { + /* 当前模式不允许滑动,则直接返回 */ + if (this.mode == MOD_FORBID) { + return; + } + if (itemView.getScrollX() > 0 && (this.mode == MOD_BOTH || this.mode == MOD_RIGHT)) { + /* 从右向左滑 */ + if (itemView.getScrollX() >= rightLength / 2) { + scrollLeft(); + } else { + // 滚回到原始位置 + scrollBack(); + } + } else if (itemView.getScrollX() < 0 && (this.mode == MOD_BOTH || this.mode == MOD_LEFT)) { + /* 从左向右滑 */ + if (itemView.getScrollX() <= -leftLength / 2) { + scrollRight(); + } else { + // 滚回到原始位置 + scrollBack(); + } + } else { + // 滚回到原始位置 + scrollBack(); + } + + } + + /** + * 往右滑动,getScrollX()返回的是左边缘的距离,就是以View左边缘为原点到开始滑动的距离,所以向右边滑动为负值 + */ + private void scrollRight() { + isSlided = true; + final int delta = (leftLength + itemView.getScrollX()); + // 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item + scroller.startScroll(itemView.getScrollX(), 0, -delta, 0, Math.abs(delta)); + postInvalidate(); // 刷新itemView + } + + /** + * 向左滑动,根据上面我们知道向左滑动为正值 + */ + private void scrollLeft() { + isSlided = true; + final int delta = (rightLength - itemView.getScrollX()); + // 调用startScroll方法来设置一些滚动的参数,我们在computeScroll()方法中调用scrollTo来滚动item + scroller.startScroll(itemView.getScrollX(), 0, delta, 0, Math.abs(delta)); + postInvalidate(); // 刷新itemView + } + + /** + * 滑动会原来的位置 + */ + private void scrollBack() { + isSlided = false; + if (itemView != null) { + scroller.startScroll(itemView.getScrollX(), 0, -itemView.getScrollX(), 0, Math.abs(itemView.getScrollX())); + } + postInvalidate(); // 刷新itemView + } + + @Override + public void computeScroll() { + // 调用startScroll的时候scroller.computeScrollOffset()返回true, + if (scroller.computeScrollOffset()) { + // 让ListView item根据当前的滚动偏移量进行滚动 + itemView.scrollTo(scroller.getCurrX(), scroller.getCurrY()); + + postInvalidate(); + } + } + + // TODO 此处方法使ListView或GridView与ScrollView相适应 + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + + int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, + + MeasureSpec.AT_MOST); + + super.onMeasure(widthMeasureSpec, expandSpec); + + } + + /** + * 提供给外部调用,用以将侧滑出来的滑回去 + */ + public void slideBack() { + this.scrollBack(); + } + + public boolean isSlided() { + return isSlided; + } + +} \ No newline at end of file diff --git a/src/main/java/com/gizwits/opensource/appkit/view/SuperSwipeRefreshLayout.java b/src/main/java/com/gizwits/opensource/appkit/view/SuperSwipeRefreshLayout.java new file mode 100644 index 0000000..bf9928a --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/SuperSwipeRefreshLayout.java @@ -0,0 +1,1466 @@ +package com.gizwits.opensource.appkit.view; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ValueAnimator; +import android.animation.ValueAnimator.AnimatorUpdateListener; +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.RectF; +import android.os.Build; +import android.os.Handler; +import android.support.v4.view.MotionEventCompat; +import android.support.v4.view.ViewCompat; +import android.support.v4.widget.NestedScrollView; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.RecyclerView.LayoutManager; +import android.support.v7.widget.StaggeredGridLayoutManager; +import android.util.AttributeSet; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.Display; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.animation.Animation; +import android.view.animation.Animation.AnimationListener; +import android.view.animation.DecelerateInterpolator; +import android.view.animation.Transformation; +import android.widget.AbsListView; +import android.widget.RelativeLayout; +import android.widget.ScrollView; + +/* + * @Description 自定义CustomeSwipeRefreshLayout
+ * 支持下拉刷新和上拉加载更多
+ * 非侵入式,对原来的ListView、RecyclerView没有任何影响,用法和SwipeRefreshLayout类似。
+ * 可自定义头部View的样式,调用setHeaderView方法即可
+ * 可自定义页尾View的样式,调用setFooterView方法即可
+ * 支持RecyclerView,ListView,ScrollView,GridView等等。
+ * 被包含的View(RecyclerView,ListView etc.)可跟随手指的滑动而滑动
+ * 默认是跟随手指的滑动而滑动,也可以设置为不跟随:setTargetScrollWithLayout(false) 回调方法更多
+ * 比如:onRefresh() onPullDistance(int distance)和onPullEnable(boolean + * enable)
+ */ +@SuppressLint("ClickableViewAccessibility") +public class SuperSwipeRefreshLayout extends ViewGroup { + private static final String LOG_TAG = "CustomeSwipeRefreshLayout"; + private static final int HEADER_VIEW_HEIGHT = 50;// HeaderView height (dp) + + private static final float DECELERATE_INTERPOLATION_FACTOR = 2f; + private static final int INVALID_POINTER = -1; + private static final float DRAG_RATE = .5f; + + private static final int SCALE_DOWN_DURATION = 150; + private static final int ANIMATE_TO_TRIGGER_DURATION = 200; + private static final int ANIMATE_TO_START_DURATION = 200; + private static final int DEFAULT_CIRCLE_TARGET = 64; + + // SuperSwipeRefreshLayout内的目标View,比如RecyclerView,ListView,ScrollView,GridView + // etc. + private View mTarget; + + private OnPullRefreshListener mListener;// 下拉刷新listener + private OnPushLoadMoreListener mOnPushLoadMoreListener;// 上拉加载更多 + + private boolean mRefreshing = false; + private boolean mLoadMore = false; + private int mTouchSlop; + private float mTotalDragDistance = -1; + private int mMediumAnimationDuration; + private int mCurrentTargetOffsetTop; + private boolean mOriginalOffsetCalculated = false; + + private float mInitialMotionY; + private boolean mIsBeingDragged; + private int mActivePointerId = INVALID_POINTER; + private boolean mScale; + + private boolean mReturningToStart; + private final DecelerateInterpolator mDecelerateInterpolator; + private static final int[] LAYOUT_ATTRS = new int[]{android.R.attr.enabled}; + + private HeadViewContainer mHeadViewContainer; + private RelativeLayout mFooterViewContainer; + private int mHeaderViewIndex = -1; + private int mFooterViewIndex = -1; + + protected int mFrom; + + private float mStartingScale; + + protected int mOriginalOffsetTop; + + private Animation mScaleAnimation; + + private Animation mScaleDownAnimation; + + private Animation mScaleDownToStartAnimation; + + // 最后停顿时的偏移量px,与DEFAULT_CIRCLE_TARGET正比 + private float mSpinnerFinalOffset; + + private boolean mNotify; + + private int mHeaderViewWidth;// headerView的宽度 + + private int mFooterViewWidth; + + private int mHeaderViewHeight; + + private int mFooterViewHeight; + + private boolean mUsingCustomStart; + + private boolean targetScrollWithLayout = true; + + private int pushDistance = 0; + + private CircleProgressView defaultProgressView = null; + + private boolean usingDefaultHeader = true; + + private float density = 1.0f; + + private boolean isProgressEnable = true; + + /** + * 下拉时,超过距离之后,弹回来的动画监听器 + */ + private AnimationListener mRefreshListener = new AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + isProgressEnable = false; + } + + @Override + public void onAnimationRepeat(Animation animation) { + } + + @Override + public void onAnimationEnd(Animation animation) { + isProgressEnable = true; + if (mRefreshing) { + if (mNotify) { + if (usingDefaultHeader) { + ViewCompat.setAlpha(defaultProgressView, 1.0f); + defaultProgressView.setOnDraw(true); + new Thread(defaultProgressView).start(); + } + if (mListener != null) { + mListener.onRefresh(); + } + } + } else { + mHeadViewContainer.setVisibility(View.GONE); + if (mScale) { + setAnimationProgress(0); + } else { + setTargetOffsetTopAndBottom(mOriginalOffsetTop + - mCurrentTargetOffsetTop, true); + } + } + mCurrentTargetOffsetTop = mHeadViewContainer.getTop(); + updateListenerCallBack(); + } + }; + + /** + * 更新回调 + */ + private void updateListenerCallBack() { + int distance = mCurrentTargetOffsetTop + mHeadViewContainer.getHeight(); + if (mListener != null) { + mListener.onPullDistance(distance); + } + if (usingDefaultHeader && isProgressEnable) { + defaultProgressView.setPullDistance(distance); + } + } + + /** + * 添加头布局 + * + * @param child + */ + public void setHeaderView(View child) { + if (child == null) { + return; + } + if (mHeadViewContainer == null) { + return; + } + usingDefaultHeader = false; + mHeadViewContainer.removeAllViews(); + RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( + mHeaderViewWidth, mHeaderViewHeight); + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); + mHeadViewContainer.addView(child, layoutParams); + } + + public void setFooterView(View child) { + if (child == null) { + return; + } + if (mFooterViewContainer == null) { + return; + } + mFooterViewContainer.removeAllViews(); + RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( + mFooterViewWidth, mFooterViewHeight); + mFooterViewContainer.addView(child, layoutParams); + } + + public SuperSwipeRefreshLayout(Context context) { + this(context, null); + } + + @SuppressWarnings("deprecation") + public SuperSwipeRefreshLayout(Context context, AttributeSet attrs) { + super(context, attrs); + + /** + * getScaledTouchSlop是一个距离,表示滑动的时候,手的移动要大于这个距离才开始移动控件。如果小于这个距离就不触发移动控件 + */ + mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); + + mMediumAnimationDuration = getResources().getInteger( + android.R.integer.config_mediumAnimTime); + + setWillNotDraw(false); + mDecelerateInterpolator = new DecelerateInterpolator( + DECELERATE_INTERPOLATION_FACTOR); + + final TypedArray a = context + .obtainStyledAttributes(attrs, LAYOUT_ATTRS); + setEnabled(a.getBoolean(0, true)); + a.recycle(); + + WindowManager wm = (WindowManager) context + .getSystemService(Context.WINDOW_SERVICE); + Display display = wm.getDefaultDisplay(); + final DisplayMetrics metrics = getResources().getDisplayMetrics(); + mHeaderViewWidth = (int) display.getWidth(); + mFooterViewWidth = (int) display.getWidth(); + mHeaderViewHeight = (int) (HEADER_VIEW_HEIGHT * metrics.density); + mFooterViewHeight = (int) (HEADER_VIEW_HEIGHT * metrics.density); + defaultProgressView = new CircleProgressView(getContext()); + createHeaderViewContainer(); + createFooterViewContainer(); + ViewCompat.setChildrenDrawingOrderEnabled(this, true); + mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density; + density = metrics.density; + mTotalDragDistance = mSpinnerFinalOffset; + } + + /* + * 孩子节点绘制的顺序 + * + * @param childCount + * @param i + * @return + */ + @Override + protected int getChildDrawingOrder(int childCount, int i) { + // 将新添加的View,放到最后绘制 + if (mHeaderViewIndex < 0 && mFooterViewIndex < 0) { + return i; + } + if (i == childCount - 2) { + return mHeaderViewIndex; + } + if (i == childCount - 1) { + return mFooterViewIndex; + } + int bigIndex = mFooterViewIndex > mHeaderViewIndex ? mFooterViewIndex + : mHeaderViewIndex; + int smallIndex = mFooterViewIndex < mHeaderViewIndex ? mFooterViewIndex + : mHeaderViewIndex; + if (i >= smallIndex && i < bigIndex - 1) { + return i + 1; + } + if (i >= bigIndex || (i == bigIndex - 1)) { + return i + 2; + } + return i; + } + + /* + * 创建头布局的容器 + */ + private void createHeaderViewContainer() { + RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( + (int) (mHeaderViewHeight * 0.8), + (int) (mHeaderViewHeight * 0.8)); + layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); + mHeadViewContainer = new HeadViewContainer(getContext()); + mHeadViewContainer.setVisibility(View.GONE); + defaultProgressView.setVisibility(View.VISIBLE); + defaultProgressView.setOnDraw(false); + mHeadViewContainer.addView(defaultProgressView, layoutParams); + addView(mHeadViewContainer); + } + + /* + * 添加底部布局 + */ + private void createFooterViewContainer() { + mFooterViewContainer = new RelativeLayout(getContext()); + mFooterViewContainer.setVisibility(View.GONE); + addView(mFooterViewContainer); + } + + /* + * 设置 + * + * @param listener + */ + public void setOnPullRefreshListener(OnPullRefreshListener listener) { + mListener = listener; + } + + public void setHeaderViewBackgroundColor(int color) { + mHeadViewContainer.setBackgroundColor(color); + } + + /* + * 设置上拉加载更多的接口 + * + * @param onPushLoadMoreListener + */ + public void setOnPushLoadMoreListener( + OnPushLoadMoreListener onPushLoadMoreListener) { + this.mOnPushLoadMoreListener = onPushLoadMoreListener; + } + + /* + * Notify the widget that refresh state has changed. Do not call this when + * refresh is triggered by a swipe gesture. + * + * @param refreshing Whether or not the view should show refresh progress. + */ + public void setRefreshing(boolean refreshing) { + if (refreshing && mRefreshing != refreshing) { + // scale and show + mRefreshing = refreshing; + int endTarget = 0; + if (!mUsingCustomStart) { + endTarget = (int) (mSpinnerFinalOffset + mOriginalOffsetTop); + } else { + endTarget = (int) mSpinnerFinalOffset; + } + setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop, + true /* requires update */); + mNotify = false; + startScaleUpAnimation(mRefreshListener); + } else { + setRefreshing(refreshing, false /* notify */); + if (usingDefaultHeader) { + defaultProgressView.setOnDraw(false); + } + } + } + + private void startScaleUpAnimation(AnimationListener listener) { + mHeadViewContainer.setVisibility(View.VISIBLE); + mScaleAnimation = new Animation() { + @Override + public void applyTransformation(float interpolatedTime, + Transformation t) { + setAnimationProgress(interpolatedTime); + } + }; + mScaleAnimation.setDuration(mMediumAnimationDuration); + if (listener != null) { + mHeadViewContainer.setAnimationListener(listener); + } + mHeadViewContainer.clearAnimation(); + mHeadViewContainer.startAnimation(mScaleAnimation); + } + + private void setAnimationProgress(float progress) { + if (!usingDefaultHeader) { + progress = 1; + } + ViewCompat.setScaleX(mHeadViewContainer, progress); + ViewCompat.setScaleY(mHeadViewContainer, progress); + } + + private void setRefreshing(boolean refreshing, final boolean notify) { + if (mRefreshing != refreshing) { + mNotify = notify; + ensureTarget(); + mRefreshing = refreshing; + if (mRefreshing) { + animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, + mRefreshListener); + } else { + //startScaleDownAnimation(mRefreshListener); + animateOffsetToStartPosition(mCurrentTargetOffsetTop, mRefreshListener); + } + } + } + + private void startScaleDownAnimation(AnimationListener listener) { + mScaleDownAnimation = new Animation() { + @Override + public void applyTransformation(float interpolatedTime, + Transformation t) { + setAnimationProgress(1 - interpolatedTime); + } + }; + mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION); + mHeadViewContainer.setAnimationListener(listener); + mHeadViewContainer.clearAnimation(); + mHeadViewContainer.startAnimation(mScaleDownAnimation); + } + + public boolean isRefreshing() { + return mRefreshing; + } + + /** + * 确保mTarget不为空
+ * mTarget一般是可滑动的ScrollView,ListView,RecyclerView等 + */ + private void ensureTarget() { + if (mTarget == null) { + for (int i = 0; i < getChildCount(); i++) { + View child = getChildAt(i); + if (!child.equals(mHeadViewContainer) + && !child.equals(mFooterViewContainer)) { + mTarget = child; + break; + } + } + } + } + + /** + * Set the distance to trigger a sync in dips + * + * @param distance + */ + public void setDistanceToTriggerSync(int distance) { + mTotalDragDistance = distance; + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, + int bottom) { + final int width = getMeasuredWidth(); + final int height = getMeasuredHeight(); + if (getChildCount() == 0) { + return; + } + if (mTarget == null) { + ensureTarget(); + } + if (mTarget == null) { + return; + } + int distance = mCurrentTargetOffsetTop + mHeadViewContainer.getMeasuredHeight(); + if (!targetScrollWithLayout) { + // 判断标志位,如果目标View不跟随手指的滑动而滑动,将下拉偏移量设置为0 + distance = 0; + } + final View child = mTarget; + final int childLeft = getPaddingLeft(); + final int childTop = getPaddingTop() + distance - pushDistance;// 根据偏移量distance更新 + final int childWidth = width - getPaddingLeft() - getPaddingRight(); + final int childHeight = height - getPaddingTop() - getPaddingBottom(); + Log.d(LOG_TAG, "debug:onLayout childHeight = " + childHeight); + child.layout(childLeft, childTop, childLeft + childWidth, childTop + + childHeight);// 更新目标View的位置 + int headViewWidth = mHeadViewContainer.getMeasuredWidth(); + int headViewHeight = mHeadViewContainer.getMeasuredHeight(); + mHeadViewContainer.layout((width / 2 - headViewWidth / 2), + mCurrentTargetOffsetTop, (width / 2 + headViewWidth / 2), + mCurrentTargetOffsetTop + headViewHeight);// 更新头布局的位置 + int footViewWidth = mFooterViewContainer.getMeasuredWidth(); + int footViewHeight = mFooterViewContainer.getMeasuredHeight(); + mFooterViewContainer.layout((width / 2 - footViewWidth / 2), height + - pushDistance, (width / 2 + footViewWidth / 2), height + + footViewHeight - pushDistance); + } + + @Override + public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + if (mTarget == null) { + ensureTarget(); + } + if (mTarget == null) { + return; + } + mTarget.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth() + - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(getMeasuredHeight() + - getPaddingTop() - getPaddingBottom(), + MeasureSpec.EXACTLY)); + mHeadViewContainer.measure(MeasureSpec.makeMeasureSpec( + mHeaderViewWidth, MeasureSpec.EXACTLY), MeasureSpec + .makeMeasureSpec(3 * mHeaderViewHeight, MeasureSpec.EXACTLY)); + mFooterViewContainer.measure(MeasureSpec.makeMeasureSpec( + mFooterViewWidth, MeasureSpec.EXACTLY), MeasureSpec + .makeMeasureSpec(mFooterViewHeight, MeasureSpec.EXACTLY)); + if (!mUsingCustomStart && !mOriginalOffsetCalculated) { + mOriginalOffsetCalculated = true; + mCurrentTargetOffsetTop = mOriginalOffsetTop = -mHeadViewContainer + .getMeasuredHeight(); + updateListenerCallBack(); + } + mHeaderViewIndex = -1; + for (int index = 0; index < getChildCount(); index++) { + if (getChildAt(index) == mHeadViewContainer) { + mHeaderViewIndex = index; + break; + } + } + mFooterViewIndex = -1; + for (int index = 0; index < getChildCount(); index++) { + if (getChildAt(index) == mFooterViewContainer) { + mFooterViewIndex = index; + break; + } + } + } + + /** + * 判断目标View是否滑动到顶部-还能否继续滑动 + * + * @return + */ + public boolean isChildScrollToTop() { + if (Build.VERSION.SDK_INT < 14) { + if (mTarget instanceof AbsListView) { + final AbsListView absListView = (AbsListView) mTarget; + return !(absListView.getChildCount() > 0 && (absListView + .getFirstVisiblePosition() > 0 || absListView + .getChildAt(0).getTop() < absListView.getPaddingTop())); + } else { + return !(mTarget.getScrollY() > 0); + } + } else { + return !ViewCompat.canScrollVertically(mTarget, -1); + } + } + + /** + * 是否滑动到底部 + * + * @return + */ + public boolean isChildScrollToBottom() { + if (isChildScrollToTop()) { + return false; + } + if (mTarget instanceof RecyclerView) { + RecyclerView recyclerView = (RecyclerView) mTarget; + LayoutManager layoutManager = recyclerView.getLayoutManager(); + int count = recyclerView.getAdapter().getItemCount(); + if (layoutManager instanceof LinearLayoutManager && count > 0) { + LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; + if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == count - 1) { + return true; + } + } else if (layoutManager instanceof StaggeredGridLayoutManager) { + StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager; + int[] lastItems = new int[2]; + staggeredGridLayoutManager + .findLastCompletelyVisibleItemPositions(lastItems); + int lastItem = Math.max(lastItems[0], lastItems[1]); + if (lastItem == count - 1) { + return true; + } + } + return false; + } else if (mTarget instanceof AbsListView) { + final AbsListView absListView = (AbsListView) mTarget; + int count = absListView.getAdapter().getCount(); + int fristPos = absListView.getFirstVisiblePosition(); + if (fristPos == 0 + && absListView.getChildAt(0).getTop() >= absListView + .getPaddingTop()) { + return false; + } + int lastPos = absListView.getLastVisiblePosition(); + if (lastPos > 0 && count > 0 && lastPos == count - 1) { + return true; + } + return false; + } else if (mTarget instanceof ScrollView) { + ScrollView scrollView = (ScrollView) mTarget; + View view = (View) scrollView + .getChildAt(scrollView.getChildCount() - 1); + if (view != null) { + int diff = (view.getBottom() - (scrollView.getHeight() + scrollView + .getScrollY())); + if (diff == 0) { + return true; + } + } + } else if (mTarget instanceof NestedScrollView) { + NestedScrollView nestedScrollView = (NestedScrollView) mTarget; + View view = (View) nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1); + if (view != null) { + int diff = (view.getBottom() - (nestedScrollView.getHeight() + nestedScrollView.getScrollY())); + if (diff == 0) { + return true; + } + } + } + return false; + } + + /** + * 主要判断是否应该拦截子View的事件
+ * 如果拦截,则交给自己的OnTouchEvent处理
+ * 否者,交给子View处理
+ */ + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + ensureTarget(); + + final int action = MotionEventCompat.getActionMasked(ev); + + if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { + mReturningToStart = false; + } + if (!isEnabled() || mReturningToStart || mRefreshing || mLoadMore + || (!isChildScrollToTop() && !isChildScrollToBottom())) { + // 如果子View可以滑动,不拦截事件,交给子View处理-下拉刷新 + // 或者子View没有滑动到底部不拦截事件-上拉加载更多 + return false; + } + + // 下拉刷新判断 + switch (action) { + case MotionEvent.ACTION_DOWN: + setTargetOffsetTopAndBottom( + mOriginalOffsetTop - mHeadViewContainer.getTop(), true);// 恢复HeaderView的初始位置 + mActivePointerId = MotionEventCompat.getPointerId(ev, 0); + mIsBeingDragged = false; + final float initialMotionY = getMotionEventY(ev, mActivePointerId); + if (initialMotionY == -1) { + return false; + } + mInitialMotionY = initialMotionY;// 记录按下的位置 + + case MotionEvent.ACTION_MOVE: + if (mActivePointerId == INVALID_POINTER) { + Log.e(LOG_TAG, + "Got ACTION_MOVE event but don't have an active pointer id."); + return false; + } + + final float y = getMotionEventY(ev, mActivePointerId); + if (y == -1) { + return false; + } + float yDiff = 0; + if (isChildScrollToBottom()) { + yDiff = mInitialMotionY - y;// 计算上拉距离 + if (yDiff > mTouchSlop && !mIsBeingDragged) {// 判断是否下拉的距离足够 + mIsBeingDragged = true;// 正在上拉 + } + } else { + yDiff = y - mInitialMotionY;// 计算下拉距离 + if (yDiff > mTouchSlop && !mIsBeingDragged) {// 判断是否下拉的距离足够 + mIsBeingDragged = true;// 正在下拉 + } + } + break; + + case MotionEventCompat.ACTION_POINTER_UP: + onSecondaryPointerUp(ev); + break; + + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + mIsBeingDragged = false; + mActivePointerId = INVALID_POINTER; + break; + } + + return mIsBeingDragged;// 如果正在拖动,则拦截子View的事件 + } + + private float getMotionEventY(MotionEvent ev, int activePointerId) { + final int index = MotionEventCompat.findPointerIndex(ev, + activePointerId); + if (index < 0) { + return -1; + } + return MotionEventCompat.getY(ev, index); + } + + @Override + public void requestDisallowInterceptTouchEvent(boolean b) { + // Nope. + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + final int action = MotionEventCompat.getActionMasked(ev); + + if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { + mReturningToStart = false; + } + if (!isEnabled() || mReturningToStart + || (!isChildScrollToTop() && !isChildScrollToBottom())) { + // 如果子View可以滑动,不拦截事件,交给子View处理 + return false; + } + + if (isChildScrollToBottom()) {// 上拉加载更多 + return handlerPushTouchEvent(ev, action); + } else {// 下拉刷新 + return handlerPullTouchEvent(ev, action); + } + } + + + //下拉刷新 + private boolean handlerPullTouchEvent(MotionEvent ev, int action) { + switch (action) { + case MotionEvent.ACTION_DOWN: + mActivePointerId = MotionEventCompat.getPointerId(ev, 0); + mIsBeingDragged = false; + break; + + case MotionEvent.ACTION_MOVE: { + final int pointerIndex = MotionEventCompat.findPointerIndex(ev, + mActivePointerId); + if (pointerIndex < 0) { + Log.e(LOG_TAG, + "Got ACTION_MOVE event but have an invalid active pointer id."); + return false; + } + + final float y = MotionEventCompat.getY(ev, pointerIndex); + final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; + if (mIsBeingDragged) { + float originalDragPercent = overscrollTop / mTotalDragDistance; + if (originalDragPercent < 0) { + return false; + } + float dragPercent = Math.min(1f, Math.abs(originalDragPercent)); + float extraOS = Math.abs(overscrollTop) - mTotalDragDistance; + float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset + - mOriginalOffsetTop : mSpinnerFinalOffset; + float tensionSlingshotPercent = Math.max(0, + Math.min(extraOS, slingshotDist * 2) / slingshotDist); + float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math + .pow((tensionSlingshotPercent / 4), 2)) * 2f; + float extraMove = (slingshotDist) * tensionPercent * 2; + + int targetY = mOriginalOffsetTop + + (int) ((slingshotDist * dragPercent) + extraMove); + if (mHeadViewContainer.getVisibility() != View.VISIBLE) { + mHeadViewContainer.setVisibility(View.VISIBLE); + } + if (!mScale) { + ViewCompat.setScaleX(mHeadViewContainer, 1f); + ViewCompat.setScaleY(mHeadViewContainer, 1f); + } + if (usingDefaultHeader) { + float alpha = overscrollTop / mTotalDragDistance; + if (alpha >= 1.0f) { + alpha = 1.0f; + } + ViewCompat.setScaleX(defaultProgressView, alpha); + ViewCompat.setScaleY(defaultProgressView, alpha); + ViewCompat.setAlpha(defaultProgressView, alpha); + } + if (overscrollTop < mTotalDragDistance) { + if (mScale) { + setAnimationProgress(overscrollTop / mTotalDragDistance); + } + if (mListener != null) { + mListener.onPullEnable(false); + } + } else { + if (mListener != null) { + mListener.onPullEnable(true); + } + } + setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop, + true); + } + break; + } + case MotionEventCompat.ACTION_POINTER_DOWN: { + final int index = MotionEventCompat.getActionIndex(ev); + mActivePointerId = MotionEventCompat.getPointerId(ev, index); + break; + } + + case MotionEventCompat.ACTION_POINTER_UP: + onSecondaryPointerUp(ev); + break; + + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: { + if (mActivePointerId == INVALID_POINTER) { + if (action == MotionEvent.ACTION_UP) { + Log.e(LOG_TAG, + "Got ACTION_UP event but don't have an active pointer id."); + } + return false; + } + final int pointerIndex = MotionEventCompat.findPointerIndex(ev, + mActivePointerId); + final float y = MotionEventCompat.getY(ev, pointerIndex); + final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; + mIsBeingDragged = false; + if (overscrollTop > mTotalDragDistance) { + setRefreshing(true, true /* notify */); + } else { + mRefreshing = false; + AnimationListener listener = null; + if (!mScale) { + listener = new AnimationListener() { + + @Override + public void onAnimationStart(Animation animation) { + } + + @Override + public void onAnimationEnd(Animation animation) { + if (!mScale) { + startScaleDownAnimation(null); + } + } + + @Override + public void onAnimationRepeat(Animation animation) { + } + + }; + } + animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener); + } + mActivePointerId = INVALID_POINTER; + return false; + } + } + + return true; + } + + /** + * 处理上拉加载更多的Touch事件 + * + * @param ev + * @param action + * @return + */ + private boolean handlerPushTouchEvent(MotionEvent ev, int action) { + switch (action) { + case MotionEvent.ACTION_DOWN: + mActivePointerId = MotionEventCompat.getPointerId(ev, 0); + mIsBeingDragged = false; + Log.d(LOG_TAG, "debug:onTouchEvent ACTION_DOWN"); + break; + case MotionEvent.ACTION_MOVE: { + final int pointerIndex = MotionEventCompat.findPointerIndex(ev, + mActivePointerId); + if (pointerIndex < 0) { + Log.e(LOG_TAG, + "Got ACTION_MOVE event but have an invalid active pointer id."); + return false; + } + final float y = MotionEventCompat.getY(ev, pointerIndex); + final float overscrollBottom = (mInitialMotionY - y) * DRAG_RATE; + if (mIsBeingDragged) { + pushDistance = (int) overscrollBottom; + updateFooterViewPosition(); + if (mOnPushLoadMoreListener != null) { + mOnPushLoadMoreListener + .onPushEnable(pushDistance >= mFooterViewHeight); + } + } + break; + } + case MotionEventCompat.ACTION_POINTER_DOWN: { + final int index = MotionEventCompat.getActionIndex(ev); + mActivePointerId = MotionEventCompat.getPointerId(ev, index); + break; + } + + case MotionEventCompat.ACTION_POINTER_UP: + onSecondaryPointerUp(ev); + break; + + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: { + if (mActivePointerId == INVALID_POINTER) { + if (action == MotionEvent.ACTION_UP) { + Log.e(LOG_TAG, + "Got ACTION_UP event but don't have an active pointer id."); + } + return false; + } + final int pointerIndex = MotionEventCompat.findPointerIndex(ev, + mActivePointerId); + final float y = MotionEventCompat.getY(ev, pointerIndex); + final float overscrollBottom = (mInitialMotionY - y) * DRAG_RATE;// 松手是下拉的距离 + mIsBeingDragged = false; + mActivePointerId = INVALID_POINTER; + if (overscrollBottom < mFooterViewHeight + || mOnPushLoadMoreListener == null) {// 直接取消 + pushDistance = 0; + } else {// 下拉到mFooterViewHeight + pushDistance = mFooterViewHeight; + } + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { + updateFooterViewPosition(); + if (pushDistance == mFooterViewHeight + && mOnPushLoadMoreListener != null) { + mLoadMore = true; + mOnPushLoadMoreListener.onLoadMore(); + } + } else { + animatorFooterToBottom((int) overscrollBottom, pushDistance); + } + return false; + } + } + return true; + } + + /** + * 松手之后,使用动画将Footer从距离start变化到end + * + * @param start + * @param end + */ + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + private void animatorFooterToBottom(int start, final int end) { + ValueAnimator valueAnimator = ValueAnimator.ofInt(start, end); + valueAnimator.setDuration(150); + valueAnimator.addUpdateListener(new AnimatorUpdateListener() { + + @Override + public void onAnimationUpdate(ValueAnimator valueAnimator) { + // update + pushDistance = (Integer) valueAnimator.getAnimatedValue(); + updateFooterViewPosition(); + } + }); + valueAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + if (end > 0 && mOnPushLoadMoreListener != null) { + // start loading more + mLoadMore = true; + mOnPushLoadMoreListener.onLoadMore(); + } else { + resetTargetLayout(); + mLoadMore = false; + } + } + }); + valueAnimator.setInterpolator(mDecelerateInterpolator); + valueAnimator.start(); + } + + /** + * 设置停止加载 + * + * @param loadMore + */ + public void setLoadMore(boolean loadMore) { + if (!loadMore && mLoadMore) {// 停止加载 + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { + mLoadMore = false; + pushDistance = 0; + updateFooterViewPosition(); + } else { + animatorFooterToBottom(mFooterViewHeight, 0); + } + } + } + + private void animateOffsetToCorrectPosition(int from, + AnimationListener listener) { + mFrom = from; + mAnimateToCorrectPosition.reset(); + mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION); + mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator); + if (listener != null) { + mHeadViewContainer.setAnimationListener(listener); + } + mHeadViewContainer.clearAnimation(); + mHeadViewContainer.startAnimation(mAnimateToCorrectPosition); + } + + private void animateOffsetToStartPosition(int from, + AnimationListener listener) { + if (mScale) { + startScaleDownReturnToStartAnimation(from, listener); + } else { + mFrom = from; + mAnimateToStartPosition.reset(); + mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION); + mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator); + if (listener != null) { + mHeadViewContainer.setAnimationListener(listener); + } + mHeadViewContainer.clearAnimation(); + mHeadViewContainer.startAnimation(mAnimateToStartPosition); + } + resetTargetLayoutDelay(ANIMATE_TO_START_DURATION); + } + + /** + * 重置Target位置 + * + * @param delay + */ + public void resetTargetLayoutDelay(int delay) { + new Handler().postDelayed(new Runnable() { + + @Override + public void run() { + resetTargetLayout(); + } + }, delay); + } + + /** + * 重置Target的位置 + */ + public void resetTargetLayout() { + final int width = getMeasuredWidth(); + final int height = getMeasuredHeight(); + final View child = mTarget; + final int childLeft = getPaddingLeft(); + final int childTop = getPaddingTop(); + final int childWidth = child.getWidth() - getPaddingLeft() + - getPaddingRight(); + final int childHeight = child.getHeight() - getPaddingTop() + - getPaddingBottom(); + child.layout(childLeft, childTop, childLeft + childWidth, childTop + + childHeight); + + int headViewWidth = mHeadViewContainer.getMeasuredWidth(); + int headViewHeight = mHeadViewContainer.getMeasuredHeight(); + mHeadViewContainer.layout((width / 2 - headViewWidth / 2), + -headViewHeight, (width / 2 + headViewWidth / 2), 0);// 更新头布局的位置 + int footViewWidth = mFooterViewContainer.getMeasuredWidth(); + int footViewHeight = mFooterViewContainer.getMeasuredHeight(); + mFooterViewContainer.layout((width / 2 - footViewWidth / 2), height, + (width / 2 + footViewWidth / 2), height + footViewHeight); + } + + private final Animation mAnimateToCorrectPosition = new Animation() { + @Override + public void applyTransformation(float interpolatedTime, Transformation t) { + int targetTop = 0; + int endTarget = 0; + if (!mUsingCustomStart) { + endTarget = (int) (mSpinnerFinalOffset - Math + .abs(mOriginalOffsetTop)); + } else { + endTarget = (int) mSpinnerFinalOffset; + } + targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime)); + int offset = targetTop - mHeadViewContainer.getTop(); + setTargetOffsetTopAndBottom(offset, false /* requires update */); + } + + @Override + public void setAnimationListener(AnimationListener listener) { + super.setAnimationListener(listener); + } + }; + + private void moveToStart(float interpolatedTime) { + int targetTop = 0; + targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime)); + int offset = targetTop - mHeadViewContainer.getTop(); + setTargetOffsetTopAndBottom(offset, false /* requires update */); + } + + private final Animation mAnimateToStartPosition = new Animation() { + @Override + public void applyTransformation(float interpolatedTime, Transformation t) { + moveToStart(interpolatedTime); + } + }; + + private void startScaleDownReturnToStartAnimation(int from, + AnimationListener listener) { + mFrom = from; + mStartingScale = ViewCompat.getScaleX(mHeadViewContainer); + mScaleDownToStartAnimation = new Animation() { + @Override + public void applyTransformation(float interpolatedTime, + Transformation t) { + float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime)); + setAnimationProgress(targetScale); + moveToStart(interpolatedTime); + } + }; + mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION); + if (listener != null) { + mHeadViewContainer.setAnimationListener(listener); + } + mHeadViewContainer.clearAnimation(); + mHeadViewContainer.startAnimation(mScaleDownToStartAnimation); + } + + private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) { + mHeadViewContainer.bringToFront(); + mHeadViewContainer.offsetTopAndBottom(offset); + mCurrentTargetOffsetTop = mHeadViewContainer.getTop(); + if (requiresUpdate && Build.VERSION.SDK_INT < 11) { + invalidate(); + } + updateListenerCallBack(); + } + + /** + * 修改底部布局的位置-敏感pushDistance + */ + private void updateFooterViewPosition() { + mFooterViewContainer.setVisibility(View.VISIBLE); + mFooterViewContainer.bringToFront(); + //针对4.4及之前版本的兼容 + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { + mFooterViewContainer.getParent().requestLayout(); + } + mFooterViewContainer.offsetTopAndBottom(-pushDistance); + updatePushDistanceListener(); + } + + private void updatePushDistanceListener() { + if (mOnPushLoadMoreListener != null) { + mOnPushLoadMoreListener.onPushDistance(pushDistance); + } + } + + private void onSecondaryPointerUp(MotionEvent ev) { + final int pointerIndex = MotionEventCompat.getActionIndex(ev); + final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); + if (pointerId == mActivePointerId) { + final int newPointerIndex = pointerIndex == 0 ? 1 : 0; + mActivePointerId = MotionEventCompat.getPointerId(ev, + newPointerIndex); + } + } + + /** + * @Description 下拉刷新布局头部的容器 + */ + private class HeadViewContainer extends RelativeLayout { + + private AnimationListener mListener; + + public HeadViewContainer(Context context) { + super(context); + } + + public void setAnimationListener(AnimationListener listener) { + mListener = listener; + } + + @Override + public void onAnimationStart() { + super.onAnimationStart(); + if (mListener != null) { + mListener.onAnimationStart(getAnimation()); + } + } + + @Override + public void onAnimationEnd() { + super.onAnimationEnd(); + if (mListener != null) { + mListener.onAnimationEnd(getAnimation()); + } + } + } + + /** + * 判断子View是否跟随手指的滑动而滑动,默认跟随 + * + * @return + */ + public boolean isTargetScrollWithLayout() { + return targetScrollWithLayout; + } + + /** + * 设置子View是否跟谁手指的滑动而滑动 + * + * @param targetScrollWithLayout + */ + public void setTargetScrollWithLayout(boolean targetScrollWithLayout) { + this.targetScrollWithLayout = targetScrollWithLayout; + } + + /** + * 下拉刷新回调 + */ + public interface OnPullRefreshListener { + public void onRefresh(); + + public void onPullDistance(int distance); + + public void onPullEnable(boolean enable); + } + + /** + * 上拉加载更多 + */ + public interface OnPushLoadMoreListener { + public void onLoadMore(); + + public void onPushDistance(int distance); + + public void onPushEnable(boolean enable); + } + + /** + * Adapter + */ + public class OnPullRefreshListenerAdapter implements OnPullRefreshListener { + + @Override + public void onRefresh() { + + } + + @Override + public void onPullDistance(int distance) { + + } + + @Override + public void onPullEnable(boolean enable) { + + } + + } + + public class OnPushLoadMoreListenerAdapter implements + OnPushLoadMoreListener { + + @Override + public void onLoadMore() { + + } + + @Override + public void onPushDistance(int distance) { + + } + + @Override + public void onPushEnable(boolean enable) { + + } + + } + + /** + * 设置默认下拉刷新进度条的颜色 + * + * @param color + */ + public void setDefaultCircleProgressColor(int color) { + if (usingDefaultHeader) { + defaultProgressView.setProgressColor(color); + } + } + + /** + * 设置圆圈的背景色 + * + * @param color + */ + public void setDefaultCircleBackgroundColor(int color) { + if (usingDefaultHeader) { + defaultProgressView.setCircleBackgroundColor(color); + } + } + + public void setDefaultCircleShadowColor(int color) { + if (usingDefaultHeader) { + defaultProgressView.setShadowColor(color); + } + } + + /** + * 默认的下拉刷新样式 + */ + public class CircleProgressView extends View implements Runnable { + + private static final int PEROID = 16;// 绘制周期 + private Paint progressPaint; + private Paint bgPaint; + private int width;// view的高度 + private int height;// view的宽度 + + private boolean isOnDraw = false; + private boolean isRunning = false; + private int startAngle = 0; + private int speed = 8; + private RectF ovalRect = null; + private RectF bgRect = null; + private int swipeAngle; + private int progressColor = 0xffcccccc; + private int circleBackgroundColor = 0xffffffff; + private int shadowColor = 0xff999999; + + public CircleProgressView(Context context) { + super(context); + } + + public CircleProgressView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public CircleProgressView(Context context, AttributeSet attrs, + int defStyleAttr) { + super(context, attrs, defStyleAttr); + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + canvas.drawArc(getBgRect(), 0, 360, false, createBgPaint()); + int index = startAngle / 360; + if (index % 2 == 0) { + swipeAngle = (startAngle % 720) / 2; + } else { + swipeAngle = 360 - (startAngle % 720) / 2; + } + canvas.drawArc(getOvalRect(), startAngle, swipeAngle, false, + createPaint()); + } + + private RectF getBgRect() { + width = getWidth(); + height = getHeight(); + if (bgRect == null) { + int offset = (int) (density * 2); + bgRect = new RectF(offset, offset, width - offset, height + - offset); + } + return bgRect; + } + + private RectF getOvalRect() { + width = getWidth(); + height = getHeight(); + if (ovalRect == null) { + int offset = (int) (density * 8); + ovalRect = new RectF(offset, offset, width - offset, height + - offset); + } + return ovalRect; + } + + public void setProgressColor(int progressColor) { + this.progressColor = progressColor; + } + + public void setCircleBackgroundColor(int circleBackgroundColor) { + this.circleBackgroundColor = circleBackgroundColor; + } + + public void setShadowColor(int shadowColor) { + this.shadowColor = shadowColor; + } + + /** + * 根据画笔的颜色,创建画笔 + * + * @return + */ + private Paint createPaint() { + if (this.progressPaint == null) { + progressPaint = new Paint(); + progressPaint.setStrokeWidth((int) (density * 3)); + progressPaint.setStyle(Paint.Style.STROKE); + progressPaint.setAntiAlias(true); + } + progressPaint.setColor(progressColor); + return progressPaint; + } + + private Paint createBgPaint() { + if (this.bgPaint == null) { + bgPaint = new Paint(); + bgPaint.setColor(circleBackgroundColor); + bgPaint.setStyle(Paint.Style.FILL); + bgPaint.setAntiAlias(true); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + this.setLayerType(LAYER_TYPE_SOFTWARE, bgPaint); + } + bgPaint.setShadowLayer(4.0f, 0.0f, 2.0f, shadowColor); + } + return bgPaint; + } + + public void setPullDistance(int distance) { + this.startAngle = distance * 2; + postInvalidate(); + } + + @Override + public void run() { + while (isOnDraw) { + isRunning = true; + long startTime = System.currentTimeMillis(); + startAngle += speed; + postInvalidate(); + long time = System.currentTimeMillis() - startTime; + if (time < PEROID) { + try { + Thread.sleep(PEROID - time); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + public void setOnDraw(boolean isOnDraw) { + this.isOnDraw = isOnDraw; + } + + public void setSpeed(int speed) { + this.speed = speed; + } + + public boolean isRunning() { + return isRunning; + } + + @Override + public void onWindowFocusChanged(boolean hasWindowFocus) { + super.onWindowFocusChanged(hasWindowFocus); + } + + @Override + protected void onDetachedFromWindow() { + isOnDraw = false; + super.onDetachedFromWindow(); + } + + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/SwitchView.java b/src/main/java/com/gizwits/opensource/appkit/view/SwitchView.java new file mode 100644 index 0000000..d9f4ba7 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/SwitchView.java @@ -0,0 +1,473 @@ +package com.gizwits.opensource.appkit.view; + + +/** + * Created by qiaoning on 2017/8/16. + */ + + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.RadialGradient; +import android.graphics.RectF; +import android.graphics.Shader; +import android.os.Build; +import android.os.Parcel; +import android.os.Parcelable; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.MotionEvent; +import android.view.View; +import android.view.animation.AccelerateInterpolator; + +import com.gizwits.opensource.appkit.R; + + +public class SwitchView extends View { + + + private final int DEFAULT_COLOR_PRIMARY = 0xFF4BD763; + private final int DEFAULT_COLOR_PRIMARY_DARK = 0xFF3AC652; + private final float RATIO_ASPECT = 0.68f; + private final float ANIMATION_SPEED = 0.1f; // (0,1] + private static final int STATE_SWITCH_ON = 4; // you change value you die + private static final int STATE_SWITCH_ON2 = 3; + private static final int STATE_SWITCH_OFF2 = 2; + private static final int STATE_SWITCH_OFF = 1; + + private final AccelerateInterpolator interpolator = new AccelerateInterpolator(2); + private final Paint paint = new Paint(); + private final Path sPath = new Path(); + private final Path bPath = new Path(); + private final RectF bRectF = new RectF(); + private float sAnim, bAnim; + private RadialGradient shadowGradient; + + private int state; + private int lastState; + private boolean isCanVisibleDrawing = false; + private OnClickListener mOnClickListener; + private int colorPrimary; + private int colorPrimaryDark; + private boolean hasShadow; + private boolean isOpened; + + private int mWidth, mHeight; + private int actuallyDrawingAreaLeft; + private int actuallyDrawingAreaRight; + private int actuallyDrawingAreaTop; + private int actuallyDrawingAreaBottom; + + private float sWidth, sHeight; + private float sLeft, sTop, sRight, sBottom; + private float sCenterX, sCenterY; + private float sScale; + + private float bOffset; + private float bRadius, bStrokeWidth; + private float bWidth; + private float bLeft, bTop, bRight, bBottom; + private float bOnLeftX, bOn2LeftX, bOff2LeftX, bOffLeftX; + + private float shadowReservedHeight; + + public SwitchView(Context context) { + this(context, null); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public SwitchView(Context context, AttributeSet attrs) { + super(context, attrs); + setLayerType(LAYER_TYPE_SOFTWARE, null); + + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwitchView); + colorPrimary = a.getColor(R.styleable.SwitchView_primaryColor, DEFAULT_COLOR_PRIMARY); + colorPrimaryDark = a.getColor(R.styleable.SwitchView_primaryColorDark, DEFAULT_COLOR_PRIMARY_DARK); + hasShadow = a.getBoolean(R.styleable.SwitchView_hasShadow, true); + isOpened = a.getBoolean(R.styleable.SwitchView_isOpened, false); + state = isOpened ? STATE_SWITCH_ON : STATE_SWITCH_OFF; + lastState = state; + a.recycle(); + + if (colorPrimary == DEFAULT_COLOR_PRIMARY && colorPrimaryDark == DEFAULT_COLOR_PRIMARY_DARK) { + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + TypedValue primaryColorTypedValue = new TypedValue(); + context.getTheme().resolveAttribute(android.R.attr.colorPrimary, primaryColorTypedValue, true); + if (primaryColorTypedValue.data > 0) colorPrimary = primaryColorTypedValue.data; + TypedValue primaryColorDarkTypedValue = new TypedValue(); + context.getTheme().resolveAttribute(android.R.attr.colorPrimaryDark, primaryColorDarkTypedValue, true); + if (primaryColorDarkTypedValue.data > 0) + colorPrimaryDark = primaryColorDarkTypedValue.data; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public void setColor(int newColorPrimary, int newColorPrimaryDark) { + colorPrimary = newColorPrimary; + colorPrimaryDark = newColorPrimaryDark; + invalidate(); + } + + public void setShadow(boolean shadow) { + hasShadow = shadow; + invalidate(); + } + + public boolean isOpened() { + return isOpened; + } + + public void setOpened(boolean isOpened) { + int wishState = isOpened ? STATE_SWITCH_ON : STATE_SWITCH_OFF; + if (wishState == state) { + return; + } + refreshState(wishState); + } + + public void toggleSwitch(boolean isOpened) { + int wishState = isOpened ? STATE_SWITCH_ON : STATE_SWITCH_OFF; + if (wishState == state) { + return; + } + if ((wishState == STATE_SWITCH_ON && (state == STATE_SWITCH_OFF || state == STATE_SWITCH_OFF2)) + || (wishState == STATE_SWITCH_OFF && (state == STATE_SWITCH_ON || state == STATE_SWITCH_ON2))) { + sAnim = 1; + } + bAnim = 1; + refreshState(wishState); + } + + private void refreshState(int newState) { + if (!isOpened && newState == STATE_SWITCH_ON) { + isOpened = true; + } else if (isOpened && newState == STATE_SWITCH_OFF) { + isOpened = false; + } + lastState = state; + state = newState; + postInvalidate(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int widthSize = MeasureSpec.getSize(widthMeasureSpec); + int widthMode = MeasureSpec.getMode(widthMeasureSpec); + int resultWidth; + if (widthMode == MeasureSpec.EXACTLY) { + resultWidth = widthSize; + } else { + resultWidth = (int) (56 * getResources().getDisplayMetrics().density + 0.5f) + + getPaddingLeft() + getPaddingRight(); + if (widthMode == MeasureSpec.AT_MOST) { + resultWidth = Math.min(resultWidth, widthSize); + } + } + + int heightSize = MeasureSpec.getSize(heightMeasureSpec); + int heightMode = MeasureSpec.getMode(heightMeasureSpec); + int resultHeight; + if (heightMode == MeasureSpec.EXACTLY) { + resultHeight = heightSize; + } else { + int selfExpectedResultHeight = (int) (resultWidth * RATIO_ASPECT) + getPaddingTop() + getPaddingBottom(); + resultHeight = selfExpectedResultHeight; + if (heightMode == MeasureSpec.AT_MOST) { + resultHeight = Math.min(resultHeight, heightSize); + } + } + setMeasuredDimension(resultWidth, resultHeight); + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + mWidth = w; + mHeight = h; + isCanVisibleDrawing = mWidth > getPaddingLeft() + getPaddingRight() && mHeight > getPaddingTop() + getPaddingBottom(); + + if (isCanVisibleDrawing) { + int actuallyDrawingAreaWidth = mWidth - getPaddingLeft() - getPaddingRight(); + int actuallyDrawingAreaHeight = mHeight - getPaddingTop() - getPaddingBottom(); + + if (actuallyDrawingAreaWidth * RATIO_ASPECT < actuallyDrawingAreaHeight) { + actuallyDrawingAreaLeft = getPaddingLeft(); + actuallyDrawingAreaRight = mWidth - getPaddingRight(); + int heightExtraSize = (int) (actuallyDrawingAreaHeight - actuallyDrawingAreaWidth * RATIO_ASPECT); + actuallyDrawingAreaTop = getPaddingTop() + heightExtraSize / 2; + actuallyDrawingAreaBottom = getHeight() - getPaddingBottom() - heightExtraSize / 2; + } else { + int widthExtraSize = (int) (actuallyDrawingAreaWidth - actuallyDrawingAreaHeight / RATIO_ASPECT); + actuallyDrawingAreaLeft = getPaddingLeft() + widthExtraSize / 2; + actuallyDrawingAreaRight = getWidth() - getPaddingRight() - widthExtraSize / 2; + actuallyDrawingAreaTop = getPaddingTop(); + actuallyDrawingAreaBottom = getHeight() - getPaddingBottom(); + } + + shadowReservedHeight = (int) ((actuallyDrawingAreaBottom - actuallyDrawingAreaTop) * 0.09f); + sLeft = actuallyDrawingAreaLeft; + sTop = actuallyDrawingAreaTop + shadowReservedHeight; + sRight = actuallyDrawingAreaRight; + sBottom = actuallyDrawingAreaBottom - shadowReservedHeight; + + sWidth = sRight - sLeft; + sHeight = sBottom - sTop; + sCenterX = (sRight + sLeft) / 2; + sCenterY = (sBottom + sTop) / 2; + + bLeft = sLeft; + bTop = sTop; + bBottom = sBottom; + bWidth = sBottom - sTop; + bRight = sLeft + bWidth; + final float halfHeightOfS = bWidth / 2; // OfB + bRadius = halfHeightOfS * 0.95f; + bOffset = bRadius * 0.2f; // offset of switching + bStrokeWidth = (halfHeightOfS - bRadius) * 2; + bOnLeftX = sRight - bWidth; + bOn2LeftX = bOnLeftX - bOffset; + bOffLeftX = sLeft; + bOff2LeftX = bOffLeftX + bOffset; + sScale = 1 - bStrokeWidth / sHeight; + + sPath.reset(); + RectF sRectF = new RectF(); + sRectF.top = sTop; + sRectF.bottom = sBottom; + sRectF.left = sLeft; + sRectF.right = sLeft + sHeight; + sPath.arcTo(sRectF, 90, 180); + sRectF.left = sRight - sHeight; + sRectF.right = sRight; + sPath.arcTo(sRectF, 270, 180); + sPath.close(); + + bRectF.left = bLeft; + bRectF.right = bRight; + bRectF.top = bTop + bStrokeWidth / 2; + bRectF.bottom = bBottom - bStrokeWidth / 2; + float bCenterX = (bRight + bLeft) / 2; + float bCenterY = (bBottom + bTop) / 2; + + shadowGradient = new RadialGradient(bCenterX, bCenterY, bRadius, 0xff000000, 0x00000000, Shader.TileMode.CLAMP); + } + } + + private void calcBPath(float percent) { + bPath.reset(); + bRectF.left = bLeft + bStrokeWidth / 2; + bRectF.right = bRight - bStrokeWidth / 2; + bPath.arcTo(bRectF, 90, 180); + bRectF.left = bLeft + percent * bOffset + bStrokeWidth / 2; + bRectF.right = bRight + percent * bOffset - bStrokeWidth / 2; + bPath.arcTo(bRectF, 270, 180); + bPath.close(); + } + + private float calcBTranslate(float percent) { + float result = 0; + switch (state - lastState) { + case 1: + if (state == STATE_SWITCH_OFF2) { + result = bOffLeftX; // off -> off2 + } else if (state == STATE_SWITCH_ON) { + result = bOnLeftX - (bOnLeftX - bOn2LeftX) * percent; // on2 -> on + } + break; + case 2: + if (state == STATE_SWITCH_ON) { + result = bOnLeftX - (bOnLeftX - bOffLeftX) * percent; // off2 -> on + } else if (state == STATE_SWITCH_ON) { + result = bOn2LeftX - (bOn2LeftX - bOffLeftX) * percent; // off -> on2 + } + break; + case 3: + result = bOnLeftX - (bOnLeftX - bOffLeftX) * percent; // off -> on + break; + case -1: + if (state == STATE_SWITCH_ON2) { + result = bOn2LeftX + (bOnLeftX - bOn2LeftX) * percent; // on -> on2 + } else if (state == STATE_SWITCH_OFF) { + result = bOffLeftX; // off2 -> off + } + break; + case -2: + if (state == STATE_SWITCH_OFF) { + result = bOffLeftX + (bOn2LeftX - bOffLeftX) * percent; // on2 -> off + } else if (state == STATE_SWITCH_OFF2) { + result = bOff2LeftX + (bOnLeftX - bOff2LeftX) * percent; // on -> off2 + } + break; + case -3: + result = bOffLeftX + (bOnLeftX - bOffLeftX) * percent; // on -> off + break; + default: // init + case 0: + if (state == STATE_SWITCH_OFF) { + result = bOffLeftX; // off -> off + } else if (state == STATE_SWITCH_ON) { + result = bOnLeftX; // on -> on + } + break; + } + return result - bOffLeftX; + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (!isCanVisibleDrawing) return; + + paint.setAntiAlias(true); + final boolean isOn = (state == STATE_SWITCH_ON || state == STATE_SWITCH_ON2); + // Draw background + paint.setStyle(Paint.Style.FILL); + paint.setColor(isOn ? colorPrimary : 0xffE3E3E3); + canvas.drawPath(sPath, paint); + + sAnim = sAnim - ANIMATION_SPEED > 0 ? sAnim - ANIMATION_SPEED : 0; + bAnim = bAnim - ANIMATION_SPEED > 0 ? bAnim - ANIMATION_SPEED : 0; + + final float dsAnim = interpolator.getInterpolation(sAnim); + final float dbAnim = interpolator.getInterpolation(bAnim); + // Draw background animation + final float scale = sScale * (isOn ? dsAnim : 1 - dsAnim); + final float scaleOffset = (sRight - sCenterX - bRadius) * (isOn ? 1 - dsAnim : dsAnim); + canvas.save(); + canvas.scale(scale, scale, sCenterX + scaleOffset, sCenterY); + paint.setColor(0xFFFFFFFF); + canvas.drawPath(sPath, paint); + canvas.restore(); + // To prepare center bar path + canvas.save(); + canvas.translate(calcBTranslate(dbAnim), shadowReservedHeight); + final boolean isState2 = (state == STATE_SWITCH_ON2 || state == STATE_SWITCH_OFF2); + calcBPath(isState2 ? 1 - dbAnim : dbAnim); + // Use center bar path to draw shadow + if (hasShadow) { + paint.setStyle(Paint.Style.FILL); + paint.setColor(0xFF333333); + paint.setShader(shadowGradient); + canvas.drawPath(bPath, paint); + paint.setShader(null); + } + canvas.translate(0, -shadowReservedHeight); + // draw bar + canvas.scale(0.98f, 0.98f, bWidth / 2, bWidth / 2); + paint.setStyle(Paint.Style.FILL); + paint.setColor(0xffffffff); + canvas.drawPath(bPath, paint); + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(bStrokeWidth * 0.5f); + paint.setColor(isOn ? colorPrimaryDark : 0xFFBFBFBF); + canvas.drawPath(bPath, paint); + canvas.restore(); + + paint.reset(); + if (sAnim > 0 || bAnim > 0) invalidate(); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + if ((state == STATE_SWITCH_ON || state == STATE_SWITCH_OFF) && (sAnim * bAnim == 0)) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + return true; + case MotionEvent.ACTION_UP: + lastState = state; + + bAnim = 1; + if (state == STATE_SWITCH_OFF) { + refreshState(STATE_SWITCH_OFF2); + listener.toggleToOn(this); + } else if (state == STATE_SWITCH_ON) { + refreshState(STATE_SWITCH_ON2); + listener.toggleToOff(this); + } + + if (mOnClickListener != null) { + mOnClickListener.onClick(this); + } + break; + } + } + return super.onTouchEvent(event); + } + + @Override + public void setOnClickListener(OnClickListener l) { + super.setOnClickListener(l); + mOnClickListener = l; + } + + public interface OnStateChangedListener { + void toggleToOn(SwitchView view); + + void toggleToOff(SwitchView view); + } + + private OnStateChangedListener listener = new OnStateChangedListener() { + @Override + public void toggleToOn(SwitchView view) { + toggleSwitch(true); + } + + @Override + public void toggleToOff(SwitchView view) { + toggleSwitch(false); + } + }; + + public void setOnStateChangedListener(OnStateChangedListener listener) { + if (listener == null) throw new IllegalArgumentException("empty listener"); + this.listener = listener; + } + + @Override + public Parcelable onSaveInstanceState() { + Parcelable superState = super.onSaveInstanceState(); + SavedState ss = new SavedState(superState); + ss.isOpened = isOpened; + return ss; + } + + @Override + public void onRestoreInstanceState(Parcelable state) { + SavedState ss = (SavedState) state; + super.onRestoreInstanceState(ss.getSuperState()); + this.isOpened = ss.isOpened; + this.state = this.isOpened ? STATE_SWITCH_ON : STATE_SWITCH_OFF; + invalidate(); + } + + @SuppressLint("ParcelCreator") + static final class SavedState extends BaseSavedState { + private boolean isOpened; + + SavedState(Parcelable superState) { + super(superState); + } + + private SavedState(Parcel in) { + super(in); + isOpened = 1 == in.readInt(); + } + + @Override + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeInt(isOpened ? 1 : 0); + } + } + + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/VerticalSwipeRefreshLayout.java b/src/main/java/com/gizwits/opensource/appkit/view/VerticalSwipeRefreshLayout.java new file mode 100644 index 0000000..92b3c24 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/VerticalSwipeRefreshLayout.java @@ -0,0 +1,42 @@ +package com.gizwits.opensource.appkit.view; + +import android.content.Context; +import android.support.v4.widget.SwipeRefreshLayout; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.ViewConfiguration; + +public class VerticalSwipeRefreshLayout extends SwipeRefreshLayout { + private int mTouchSlop; + // 上一次触摸时的X坐标 + private float mPrevX; + + public VerticalSwipeRefreshLayout(Context context, AttributeSet attrs) { + super(context, attrs); + + // 触发移动事件的最短距离,如果小于这个距离就不触发移动控件 + mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent event) { + + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + mPrevX = event.getX(); + break; + + case MotionEvent.ACTION_MOVE: + final float eventX = event.getX(); + float xDiff = Math.abs(eventX - mPrevX); + // Log.d("refresh" ,"move----" + eventX + " " + mPrevX + " " + + // mTouchSlop); + // 增加60的容差,让下拉刷新在竖直滑动时就可以触发 + if (xDiff > mTouchSlop + 60) { + return false; + } + } + + return super.onInterceptTouchEvent(event); + } +} diff --git a/src/main/java/com/gizwits/opensource/appkit/view/ViewPagerIndicator.java b/src/main/java/com/gizwits/opensource/appkit/view/ViewPagerIndicator.java new file mode 100644 index 0000000..d3931b8 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/view/ViewPagerIndicator.java @@ -0,0 +1,415 @@ +package com.gizwits.opensource.appkit.view; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.CornerPathEffect; +import android.graphics.Paint; +import android.graphics.Paint.Style; +import android.graphics.Path; +import android.support.v4.view.ViewPager; +import android.support.v4.view.ViewPager.OnPageChangeListener; +import android.util.AttributeSet; +import android.util.DisplayMetrics; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.R; + +import java.util.List; + +/** + * http://blog.csdn.net/lmj623565791/article/details/42160391 + * + * @author zhy + */ +public class ViewPagerIndicator extends LinearLayout { + /** + * 绘制三角形的画笔 + */ + private Paint mPaint; + /** + * path构成一个三角形 + */ + private Path mPath; + /** + * 线的宽度 + */ + private int mTriangleWidth; + /** + * 线的高度 + */ + private int mTriangleHeight; + + /** + * 三角形的宽度为单个Tab的1/6 + */ + //private static final float RADIO_TRIANGEL = 1.0f / 6; + /** + * 线的最大宽度 + */ + private final int DIMENSION_TRIANGEL_WIDTH = (int) (getScreenWidth() / 2); + + /** + * 初始时,线指示器的偏移量 + */ + private int mInitTranslationX; + /** + * 手指滑动时的偏移量 + */ + private float mTranslationX; + + /** + * 默认的Tab数量 + */ + private static final int COUNT_DEFAULT_TAB = 2; + /** + * tab数量 + */ + private int mTabVisibleCount = 2; + + /** + * tab上的内容 + */ + private List mTabTitles; + /** + * 与之绑定的ViewPager + */ + public ViewPager mViewPager; + + /** + * 标题正常时的颜色(并没有使用 使用的是getContext().getResources().getColor(R.color.text_color) ) + */ + private static final int COLOR_TEXT_NORMAL = 0xFFC6CBCC; + /** + * 标题选中时的颜色 + */ + private static final int COLOR_TEXT_HIGHLIGHTCOLOR = 0xFFFF9A23; + + public ViewPagerIndicator(Context context) { + this(context, null); + } + + public ViewPagerIndicator(Context context, AttributeSet attrs) { + super(context, attrs); + + // 获得自定义属性,tab的数量 + mTabVisibleCount = 2; + if (mTabVisibleCount < 0) + mTabVisibleCount = COUNT_DEFAULT_TAB; + + // 初始化画笔 + mPaint = new Paint(); + mPaint.setAntiAlias(true); +// mPaint.setColor(Color.parseColor("#ffff9a23")); +// mPaint.setColor(getContext().getResources().getColor(R.color.yellow)); + mPaint.setColor(GosDeploy.appConfig_Background()); + mPaint.setStyle(Style.FILL); + mPaint.setPathEffect(new CornerPathEffect(3)); + + } + + /** + * 绘制指示器 + */ + @Override + protected void dispatchDraw(Canvas canvas) { + canvas.save(); + + + // 画笔平移到正确的位置 + canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 1); + Path path = new Path(); + int height = 6; + path.moveTo(-(mInitTranslationX + mTranslationX), 0); + path.lineTo(getScreenWidth(), 0); + path.lineTo(getScreenWidth(), -height); + path.lineTo(-(mInitTranslationX + mTranslationX), -height); + path.close(); + mPaint.setColor(getResources().getColor(R.color.background_color)); + canvas.drawPath(path, mPaint); + + //mPaint.setColor(getResources().getColor(R.color.yellow)); + mPaint.setColor(GosDeploy.appConfig_Background()); + canvas.drawPath(mPath, mPaint); + + canvas.restore(); + + super.dispatchDraw(canvas); + } + + /** + * 初始化三角形的宽度 + */ + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + mTriangleWidth = (int) (w / mTabVisibleCount);// 1/6 of + // width + mTriangleWidth = Math.min(DIMENSION_TRIANGEL_WIDTH, mTriangleWidth); + + // 初始化三角形 + initTriangle(); + + // 初始时的偏移量 + mInitTranslationX = getWidth() / mTabVisibleCount / 2 - mTriangleWidth + / 2; + } + + /** + * 设置可见的tab的数量 + * + * @param count + */ + public void setVisibleTabCount(int count) { + this.mTabVisibleCount = count; + } + + /** + * 设置tab的标题内容 可选,可以自己在布局文件中写死 + * + * @param datas + */ + public void setTabItemTitles(List datas) { + // 如果传入的list有值,则移除布局文件中设置的view + if (datas != null && datas.size() > 0) { + this.removeAllViews(); + this.mTabTitles = datas; + + for (String title : mTabTitles) { + // 添加view + addView(generateTextView(title)); + } + // 设置item的click事件 + setItemClickEvent(); + } + + } + + /** + * 对外的ViewPager的回调接口 + * + * @author zhy + */ + public interface PageChangeListener { + public void onPageScrolled(int position, float positionOffset, + int positionOffsetPixels); + + public void onPageSelected(int position); + + public void onPageScrollStateChanged(int state); + } + + // 对外的ViewPager的回调接口 + private PageChangeListener onPageChangeListener; + + // 对外的ViewPager的回调接口的设置 + public void setOnPageChangeListener(PageChangeListener pageChangeListener) { + this.onPageChangeListener = pageChangeListener; + } + + // 设置关联的ViewPager + public void setViewPager(ViewPager mViewPager, int pos) { + this.mViewPager = mViewPager; + + mViewPager.setOnPageChangeListener(new OnPageChangeListener() { + @Override + public void onPageSelected(int position) { + // 设置字体颜色高亮 + resetTextViewColor(); + highLightTextView(position); + + // 回调 + if (onPageChangeListener != null) { + onPageChangeListener.onPageSelected(position); + } + } + + @Override + public void onPageScrolled(int position, float positionOffset, + int positionOffsetPixels) { + // 滚动 + scroll(position, positionOffset); + + // 回调 + if (onPageChangeListener != null) { + onPageChangeListener.onPageScrolled(position, + positionOffset, positionOffsetPixels); + } + + } + + @Override + public void onPageScrollStateChanged(int state) { + // 回调 + if (onPageChangeListener != null) { + onPageChangeListener.onPageScrollStateChanged(state); + } + + } + }); + // 设置当前页 + mViewPager.setCurrentItem(pos); + // 高亮 + highLightTextView(pos); + } + + /** + * 高亮文本 + * + * @param position + */ + protected void highLightTextView(int position) { + View view = getChildAt(position); + if (view instanceof TextView) { + ((TextView) view).setTextColor(getContext().getResources().getColor(R.color.text_color)); + } + + } + + /** + * 重置文本颜色 + */ + private void resetTextViewColor() { + for (int i = 0; i < getChildCount(); i++) { + View view = getChildAt(i); + if (view instanceof TextView) { + ((TextView) view).setTextColor(getContext().getResources().getColor(R.color.text_state)); + } + } + } + + /** + * 设置点击事件 + */ + public void setItemClickEvent() { + int cCount = getChildCount(); + for (int i = 0; i < cCount; i++) { + final int j = i; + View view = getChildAt(i); + view.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + mViewPager.setCurrentItem(j); + } + }); + } + } + + /** + * 根据标题生成我们的TextView + * + * @param text + * @return + */ + private TextView generateTextView(String text) { + TextView tv = new TextView(getContext()); + LayoutParams lp = new LayoutParams( + LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); + lp.width = getScreenWidth() / mTabVisibleCount; + lp.bottomMargin = 25; + lp.topMargin = 15; + tv.setGravity(Gravity.CENTER); + tv.setTextColor(getContext().getResources().getColor(R.color.text_state)); + tv.setText(text); + tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15); + tv.setLayoutParams(lp); + return tv; + } + + /** + * 初始化三角形指示器 + */ + private void initTriangle() { + mPath = new Path(); + + mTriangleHeight = 10; + mPath.moveTo(0, 0); + mPath.lineTo(mTriangleWidth, 0); + mPath.lineTo(mTriangleWidth, -mTriangleHeight); + mPath.lineTo(0, -mTriangleHeight); + mPath.close(); + } + + private void initLine() { + + } + + + /** + * 指示器跟随手指滚动,以及容器滚动 + * + * @param position + * @param offset + */ + public void scroll(int position, float offset) { + /** + *

+         *  0-1:position=0 ;1-0:postion=0;
+         * 
+ */ + // 不断改变偏移量,invalidate + mTranslationX = getWidth() / mTabVisibleCount * (position + offset); + + int tabWidth = getScreenWidth() / mTabVisibleCount; + + // 容器滚动,当移动到倒数最后一个的时候,开始滚动 + if (offset > 0 && position >= (mTabVisibleCount - 2) + && getChildCount() > mTabVisibleCount) { + if (mTabVisibleCount != 1) { + this.scrollTo((position - (mTabVisibleCount - 2)) * tabWidth + + (int) (tabWidth * offset), 0); + } else + // 为count为1时 的特殊处理 + { + this.scrollTo( + position * tabWidth + (int) (tabWidth * offset), 0); + } + } + + invalidate(); + } + + /** + * 设置布局中view的一些必要属性;如果设置了setTabTitles,布局中view则无效 + */ + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + + int cCount = getChildCount(); + + if (cCount == 0) + return; + + for (int i = 0; i < cCount; i++) { + View view = getChildAt(i); + LayoutParams lp = (LayoutParams) view + .getLayoutParams(); + lp.weight = 0; + lp.width = getScreenWidth() / mTabVisibleCount; + view.setLayoutParams(lp); + } + // 设置点击事件 + setItemClickEvent(); + + } + + /** + * 获得屏幕的宽度 + * + * @return + */ + public int getScreenWidth() { + WindowManager wm = (WindowManager) getContext().getSystemService( + Context.WINDOW_SERVICE); + DisplayMetrics outMetrics = new DisplayMetrics(); + wm.getDefaultDisplay().getMetrics(outMetrics); + return outMetrics.widthPixels; + } + +} diff --git a/src/main/java/com/gizwits/opensource/appkit/wxapi/.DS_Store b/src/main/java/com/gizwits/opensource/appkit/wxapi/.DS_Store new file mode 100644 index 0000000..f4fc62e Binary files /dev/null and b/src/main/java/com/gizwits/opensource/appkit/wxapi/.DS_Store differ diff --git a/src/main/java/com/gizwits/opensource/appkit/wxapi/WXEntryActivity.java b/src/main/java/com/gizwits/opensource/appkit/wxapi/WXEntryActivity.java new file mode 100644 index 0000000..4b55ea3 --- /dev/null +++ b/src/main/java/com/gizwits/opensource/appkit/wxapi/WXEntryActivity.java @@ -0,0 +1,148 @@ +package com.gizwits.opensource.appkit.wxapi; + +import android.os.Bundle; +import android.os.Message; +import android.util.Log; + +import com.gizwits.gizwifisdk.enumration.GizThirdAccountType; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.CommonModule.GosDeploy; +import com.gizwits.opensource.appkit.UserModule.GosUserLoginActivity; +import com.tencent.mm.sdk.modelbase.BaseReq; +import com.tencent.mm.sdk.modelbase.BaseResp; +import com.tencent.mm.sdk.modelmsg.SendAuth; +import com.tencent.mm.sdk.openapi.IWXAPI; +import com.tencent.mm.sdk.openapi.IWXAPIEventHandler; +import com.tencent.mm.sdk.openapi.WXAPIFactory; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + + +public class WXEntryActivity extends GosBaseActivity implements IWXAPIEventHandler { + + private static final String TAG = "WXEntryActivity"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + IWXAPI api = WXAPIFactory.createWXAPI(this, GosDeploy.appConfig_WechatAppID(), true); + api.handleIntent(getIntent(), this); + } + + @Override + public void onReq(BaseReq req) { + Log.i(TAG, "onReq..."); + } + + @Override + public void onResp(BaseResp resp) { + Log.i(TAG, "onResp: " + resp); + String code = null; + switch (resp.errCode) { + case BaseResp.ErrCode.ERR_OK:// 用户同意,只有这种情况的时候code是有效的 + code = ((SendAuth.Resp) resp).code; + Log.i("Apptest", code); + try { + requesUserInfo(code); + } catch (Exception e) { + e.printStackTrace(); + } + break; + case BaseResp.ErrCode.ERR_AUTH_DENIED:// 用户拒绝授权 + Log.i("Apptest", "用户拒绝授权"); + break; + case BaseResp.ErrCode.ERR_USER_CANCEL:// 用户取消 + Log.i("Apptest", "用户取消"); + break; + + default:// 发送返回 + + break; + } + finish(); + } + + public void requesUserInfo(final String code) throws Exception { + final String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GosDeploy.appConfig_WechatAppID() + + "&secret=" + GosDeploy.appConfig_WechatAppSecret() + "&code=" + code + + "&grant_type=authorization_code"; + final android.os.Handler handler = new android.os.Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + Bundle b = msg.getData(); + String newsTemp = b.getString("msg"); + try { + JSONObject jsonObject = new JSONObject(newsTemp); + if (null != jsonObject) { + String openid = jsonObject.getString("openid").toString().trim(); + String access_token = jsonObject.getString("access_token").toString().trim(); + + GosUserLoginActivity.gizThirdAccountType = GizThirdAccountType.GizThirdWeChat; + GosUserLoginActivity.thirdToken = access_token; + GosUserLoginActivity.thirdUid = openid; + + Message msg1 = new Message(); + msg1.what = GosUserLoginActivity.handler_key.THRED_LOGIN.ordinal(); + baseHandler.sendMessage(msg1); + + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + }; + + new Thread(new Runnable() { + @Override + public void run() { + BufferedReader br = null; + try { + URL url = new URL(path); + HttpURLConnection httpconn = (HttpURLConnection) url.openConnection(); + httpconn.setRequestProperty("accept", "*/*"); + httpconn.setDoInput(true); + httpconn.setDoOutput(true); + httpconn.setConnectTimeout(5000); + httpconn.connect(); + int stat = 200; + String msg = ""; + if (stat == 200) { + br = new BufferedReader(new InputStreamReader(httpconn.getInputStream())); + msg = br.readLine(); + Bundle b = new Bundle(); + b.putString("msg", msg); + Message m = new Message(); + m.setData(b); + handler.sendMessage(m); + } else { + msg = "请求失败"; + Log.i(TAG, msg); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + }).start(); + } + +} + diff --git a/src/main/java/zxing/CaptureActivity.java b/src/main/java/zxing/CaptureActivity.java new file mode 100644 index 0000000..0a2cbac --- /dev/null +++ b/src/main/java/zxing/CaptureActivity.java @@ -0,0 +1,443 @@ +/* + * Copyright (C) 2008 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package zxing; + +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.graphics.Rect; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.util.Log; +import android.view.SurfaceHolder; +import android.view.SurfaceView; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.Window; +import android.view.WindowManager; +import android.view.animation.Animation; +import android.view.animation.TranslateAnimation; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.RelativeLayout; +import android.widget.TextView; +import android.widget.Toast; + +import com.gizwits.opensource.appkit.R; +import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; +import com.gizwits.opensource.appkit.DeviceModule.GosDeviceListFragment; +import com.google.zxing.Result; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.lang.reflect.Field; + +import zxing.camera.CameraManager; +import zxing.decoding.DecodeThread; +import zxing.utils.CaptureActivityHandler; +import zxing.utils.InactivityTimer; + +/** + * This activity opens the camera and does the actual scanning on a background + * thread. It draws a viewfinder to help the user place the barcode correctly, + * shows feedback as the image processing is happening, and then overlays the + * results when a scan is successful. + * + * @author dswitkin@google.com (Daniel Switkin) + * @author Sean Owen + */ +public final class CaptureActivity extends GosBaseActivity implements SurfaceHolder.Callback { + + private static final String TAG = CaptureActivity.class.getSimpleName(); + + private CameraManager cameraManager; + private CaptureActivityHandler handler; + private InactivityTimer inactivityTimer; + + private SurfaceView scanPreview = null; + private RelativeLayout scanContainer; + private RelativeLayout scanCropView; + private ImageView scanLine; + private Button btnCancel; + private ImageView ivReturn; + // private String uid, token, mac, productKey, productSecret; + private String did, passcode, product_key; + private TextView tvDeviceCode; + private boolean isSetting = false; + + /** + * ClassName: Enum handler_key.
+ *
+ * date: 2014-11-26 17:51:10
+ * + * @author Lien + */ + private enum handler_key { + + START_BIND, + SEND_CODE + } + + /** + * The handler. + */ + @SuppressLint("HandlerLeak") + Handler mHandler = new Handler() { + public void handleMessage(Message msg) { + super.handleMessage(msg); + handler_key key = handler_key.values()[msg.what]; + switch (key) { + + case START_BIND: + String[] strings = (String[]) msg.obj; + for (String string : strings) { + GosDeviceListFragment.boundMessage.add(string); + } + finish(); + break; + case SEND_CODE: + String s = (String) msg.obj; + Intent intent = new Intent(); + intent.putExtra("code", s); + setResult(33, intent); + finish(); + break; + + } + } + }; + + private Rect mCropRect = null; + + public Handler getHandler() { + return handler; + } + + public CameraManager getCameraManager() { + return cameraManager; + } + + private boolean isHasSurface = false; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + /** + * 设置为竖屏 + */ + if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } + + Window window = getWindow(); + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + setContentView(R.layout.activity_gos_capture); + + scanPreview = (SurfaceView) findViewById(R.id.capture_preview); + scanContainer = (RelativeLayout) findViewById(R.id.capture_container); + scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view); + scanLine = (ImageView) findViewById(R.id.capture_scan_line); + tvDeviceCode = (TextView) findViewById(R.id.tvDeviceCode); + + inactivityTimer = new InactivityTimer(this); + + TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, + Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, + 0.0f); + animation.setDuration(4500); + animation.setRepeatCount(-1); + animation.setRepeatMode(Animation.RESTART); + scanLine.startAnimation(animation); + + btnCancel = (Button) findViewById(R.id.btn_cancel); + ivReturn = (ImageView) findViewById(R.id.iv_return); + OnClickListener myClick = new OnClickListener() { + @Override + public void onClick(View arg0) { + CaptureActivity.this.finish(); + } + }; + btnCancel.setOnClickListener(myClick); + ivReturn.setOnClickListener(myClick); + isSetting = getIntent().getBooleanExtra("isSetting", false); + } + + @Override + public void onResume() { + super.onResume(); + + // CameraManager must be initialized here, not in onCreate(). This is + // necessary because we don't + // want to open the camera driver and measure the screen size if we're + // going to show the help on + // first launch. That led to bugs where the scanning rectangle was the + // wrong size and partially + // off screen. + cameraManager = new CameraManager(getApplication()); + + handler = null; + + if (isHasSurface) { + // The activity was paused but not stopped, so the surface still + // exists. Therefore + // surfaceCreated() won't be called, so init the camera here. + initCamera(scanPreview.getHolder()); + } else { + // Install the callback and wait for surfaceCreated() to init the + // camera. + scanPreview.getHolder().addCallback(this); + } + + inactivityTimer.onResume(); + } + + @Override + public void onPause() { + if (handler != null) { + handler.quitSynchronously(); + handler = null; + } + inactivityTimer.onPause(); + cameraManager.closeDriver(); + if (!isHasSurface) { + scanPreview.getHolder().removeCallback(this); + } + super.onPause(); + } + + @Override + protected void onDestroy() { + inactivityTimer.shutdown(); + super.onDestroy(); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right); + } + + @Override + public void surfaceCreated(SurfaceHolder holder) { + if (holder == null) { + Log.i(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); + } + if (!isHasSurface) { + isHasSurface = true; + initCamera(holder); + } + } + + @Override + public void surfaceDestroyed(SurfaceHolder holder) { + isHasSurface = false; + } + + @Override + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { + + } + + /** + * A valid barcode has been found, so give an indication of success and show + * the results. + * + * @param rawResult The contents of the barcode. + * @param bundle The extras + */ + public void handleDecode(Result rawResult, Bundle bundle) { + String text = rawResult.getText(); + boolean isJson = false; + try { + JSONObject jsonObject = new JSONObject(text); + isJson = true; + } catch(JSONException e) { + e.printStackTrace(); + } + Message msg = new Message(); + if (isSetting) { + if (isJson) { + msg.what = handler_key.SEND_CODE.ordinal(); + msg.obj = text; + mHandler.sendMessage(msg); + } else { + Toast.makeText(this, getString(R.string.code_invalid), Toast.LENGTH_LONG).show(); + } + } else { + if (text.contains("product_key=") && text.contains("did=") && text.contains("passcode=")) { + inactivityTimer.onActivity(); + product_key = getParamFomeUrl(text, "product_key"); + did = getParamFomeUrl(text, "did"); + passcode = getParamFomeUrl(text, "passcode"); + String[] strings = {did, passcode}; + msg.what = handler_key.START_BIND.ordinal(); + msg.obj = strings; + mHandler.sendMessage(msg); + Log.e(TAG, "handleDecode-------: " + strings); + } else if (text.contains("type=") && text.contains("code=")) { + //type=xxx & code=xxx + String[] split = text.split("&"); + String[] split2 = split[1].split("="); + final String code = split2[1]; + String[] strings = {"", "", code}; + + msg.what = handler_key.START_BIND.ordinal(); + msg.obj = strings; + mHandler.sendMessage(msg); + } else { + // handler = new CaptureActivityHandler(this, cameraManager, + // DecodeThread.ALL_MODE); + String[] strings = {text}; + msg.what = handler_key.START_BIND.ordinal(); + msg.obj = strings; + mHandler.sendMessage(msg); + } + } + } + + + private String getParamFomeUrl(String url, String param) { + String product_key = ""; + int startindex = url.indexOf(param + "="); + startindex += (param.length() + 1); + String subString = url.substring(startindex); + int endindex = subString.indexOf("&"); + if (endindex == -1) { + product_key = subString; + } else { + product_key = subString.substring(0, endindex); + } + return product_key; + } + + private void initCamera(SurfaceHolder surfaceHolder) { + if (surfaceHolder == null) { + throw new IllegalStateException("No SurfaceHolder provided"); + } + if (cameraManager.isOpen()) { + Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); + return; + } + try { + cameraManager.openDriver(surfaceHolder); + // Creating the handler starts the preview, which can also throw a + // RuntimeException. + if (handler == null) { + handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE); + } + + initCrop(); + } catch(IOException ioe) { + Log.w(TAG, ioe); + displayFrameworkBugMessageAndExit(); + } catch(RuntimeException e) { + // Barcode Scanner has seen crashes in the wild of this variety: + // java.?lang.?RuntimeException: Fail to connect to camera service + Log.w(TAG, "Unexpected error initializing camera", e); + displayFrameworkBugMessageAndExit(); + } + } + + private void displayFrameworkBugMessageAndExit() { + // camera error + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.app_name)); + String camera_error = getText(R.string.camera_error).toString(); + builder.setMessage(camera_error); + String shure = getText(R.string.besure).toString(); + builder.setPositiveButton(shure, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + + }); + builder.setOnCancelListener(new DialogInterface.OnCancelListener() { + + @Override + public void onCancel(DialogInterface dialog) { + finish(); + } + }); + builder.show(); + } + + public void restartPreviewAfterDelay(long delayMS) { + if (handler != null) { + handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS); + } + } + + public Rect getCropRect() { + return mCropRect; + } + + /** + * 初始化截取的矩形区域 + */ + private void initCrop() { + int cameraWidth = cameraManager.getCameraResolution().y; + int cameraHeight = cameraManager.getCameraResolution().x; + + /** 获取布局中扫描框的位置信息 */ + int[] location = new int[2]; + scanCropView.getLocationInWindow(location); + + int cropLeft = location[0]; + int cropTop = location[1] - getStatusBarHeight(); + + int cropWidth = scanCropView.getWidth(); + int cropHeight = scanCropView.getHeight(); + + /** 获取布局容器的宽高 */ + int containerWidth = scanContainer.getWidth(); + int containerHeight = scanContainer.getHeight(); + + /** 计算最终截取的矩形的左上角顶点x坐标 */ + int x = cropLeft * cameraWidth / containerWidth; + /** 计算最终截取的矩形的左上角顶点y坐标 */ + int y = cropTop * cameraHeight / containerHeight; + + /** 计算最终截取的矩形的宽度 */ + int width = cropWidth * cameraWidth / containerWidth; + /** 计算最终截取的矩形的高度 */ + int height = cropHeight * cameraHeight / containerHeight; + + /** 生成最终的截取的矩形 */ + mCropRect = new Rect(x, y, width + x, height + y); + } + + private int getStatusBarHeight() { + try { + Class c = Class.forName("com.android.internal.R$dimen"); + Object obj = c.newInstance(); + Field field = c.getField("status_bar_height"); + int x = Integer.parseInt(field.get(obj).toString()); + return getResources().getDimensionPixelSize(x); + } catch(Exception e) { + e.printStackTrace(); + } + return 0; + } + +} \ No newline at end of file diff --git a/src/main/java/zxing/camera/AutoFocusManager.java b/src/main/java/zxing/camera/AutoFocusManager.java new file mode 100644 index 0000000..914bfc8 --- /dev/null +++ b/src/main/java/zxing/camera/AutoFocusManager.java @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2012 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.camera; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.RejectedExecutionException; +import android.annotation.SuppressLint; +import android.content.Context; +import android.hardware.*; +import android.os.AsyncTask; +import android.os.Build; +import android.util.Log; + +public class AutoFocusManager implements Camera.AutoFocusCallback { + + private static final String TAG = AutoFocusManager.class.getSimpleName(); + + private static final long AUTO_FOCUS_INTERVAL_MS = 2000L; + private static final Collection FOCUS_MODES_CALLING_AF; + + static { + FOCUS_MODES_CALLING_AF = new ArrayList(2); + FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO); + FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO); + } + + private boolean stopped; + private boolean focusing; + private final boolean useAutoFocus; + private final Camera camera; + private AsyncTask outstandingTask; + + public AutoFocusManager(Context context, Camera camera) { + this.camera = camera; + String currentFocusMode = camera.getParameters().getFocusMode(); + useAutoFocus = FOCUS_MODES_CALLING_AF.contains(currentFocusMode); + Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus); + start(); + } + + @Override + public synchronized void onAutoFocus(boolean success, Camera theCamera) { + focusing = false; + autoFocusAgainLater(); + } + + @SuppressLint("NewApi") + private synchronized void autoFocusAgainLater() { + if (!stopped && outstandingTask == null) { + AutoFocusTask newTask = new AutoFocusTask(); + try { + if (Build.VERSION.SDK_INT >= 11) { + newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { + newTask.execute(); + } + outstandingTask = newTask; + } catch (RejectedExecutionException ree) { + Log.w(TAG, "Could not request auto focus", ree); + } + } + } + + public synchronized void start() { + if (useAutoFocus) { + outstandingTask = null; + if (!stopped && !focusing) { + try { + camera.autoFocus(this); + focusing = true; + } catch (RuntimeException re) { + // Have heard RuntimeException reported in Android 4.0.x+; + // continue? + Log.w(TAG, "Unexpected exception while focusing", re); + // Try again later to keep cycle going + autoFocusAgainLater(); + } + } + } + } + + private synchronized void cancelOutstandingTask() { + if (outstandingTask != null) { + if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) { + outstandingTask.cancel(true); + } + outstandingTask = null; + } + } + + public synchronized void stop() { + stopped = true; + if (useAutoFocus) { + cancelOutstandingTask(); + // Doesn't hurt to call this even if not focusing + try { + camera.cancelAutoFocus(); + } catch (RuntimeException re) { + // Have heard RuntimeException reported in Android 4.0.x+; + // continue? + Log.w(TAG, "Unexpected exception while cancelling focusing", re); + } + } + } + + private final class AutoFocusTask extends AsyncTask { + @Override + protected Object doInBackground(Object... voids) { + try { + Thread.sleep(AUTO_FOCUS_INTERVAL_MS); + } catch (InterruptedException e) { + // continue + } + start(); + return null; + } + } + +} diff --git a/src/main/java/zxing/camera/CameraConfigurationManager.java b/src/main/java/zxing/camera/CameraConfigurationManager.java new file mode 100644 index 0000000..53a8c50 --- /dev/null +++ b/src/main/java/zxing/camera/CameraConfigurationManager.java @@ -0,0 +1,220 @@ +/* + * Copyright (C) 2008 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package zxing.camera; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.Point; +import android.hardware.Camera; +import android.util.Log; +import android.view.Display; +import android.view.WindowManager; + +public final class CameraConfigurationManager { + + private static final String TAG = "CameraConfiguration"; + + private static final int MIN_PREVIEW_PIXELS = 480 * 320; + private static final double MAX_ASPECT_DISTORTION = 0.15; + + private final Context context; + + // 屏幕分辨率 + private Point screenResolution; + // 相机分辨率 + private Point cameraResolution; + + public CameraConfigurationManager(Context context) { + this.context = context; + } + + public void initFromCameraParameters(Camera camera) { + Camera.Parameters parameters = camera.getParameters(); + WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + Display display = manager.getDefaultDisplay(); + Point theScreenResolution = new Point(); + theScreenResolution = getDisplaySize(display); + + screenResolution = theScreenResolution; + Log.i(TAG, "Screen resolution: " + screenResolution); + + /** 因为换成了竖屏显示,所以不替换屏幕宽高得出的预览图是变形的 */ + Point screenResolutionForCamera = new Point(); + screenResolutionForCamera.x = screenResolution.x; + screenResolutionForCamera.y = screenResolution.y; + + if (screenResolution.x < screenResolution.y) { + screenResolutionForCamera.x = screenResolution.y; + screenResolutionForCamera.y = screenResolution.x; + } + + cameraResolution = findBestPreviewSizeValue(parameters, screenResolutionForCamera); + Log.i(TAG, "Camera resolution x: " + cameraResolution.x); + Log.i(TAG, "Camera resolution y: " + cameraResolution.y); + } + + @SuppressLint("NewApi") + private Point getDisplaySize(final Display display) { + final Point point = new Point(); + try { + display.getSize(point); + } catch (NoSuchMethodError ignore) { + point.x = display.getWidth(); + point.y = display.getHeight(); + } + return point; + } + + public void setDesiredCameraParameters(Camera camera, boolean safeMode) { + Camera.Parameters parameters = camera.getParameters(); + + if (parameters == null) { + Log.w(TAG, "Device error: no camera parameters are available. Proceeding without configuration."); + return; + } + + Log.i(TAG, "Initial camera parameters: " + parameters.flatten()); + + if (safeMode) { + Log.w(TAG, "In camera config safe mode -- most settings will not be honored"); + } + + parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); + camera.setParameters(parameters); + + Camera.Parameters afterParameters = camera.getParameters(); + Camera.Size afterSize = afterParameters.getPreviewSize(); + if (afterSize != null && (cameraResolution.x != afterSize.width || cameraResolution.y != afterSize.height)) { + Log.w(TAG, "Camera said it supported preview size " + cameraResolution.x + 'x' + cameraResolution.y + ", but after setting it, preview size is " + afterSize.width + 'x' + afterSize.height); + cameraResolution.x = afterSize.width; + cameraResolution.y = afterSize.height; + } + + /** 设置相机预览为竖屏 */ + String model=android.os.Build.MODEL; + if("Nexus 5X".equals(model)){ + camera.setDisplayOrientation(270); + }else{ + camera.setDisplayOrientation(90); + } + + } + + public Point getCameraResolution() { + return cameraResolution; + } + + public Point getScreenResolution() { + return screenResolution; + } + + /** + * 从相机支持的分辨率中计算出最适合的预览界面尺寸 + * + * @param parameters + * @param screenResolution + * @return + */ + private Point findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution) { + List rawSupportedSizes = parameters.getSupportedPreviewSizes(); + if (rawSupportedSizes == null) { + Log.w(TAG, "Device returned no supported preview sizes; using default"); + Camera.Size defaultSize = parameters.getPreviewSize(); + return new Point(defaultSize.width, defaultSize.height); + } + + // Sort by size, descending + List supportedPreviewSizes = new ArrayList(rawSupportedSizes); + Collections.sort(supportedPreviewSizes, new Comparator() { + @Override + public int compare(Camera.Size a, Camera.Size b) { + int aPixels = a.height * a.width; + int bPixels = b.height * b.width; + if (bPixels < aPixels) { + return -1; + } + if (bPixels > aPixels) { + return 1; + } + return 0; + } + }); + + if (Log.isLoggable(TAG, Log.INFO)) { + StringBuilder previewSizesString = new StringBuilder(); + for (Camera.Size supportedPreviewSize : supportedPreviewSizes) { + previewSizesString.append(supportedPreviewSize.width).append('x').append(supportedPreviewSize.height).append(' '); + } + Log.i(TAG, "Supported preview sizes: " + previewSizesString); + } + + double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y; + + // Remove sizes that are unsuitable + Iterator it = supportedPreviewSizes.iterator(); + while (it.hasNext()) { + Camera.Size supportedPreviewSize = it.next(); + int realWidth = supportedPreviewSize.width; + int realHeight = supportedPreviewSize.height; + if (realWidth * realHeight < MIN_PREVIEW_PIXELS) { + it.remove(); + continue; + } + + boolean isCandidatePortrait = realWidth < realHeight; + int maybeFlippedWidth = isCandidatePortrait ? realHeight : realWidth; + int maybeFlippedHeight = isCandidatePortrait ? realWidth : realHeight; + + double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight; + double distortion = Math.abs(aspectRatio - screenAspectRatio); + if (distortion > MAX_ASPECT_DISTORTION) { + it.remove(); + continue; + } + + if (maybeFlippedWidth == screenResolution.x && maybeFlippedHeight == screenResolution.y) { + Point exactPoint = new Point(realWidth, realHeight); + Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint); + return exactPoint; + } + } + + // If no exact match, use largest preview size. This was not a great + // idea on older devices because + // of the additional computation needed. We're likely to get here on + // newer Android 4+ devices, where + // the CPU is much more powerful. + if (!supportedPreviewSizes.isEmpty()) { + Camera.Size largestPreview = supportedPreviewSizes.get(0); + Point largestSize = new Point(largestPreview.width, largestPreview.height); + Log.i(TAG, "Using largest suitable preview size: " + largestSize); + return largestSize; + } + + // If there is nothing at all suitable, return current preview size + Camera.Size defaultPreview = parameters.getPreviewSize(); + Point defaultSize = new Point(defaultPreview.width, defaultPreview.height); + Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize); + + return defaultSize; + } +} diff --git a/src/main/java/zxing/camera/CameraManager.java b/src/main/java/zxing/camera/CameraManager.java new file mode 100644 index 0000000..9286c5b --- /dev/null +++ b/src/main/java/zxing/camera/CameraManager.java @@ -0,0 +1,209 @@ +/* + * Copyright (C) 2008 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.camera; + +import java.io.IOException; + +import zxing.camera.open.OpenCameraInterface; +import android.content.Context; +import android.graphics.Point; +import android.hardware.Camera; +import android.hardware.Camera.Size; +import android.os.Handler; +import android.util.Log; +import android.view.SurfaceHolder; + + +/** + * This object wraps the Camera service object and expects to be the only one + * talking to it. The implementation encapsulates the steps needed to take + * preview-sized images, which are used for both preview and decoding. + * + * @author dswitkin@google.com (Daniel Switkin) + */ +public class CameraManager { + + private static final String TAG = CameraManager.class.getSimpleName(); + + private final Context context; + private final CameraConfigurationManager configManager; + private Camera camera; + private AutoFocusManager autoFocusManager; + + private boolean initialized; + private boolean previewing; + private int requestedCameraId = -1; + /** + * Preview frames are delivered here, which we pass on to the registered + * handler. Make sure to clear the handler so it will only receive one + * message. + */ + private final PreviewCallback previewCallback; + + public CameraManager(Context context) { + this.context = context; + this.configManager = new CameraConfigurationManager(context); + previewCallback = new PreviewCallback(configManager); + } + + /** + * Opens the camera driver and initializes the hardware parameters. + * + * @param holder + * The surface object which the camera will draw preview frames + * into. + * @throws IOException + * Indicates the camera driver failed to open. + */ + public synchronized void openDriver(SurfaceHolder holder) throws IOException { + Camera theCamera = camera; + if (theCamera == null) { + + if (requestedCameraId >= 0) { + theCamera = OpenCameraInterface.open(requestedCameraId); + } else { + theCamera = OpenCameraInterface.open(); + } + + if (theCamera == null) { + throw new IOException(); + } + camera = theCamera; + } + theCamera.setPreviewDisplay(holder); + + if (!initialized) { + initialized = true; + configManager.initFromCameraParameters(theCamera); + } + + Camera.Parameters parameters = theCamera.getParameters(); + String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save + // these, + // temporarily + try { + configManager.setDesiredCameraParameters(theCamera, false); + } catch (RuntimeException re) { + // Driver failed + Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); + Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); + // Reset: + if (parametersFlattened != null) { + parameters = theCamera.getParameters(); + parameters.unflatten(parametersFlattened); + try { + theCamera.setParameters(parameters); + configManager.setDesiredCameraParameters(theCamera, true); + } catch (RuntimeException re2) { + // Well, darn. Give up + Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); + } + } + } + + } + + public synchronized boolean isOpen() { + return camera != null; + } + + /** + * Closes the camera driver if still in use. + */ + public synchronized void closeDriver() { + if (camera != null) { + camera.release(); + camera = null; + // Make sure to clear these each time we close the camera, so that + // any scanning rect + // requested by intent is forgotten. + } + } + + /** + * Asks the camera hardware to begin drawing preview frames to the screen. + */ + public synchronized void startPreview() { + Camera theCamera = camera; + if (theCamera != null && !previewing) { + theCamera.startPreview(); + previewing = true; + autoFocusManager = new AutoFocusManager(context, camera); + } + } + + /** + * Tells the camera to stop drawing preview frames. + */ + public synchronized void stopPreview() { + if (autoFocusManager != null) { + autoFocusManager.stop(); + autoFocusManager = null; + } + if (camera != null && previewing) { + camera.stopPreview(); + previewCallback.setHandler(null, 0); + previewing = false; + } + } + + /** + * A single preview frame will be returned to the handler supplied. The data + * will arrive as byte[] in the message.obj field, with width and height + * encoded as message.arg1 and message.arg2, respectively. + * + * @param handler + * The handler to send the message to. + * @param message + * The what field of the message to be sent. + */ + public synchronized void requestPreviewFrame(Handler handler, int message) { + Camera theCamera = camera; + if (theCamera != null && previewing) { + previewCallback.setHandler(handler, message); + theCamera.setOneShotPreviewCallback(previewCallback); + } + } + + /** + * Allows third party apps to specify the camera ID, rather than determine + * it automatically based on available cameras and their orientation. + * + * @param cameraId + * camera ID of the camera to use. A negative value means + * "no preference". + */ + public synchronized void setManualCameraId(int cameraId) { + requestedCameraId = cameraId; + } + + /** + * 获取相机分辨率 + * + * @return + */ + public Point getCameraResolution() { + return configManager.getCameraResolution(); + } + + public Size getPreviewSize() { + if (null != camera) { + return camera.getParameters().getPreviewSize(); + } + return null; + } +} diff --git a/src/main/java/zxing/camera/PreviewCallback.java b/src/main/java/zxing/camera/PreviewCallback.java new file mode 100644 index 0000000..7333d87 --- /dev/null +++ b/src/main/java/zxing/camera/PreviewCallback.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2010 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.camera; + +import android.graphics.Point; +import android.hardware.Camera; +import android.os.Handler; +import android.os.Message; +import android.util.Log; + +public class PreviewCallback implements Camera.PreviewCallback { + + private static final String TAG = PreviewCallback.class.getSimpleName(); + + private final CameraConfigurationManager configManager; + private Handler previewHandler; + private int previewMessage; + + public PreviewCallback(CameraConfigurationManager configManager) { + this.configManager = configManager; + } + + public void setHandler(Handler previewHandler, int previewMessage) { + this.previewHandler = previewHandler; + this.previewMessage = previewMessage; + } + + @Override + public void onPreviewFrame(byte[] data, Camera camera) { + Point cameraResolution = configManager.getCameraResolution(); + Handler thePreviewHandler = previewHandler; + if (cameraResolution != null && thePreviewHandler != null) { + Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x, cameraResolution.y, + data); + message.sendToTarget(); + previewHandler = null; + } else { + Log.d(TAG, "Got preview callback, but no handler or resolution available"); + } + } + +} diff --git a/src/main/java/zxing/camera/open/OpenCameraInterface.java b/src/main/java/zxing/camera/open/OpenCameraInterface.java new file mode 100644 index 0000000..553964e --- /dev/null +++ b/src/main/java/zxing/camera/open/OpenCameraInterface.java @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2012 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.camera.open; + +import android.hardware.Camera; +import android.util.Log; + +public class OpenCameraInterface { + + private static final String TAG = OpenCameraInterface.class.getName(); + + /** + * Opens the requested camera with {@link Camera#open(int)}, if one exists. + * + * @param cameraId + * camera ID of the camera to use. A negative value means + * "no preference" + * @return handle to {@link Camera} that was opened + */ + public static Camera open(int cameraId) { + + int numCameras = Camera.getNumberOfCameras(); + if (numCameras == 0) { + Log.w(TAG, "No cameras!"); + return null; + } + + boolean explicitRequest = cameraId >= 0; + + if (!explicitRequest) { + // Select a camera if no explicit camera requested + int index = 0; + while (index < numCameras) { + Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); + Camera.getCameraInfo(index, cameraInfo); + if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { + break; + } + index++; + } + + cameraId = index; + } + + Camera camera; + if (cameraId < numCameras) { + Log.i(TAG, "Opening camera #" + cameraId); + camera = Camera.open(cameraId); + } else { + if (explicitRequest) { + Log.w(TAG, "Requested camera does not exist: " + cameraId); + camera = null; + } else { + Log.i(TAG, "No camera facing back; returning camera #0"); + camera = Camera.open(0); + } + } + + return camera; + } + + /** + * Opens a rear-facing camera with {@link Camera#open(int)}, if one exists, + * or opens camera 0. + * + * @return handle to {@link Camera} that was opened + */ + public static Camera open() { + return open(-1); + } + +} diff --git a/src/main/java/zxing/decoding/DecodeFormatManager.java b/src/main/java/zxing/decoding/DecodeFormatManager.java new file mode 100644 index 0000000..3ddebe9 --- /dev/null +++ b/src/main/java/zxing/decoding/DecodeFormatManager.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2010 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.decoding; + +import java.util.Collection; +import java.util.EnumSet; +import java.util.Set; + +import com.google.zxing.BarcodeFormat; + +public class DecodeFormatManager { + + // 1D解码 + private static final Set PRODUCT_FORMATS; + private static final Set INDUSTRIAL_FORMATS; + private static final Set ONE_D_FORMATS; + + // 二维码解码 + private static final Set QR_CODE_FORMATS; + + static { + PRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A, BarcodeFormat.UPC_E, BarcodeFormat.EAN_13, BarcodeFormat.EAN_8, BarcodeFormat.RSS_14, BarcodeFormat.RSS_EXPANDED); + INDUSTRIAL_FORMATS = EnumSet.of(BarcodeFormat.CODE_39, BarcodeFormat.CODE_93, BarcodeFormat.CODE_128, BarcodeFormat.ITF, BarcodeFormat.CODABAR); + ONE_D_FORMATS = EnumSet.copyOf(PRODUCT_FORMATS); + ONE_D_FORMATS.addAll(INDUSTRIAL_FORMATS); + + QR_CODE_FORMATS = EnumSet.of(BarcodeFormat.QR_CODE); + } + + public static Collection getQrCodeFormats() { + return QR_CODE_FORMATS; + } + + public static Collection getBarCodeFormats() { + return ONE_D_FORMATS; + } +} diff --git a/src/main/java/zxing/decoding/DecodeHandler.java b/src/main/java/zxing/decoding/DecodeHandler.java new file mode 100644 index 0000000..c95ea87 --- /dev/null +++ b/src/main/java/zxing/decoding/DecodeHandler.java @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2010 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.decoding; + +import android.graphics.Bitmap; +import android.graphics.Rect; +import android.hardware.Camera.Size; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; + +import com.gizwits.opensource.appkit.R; +import com.google.zxing.BinaryBitmap; +import com.google.zxing.DecodeHintType; +import com.google.zxing.MultiFormatReader; +import com.google.zxing.PlanarYUVLuminanceSource; +import com.google.zxing.ReaderException; +import com.google.zxing.Result; +import com.google.zxing.common.HybridBinarizer; + +import java.io.ByteArrayOutputStream; +import java.util.Map; + +import zxing.CaptureActivity; + + +public class DecodeHandler extends Handler { + + private final CaptureActivity activity; + private final MultiFormatReader multiFormatReader; + private boolean running = true; + + public DecodeHandler(CaptureActivity activity, Map hints) { + multiFormatReader = new MultiFormatReader(); + multiFormatReader.setHints(hints); + this.activity = activity; + } + + @Override + public void handleMessage(Message message) { + if (!running) { + return; + } + switch (message.what) { + case R.id.decode: + decode((byte[]) message.obj, message.arg1, message.arg2); + break; + case R.id.quit: + running = false; + Looper.myLooper().quit(); + break; + } + } + + /** + * Decode the data within the viewfinder rectangle, and time how long it + * took. For efficiency, reuse the same reader objects from one decode to + * the next. + * + * @param data + * The YUV preview frame. + * @param width + * The width of the preview frame. + * @param height + * The height of the preview frame. + */ + private void decode(byte[] data, int width, int height) { + Size size = activity.getCameraManager().getPreviewSize(); + + // 这里需要将获取的data翻转一下,因为相机默认拿的的横屏的数据 + byte[] rotatedData = new byte[data.length]; + for (int y = 0; y < size.height; y++) { + for (int x = 0; x < size.width; x++) + rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width]; + } + + // 宽高也要调整 + int tmp = size.width; + size.width = size.height; + size.height = tmp; + + Result rawResult = null; + PlanarYUVLuminanceSource source = buildLuminanceSource(rotatedData, size.width, size.height); + if (source != null) { + BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + try { + rawResult = multiFormatReader.decodeWithState(bitmap); + } catch (ReaderException re) { + // continue + } finally { + multiFormatReader.reset(); + } + } + + Handler handler = activity.getHandler(); + if (rawResult != null) { + // Don't log the barcode contents for security. + if (handler != null) { + Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult); + Bundle bundle = new Bundle(); + bundleThumbnail(source, bundle); + message.setData(bundle); + message.sendToTarget(); + } + } else { + if (handler != null) { + Message message = Message.obtain(handler, R.id.decode_failed); + message.sendToTarget(); + } + } + + } + + private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bundle) { + int[] pixels = source.renderThumbnail(); + int width = source.getThumbnailWidth(); + int height = source.getThumbnailHeight(); + Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out); + bundle.putByteArray(DecodeThread.BARCODE_BITMAP, out.toByteArray()); + } + + /** + * A factory method to build the appropriate LuminanceSource object based on + * the format of the preview buffers, as described by Camera.Parameters. + * + * @param data + * A preview frame. + * @param width + * The width of the image. + * @param height + * The height of the image. + * @return A PlanarYUVLuminanceSource instance. + */ + public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) { + Rect rect = activity.getCropRect(); + if (rect == null) { + return null; + } + // Go ahead and assume it's YUV rather than die. + return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), + false); + } + +} diff --git a/src/main/java/zxing/decoding/DecodeThread.java b/src/main/java/zxing/decoding/DecodeThread.java new file mode 100644 index 0000000..140ef38 --- /dev/null +++ b/src/main/java/zxing/decoding/DecodeThread.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2008 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.decoding; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import zxing.CaptureActivity; +import android.os.Handler; +import android.os.Looper; +import com.google.zxing.BarcodeFormat; +import com.google.zxing.DecodeHintType; + +/** + * This thread does all the heavy lifting of decoding the images. + * + * @author dswitkin@google.com (Daniel Switkin) + */ +public class DecodeThread extends Thread { + + public static final String BARCODE_BITMAP = "barcode_bitmap"; + + public static final int BARCODE_MODE = 0X100; + public static final int QRCODE_MODE = 0X200; + public static final int ALL_MODE = 0X300; + + private final CaptureActivity activity; + private final Map hints; + private Handler handler; + private final CountDownLatch handlerInitLatch; + + public DecodeThread(CaptureActivity activity, int decodeMode) { + + this.activity = activity; + handlerInitLatch = new CountDownLatch(1); + + hints = new EnumMap(DecodeHintType.class); + + Collection decodeFormats = new ArrayList(); + decodeFormats.addAll(EnumSet.of(BarcodeFormat.AZTEC)); + decodeFormats.addAll(EnumSet.of(BarcodeFormat.PDF_417)); + + switch (decodeMode) { + case BARCODE_MODE: + decodeFormats.addAll(DecodeFormatManager.getBarCodeFormats()); + break; + + case QRCODE_MODE: + decodeFormats.addAll(DecodeFormatManager.getQrCodeFormats()); + break; + + case ALL_MODE: + decodeFormats.addAll(DecodeFormatManager.getBarCodeFormats()); + decodeFormats.addAll(DecodeFormatManager.getQrCodeFormats()); + break; + + default: + break; + } + + hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); + } + + public Handler getHandler() { + try { + handlerInitLatch.await(); + } catch (InterruptedException ie) { + // continue? + } + return handler; + } + + @Override + public void run() { + Looper.prepare(); + handler = new DecodeHandler(activity, hints); + handlerInitLatch.countDown(); + Looper.loop(); + } + +} diff --git a/src/main/java/zxing/utils/CaptureActivityHandler.java b/src/main/java/zxing/utils/CaptureActivityHandler.java new file mode 100644 index 0000000..fc9d696 --- /dev/null +++ b/src/main/java/zxing/utils/CaptureActivityHandler.java @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2008 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.utils; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; + +import com.gizwits.opensource.appkit.R; +import com.google.zxing.Result; + +import zxing.CaptureActivity; +import zxing.camera.CameraManager; +import zxing.decoding.DecodeThread; + + +/** + * This class handles all the messaging which comprises the state machine for + * capture. + * + * @author dswitkin@google.com (Daniel Switkin) + */ +public class CaptureActivityHandler extends Handler { + + private final CaptureActivity activity; + private final DecodeThread decodeThread; + private final CameraManager cameraManager; + private State state; + + private enum State { + PREVIEW, SUCCESS, DONE + } + + public CaptureActivityHandler(CaptureActivity activity, CameraManager cameraManager, int decodeMode) { + this.activity = activity; + decodeThread = new DecodeThread(activity, decodeMode); + decodeThread.start(); + state = State.SUCCESS; + + // Start ourselves capturing previews and decoding. + this.cameraManager = cameraManager; + cameraManager.startPreview(); + restartPreviewAndDecode(); + } + + @Override + public void handleMessage(Message message) { + switch (message.what) { + case R.id.restart_preview: + restartPreviewAndDecode(); + break; + case R.id.decode_succeeded: + state = State.SUCCESS; + Bundle bundle = message.getData(); + + activity.handleDecode((Result) message.obj, bundle); + break; + case R.id.decode_failed: + // We're decoding as fast as possible, so when one decode fails, + // start another. + state = State.PREVIEW; + cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode); + break; + case R.id.return_scan_result: + activity.setResult(Activity.RESULT_OK, (Intent) message.obj); + activity.finish(); + break; + } + } + + public void quitSynchronously() { + state = State.DONE; + cameraManager.stopPreview(); + Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit); + quit.sendToTarget(); + try { + // Wait at most half a second; should be enough time, and onPause() + // will timeout quickly + decodeThread.join(500L); + } catch (InterruptedException e) { + // continue + } + + // Be absolutely sure we don't send any queued up messages + removeMessages(R.id.decode_succeeded); + removeMessages(R.id.decode_failed); + } + + private void restartPreviewAndDecode() { + if (state == State.SUCCESS) { + state = State.PREVIEW; + cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode); + } + } + +} diff --git a/src/main/java/zxing/utils/InactivityTimer.java b/src/main/java/zxing/utils/InactivityTimer.java new file mode 100644 index 0000000..c26733a --- /dev/null +++ b/src/main/java/zxing/utils/InactivityTimer.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2010 ZXing authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zxing.utils; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.AsyncTask; +import android.os.BatteryManager; +import android.os.Build; +import android.util.Log; + +/** + * Finishes an activity after a period of inactivity if the device is on battery + * power. + */ +public class InactivityTimer { + + private static final String TAG = InactivityTimer.class.getSimpleName(); + + private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L; + + private Activity activity; + private BroadcastReceiver powerStatusReceiver; + private boolean registered; + private AsyncTask inactivityTask; + + public InactivityTimer(Activity activity) { + this.activity = activity; + powerStatusReceiver = new PowerStatusReceiver(); + registered = false; + onActivity(); + } + + @SuppressLint("NewApi") + public synchronized void onActivity() { + cancel(); + inactivityTask = new InactivityAsyncTask(); + if (Build.VERSION.SDK_INT >= 11) { + inactivityTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } else { + inactivityTask.execute(); + } + } + + public synchronized void onPause() { + cancel(); + if (registered) { + activity.unregisterReceiver(powerStatusReceiver); + registered = false; + } else { + Log.w(TAG, "PowerStatusReceiver was never registered?"); + } + } + + public synchronized void onResume() { + if (registered) { + Log.w(TAG, "PowerStatusReceiver was already registered?"); + } else { + activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + registered = true; + } + onActivity(); + } + + private synchronized void cancel() { + AsyncTask task = inactivityTask; + if (task != null) { + task.cancel(true); + inactivityTask = null; + } + } + + public void shutdown() { + cancel(); + } + + private class PowerStatusReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { + // 0 indicates that we're on battery + boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0; + if (onBatteryNow) { + InactivityTimer.this.onActivity(); + } else { + InactivityTimer.this.cancel(); + } + } + } + } + + private class InactivityAsyncTask extends AsyncTask { + @Override + protected Object doInBackground(Object... objects) { + try { + Thread.sleep(INACTIVITY_DELAY_MS); + Log.i(TAG, "Finishing activity due to inactivity"); + activity.finish(); + } catch (InterruptedException e) { + // continue without killing + } + return null; + } + } + +} diff --git a/src/main/res/.DS_Store b/src/main/res/.DS_Store new file mode 100644 index 0000000..cfe1ba1 Binary files /dev/null and b/src/main/res/.DS_Store differ diff --git a/src/main/res/anim/in_from_left.xml b/src/main/res/anim/in_from_left.xml new file mode 100644 index 0000000..396cd1a --- /dev/null +++ b/src/main/res/anim/in_from_left.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/anim/in_from_right.xml b/src/main/res/anim/in_from_right.xml new file mode 100644 index 0000000..fe65b4e --- /dev/null +++ b/src/main/res/anim/in_from_right.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/anim/out_to_left.xml b/src/main/res/anim/out_to_left.xml new file mode 100644 index 0000000..79ea6ef --- /dev/null +++ b/src/main/res/anim/out_to_left.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/anim/out_to_right.xml b/src/main/res/anim/out_to_right.xml new file mode 100644 index 0000000..d4504cf --- /dev/null +++ b/src/main/res/anim/out_to_right.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/src/main/res/drawable-hdpi/launch.png b/src/main/res/drawable-hdpi/launch.png new file mode 100644 index 0000000..9f9f7c3 Binary files /dev/null and b/src/main/res/drawable-hdpi/launch.png differ diff --git a/src/main/res/drawable-xhdpi/.DS_Store b/src/main/res/drawable-xhdpi/.DS_Store new file mode 100644 index 0000000..a49a8d7 Binary files /dev/null and b/src/main/res/drawable-xhdpi/.DS_Store differ diff --git a/src/main/res/drawable-xhdpi/about_logo.png b/src/main/res/drawable-xhdpi/about_logo.png new file mode 100644 index 0000000..3cc3667 Binary files /dev/null and b/src/main/res/drawable-xhdpi/about_logo.png differ diff --git a/src/main/res/drawable-xhdpi/button_blue_long.png b/src/main/res/drawable-xhdpi/button_blue_long.png new file mode 100644 index 0000000..5eba212 Binary files /dev/null and b/src/main/res/drawable-xhdpi/button_blue_long.png differ diff --git a/src/main/res/drawable-xhdpi/checkmark.png b/src/main/res/drawable-xhdpi/checkmark.png new file mode 100644 index 0000000..b147604 Binary files /dev/null and b/src/main/res/drawable-xhdpi/checkmark.png differ diff --git a/src/main/res/drawable-xhdpi/common_add_button.png b/src/main/res/drawable-xhdpi/common_add_button.png new file mode 100644 index 0000000..93988bb Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_add_button.png differ diff --git a/src/main/res/drawable-xhdpi/common_arrow_right.png b/src/main/res/drawable-xhdpi/common_arrow_right.png new file mode 100644 index 0000000..19d5b82 Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_arrow_right.png differ diff --git a/src/main/res/drawable-xhdpi/common_device_lan_offline.png b/src/main/res/drawable-xhdpi/common_device_lan_offline.png new file mode 100644 index 0000000..60c0d0e Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_device_lan_offline.png differ diff --git a/src/main/res/drawable-xhdpi/common_device_lan_online.png b/src/main/res/drawable-xhdpi/common_device_lan_online.png new file mode 100644 index 0000000..f1865b8 Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_device_lan_online.png differ diff --git a/src/main/res/drawable-xhdpi/common_device_remote_offline.png b/src/main/res/drawable-xhdpi/common_device_remote_offline.png new file mode 100644 index 0000000..583c1de Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_device_remote_offline.png differ diff --git a/src/main/res/drawable-xhdpi/common_device_remote_online.png b/src/main/res/drawable-xhdpi/common_device_remote_online.png new file mode 100644 index 0000000..6d7110e Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_device_remote_online.png differ diff --git a/src/main/res/drawable-xhdpi/common_password_hide.png b/src/main/res/drawable-xhdpi/common_password_hide.png new file mode 100644 index 0000000..18eb3bc Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_password_hide.png differ diff --git a/src/main/res/drawable-xhdpi/common_password_show.png b/src/main/res/drawable-xhdpi/common_password_show.png new file mode 100644 index 0000000..553120d Binary files /dev/null and b/src/main/res/drawable-xhdpi/common_password_show.png differ diff --git a/src/main/res/drawable-xhdpi/config_help_button.png b/src/main/res/drawable-xhdpi/config_help_button.png new file mode 100644 index 0000000..37d3840 Binary files /dev/null and b/src/main/res/drawable-xhdpi/config_help_button.png differ diff --git a/src/main/res/drawable-xhdpi/device_none.png b/src/main/res/drawable-xhdpi/device_none.png new file mode 100644 index 0000000..278221e Binary files /dev/null and b/src/main/res/drawable-xhdpi/device_none.png differ diff --git a/src/main/res/drawable-xhdpi/deviceonboarding_airlink_tips.png b/src/main/res/drawable-xhdpi/deviceonboarding_airlink_tips.png new file mode 100644 index 0000000..e58038b Binary files /dev/null and b/src/main/res/drawable-xhdpi/deviceonboarding_airlink_tips.png differ diff --git a/src/main/res/drawable-xhdpi/deviceonboarding_softap_tips.png b/src/main/res/drawable-xhdpi/deviceonboarding_softap_tips.png new file mode 100644 index 0000000..e58038b Binary files /dev/null and b/src/main/res/drawable-xhdpi/deviceonboarding_softap_tips.png differ diff --git a/src/main/res/drawable-xhdpi/devicesharing_user_icon.png b/src/main/res/drawable-xhdpi/devicesharing_user_icon.png new file mode 100644 index 0000000..400a505 Binary files /dev/null and b/src/main/res/drawable-xhdpi/devicesharing_user_icon.png differ diff --git a/src/main/res/drawable-xhdpi/feedbacksupport_selected.png b/src/main/res/drawable-xhdpi/feedbacksupport_selected.png new file mode 100644 index 0000000..dd7eb10 Binary files /dev/null and b/src/main/res/drawable-xhdpi/feedbacksupport_selected.png differ diff --git a/src/main/res/drawable-xhdpi/feedbacksupport_unselected.png b/src/main/res/drawable-xhdpi/feedbacksupport_unselected.png new file mode 100644 index 0000000..55b3d80 Binary files /dev/null and b/src/main/res/drawable-xhdpi/feedbacksupport_unselected.png differ diff --git a/src/main/res/drawable-xhdpi/icon.png b/src/main/res/drawable-xhdpi/icon.png new file mode 100644 index 0000000..3cc3667 Binary files /dev/null and b/src/main/res/drawable-xhdpi/icon.png differ diff --git a/src/main/res/drawable-xhdpi/info_edit.png b/src/main/res/drawable-xhdpi/info_edit.png new file mode 100644 index 0000000..9ad867b Binary files /dev/null and b/src/main/res/drawable-xhdpi/info_edit.png differ diff --git a/src/main/res/drawable-xhdpi/info_edit_cancel.png b/src/main/res/drawable-xhdpi/info_edit_cancel.png new file mode 100644 index 0000000..d5a1e90 Binary files /dev/null and b/src/main/res/drawable-xhdpi/info_edit_cancel.png differ diff --git a/src/main/res/drawable-xhdpi/launch.png b/src/main/res/drawable-xhdpi/launch.png new file mode 100644 index 0000000..c3cb074 Binary files /dev/null and b/src/main/res/drawable-xhdpi/launch.png differ diff --git a/src/main/res/drawable-xhdpi/launch_logo.png b/src/main/res/drawable-xhdpi/launch_logo.png new file mode 100644 index 0000000..61f1c04 Binary files /dev/null and b/src/main/res/drawable-xhdpi/launch_logo.png differ diff --git a/src/main/res/drawable-xhdpi/page_back_button.png b/src/main/res/drawable-xhdpi/page_back_button.png new file mode 100644 index 0000000..3da2151 Binary files /dev/null and b/src/main/res/drawable-xhdpi/page_back_button.png differ diff --git a/src/main/res/drawable-xhdpi/personal_sharing_icon.png b/src/main/res/drawable-xhdpi/personal_sharing_icon.png new file mode 100644 index 0000000..ce366f3 Binary files /dev/null and b/src/main/res/drawable-xhdpi/personal_sharing_icon.png differ diff --git a/src/main/res/drawable-xhdpi/personalcenter_usermanger_icon.png b/src/main/res/drawable-xhdpi/personalcenter_usermanger_icon.png new file mode 100644 index 0000000..aff852a Binary files /dev/null and b/src/main/res/drawable-xhdpi/personalcenter_usermanger_icon.png differ diff --git a/src/main/res/drawable-xhdpi/qrcode_scan_frame.png b/src/main/res/drawable-xhdpi/qrcode_scan_frame.png new file mode 100644 index 0000000..de6cfbf Binary files /dev/null and b/src/main/res/drawable-xhdpi/qrcode_scan_frame.png differ diff --git a/src/main/res/drawable-xhdpi/qrcode_scan_line.png b/src/main/res/drawable-xhdpi/qrcode_scan_line.png new file mode 100644 index 0000000..0749422 Binary files /dev/null and b/src/main/res/drawable-xhdpi/qrcode_scan_line.png differ diff --git a/src/main/res/drawable-xhdpi/right_icon.png b/src/main/res/drawable-xhdpi/right_icon.png new file mode 100644 index 0000000..0b73e0f Binary files /dev/null and b/src/main/res/drawable-xhdpi/right_icon.png differ diff --git a/src/main/res/drawable-xhdpi/thumb.png b/src/main/res/drawable-xhdpi/thumb.png new file mode 100644 index 0000000..0db9afa Binary files /dev/null and b/src/main/res/drawable-xhdpi/thumb.png differ diff --git a/src/main/res/drawable-xhdpi/txt_delete_btn.png b/src/main/res/drawable-xhdpi/txt_delete_btn.png new file mode 100644 index 0000000..7e4821d Binary files /dev/null and b/src/main/res/drawable-xhdpi/txt_delete_btn.png differ diff --git a/src/main/res/drawable-xhdpi/user_login_logo.png b/src/main/res/drawable-xhdpi/user_login_logo.png new file mode 100644 index 0000000..e49b86b Binary files /dev/null and b/src/main/res/drawable-xhdpi/user_login_logo.png differ diff --git a/src/main/res/drawable-xhdpi/user_login_qq.png b/src/main/res/drawable-xhdpi/user_login_qq.png new file mode 100644 index 0000000..0b3b4d8 Binary files /dev/null and b/src/main/res/drawable-xhdpi/user_login_qq.png differ diff --git a/src/main/res/drawable-xhdpi/user_login_wechat.png b/src/main/res/drawable-xhdpi/user_login_wechat.png new file mode 100644 index 0000000..f09cbf0 Binary files /dev/null and b/src/main/res/drawable-xhdpi/user_login_wechat.png differ diff --git a/src/main/res/drawable-xxhdpi/icon.png b/src/main/res/drawable-xxhdpi/icon.png new file mode 100644 index 0000000..3cc3667 Binary files /dev/null and b/src/main/res/drawable-xxhdpi/icon.png differ diff --git a/src/main/res/drawable-xxhdpi/launch.png b/src/main/res/drawable-xxhdpi/launch.png new file mode 100644 index 0000000..80e88e7 Binary files /dev/null and b/src/main/res/drawable-xxhdpi/launch.png differ diff --git a/src/main/res/drawable/alert_bottom_left_shape.xml b/src/main/res/drawable/alert_bottom_left_shape.xml new file mode 100644 index 0000000..bbefd18 --- /dev/null +++ b/src/main/res/drawable/alert_bottom_left_shape.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/alert_bottom_left_shape_gray.xml b/src/main/res/drawable/alert_bottom_left_shape_gray.xml new file mode 100644 index 0000000..a23656b --- /dev/null +++ b/src/main/res/drawable/alert_bottom_left_shape_gray.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/alert_bottom_right_shape.xml b/src/main/res/drawable/alert_bottom_right_shape.xml new file mode 100644 index 0000000..423417b --- /dev/null +++ b/src/main/res/drawable/alert_bottom_right_shape.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/main/res/drawable/alert_bottom_right_shape_gray.xml b/src/main/res/drawable/alert_bottom_right_shape_gray.xml new file mode 100644 index 0000000..ffa8ccc --- /dev/null +++ b/src/main/res/drawable/alert_bottom_right_shape_gray.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/main/res/drawable/alert_bottom_shape.xml b/src/main/res/drawable/alert_bottom_shape.xml new file mode 100644 index 0000000..23bf7da --- /dev/null +++ b/src/main/res/drawable/alert_bottom_shape.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + diff --git a/src/main/res/drawable/alert_shape.xml b/src/main/res/drawable/alert_shape.xml new file mode 100644 index 0000000..1835354 --- /dev/null +++ b/src/main/res/drawable/alert_shape.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/alert_top_shape.xml b/src/main/res/drawable/alert_top_shape.xml new file mode 100644 index 0000000..8751978 --- /dev/null +++ b/src/main/res/drawable/alert_top_shape.xml @@ -0,0 +1,10 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/alert_top_shape_gray.xml b/src/main/res/drawable/alert_top_shape_gray.xml new file mode 100644 index 0000000..2ed4c02 --- /dev/null +++ b/src/main/res/drawable/alert_top_shape_gray.xml @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/border_input_box.xml b/src/main/res/drawable/border_input_box.xml new file mode 100644 index 0000000..ce6f458 --- /dev/null +++ b/src/main/res/drawable/border_input_box.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/border_layer_list.xml b/src/main/res/drawable/border_layer_list.xml new file mode 100644 index 0000000..75970f7 --- /dev/null +++ b/src/main/res/drawable/border_layer_list.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/btn_next_shape_gray.xml b/src/main/res/drawable/btn_next_shape_gray.xml new file mode 100644 index 0000000..674f838 --- /dev/null +++ b/src/main/res/drawable/btn_next_shape_gray.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/main/res/drawable/checkbox_hook_selector.xml b/src/main/res/drawable/checkbox_hook_selector.xml new file mode 100644 index 0000000..2f43081 --- /dev/null +++ b/src/main/res/drawable/checkbox_hook_selector.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/checkbox_laws_selector.xml b/src/main/res/drawable/checkbox_laws_selector.xml new file mode 100644 index 0000000..061b8b4 --- /dev/null +++ b/src/main/res/drawable/checkbox_laws_selector.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/common_page_back_button.xml b/src/main/res/drawable/common_page_back_button.xml new file mode 100644 index 0000000..edcf940 --- /dev/null +++ b/src/main/res/drawable/common_page_back_button.xml @@ -0,0 +1,4 @@ + + + diff --git a/src/main/res/drawable/common_qrcode_button.xml b/src/main/res/drawable/common_qrcode_button.xml new file mode 100644 index 0000000..01d1478 --- /dev/null +++ b/src/main/res/drawable/common_qrcode_button.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/common_setting_more.xml b/src/main/res/drawable/common_setting_more.xml new file mode 100644 index 0000000..e55da18 --- /dev/null +++ b/src/main/res/drawable/common_setting_more.xml @@ -0,0 +1,4 @@ + + + diff --git a/src/main/res/drawable/devicelist_item_selector.xml b/src/main/res/drawable/devicelist_item_selector.xml new file mode 100644 index 0000000..a57286d --- /dev/null +++ b/src/main/res/drawable/devicelist_item_selector.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/main/res/drawable/deviceonboarding_add.xml b/src/main/res/drawable/deviceonboarding_add.xml new file mode 100644 index 0000000..6f2f2be --- /dev/null +++ b/src/main/res/drawable/deviceonboarding_add.xml @@ -0,0 +1,4 @@ + + + diff --git a/src/main/res/drawable/gray_thumb.xml b/src/main/res/drawable/gray_thumb.xml new file mode 100644 index 0000000..1f0a893 --- /dev/null +++ b/src/main/res/drawable/gray_thumb.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/gray_track.xml b/src/main/res/drawable/gray_track.xml new file mode 100644 index 0000000..187810c --- /dev/null +++ b/src/main/res/drawable/gray_track.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/green_thumb.xml b/src/main/res/drawable/green_thumb.xml new file mode 100644 index 0000000..6553a07 --- /dev/null +++ b/src/main/res/drawable/green_thumb.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/green_track.xml b/src/main/res/drawable/green_track.xml new file mode 100644 index 0000000..f0d37fe --- /dev/null +++ b/src/main/res/drawable/green_track.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/ic_list_divider.xml b/src/main/res/drawable/ic_list_divider.xml new file mode 100644 index 0000000..8ebba91 --- /dev/null +++ b/src/main/res/drawable/ic_list_divider.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/img_bg_shape.xml b/src/main/res/drawable/img_bg_shape.xml new file mode 100644 index 0000000..076dc54 --- /dev/null +++ b/src/main/res/drawable/img_bg_shape.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/main/res/drawable/img_bg_shape_white.xml b/src/main/res/drawable/img_bg_shape_white.xml new file mode 100644 index 0000000..170a204 --- /dev/null +++ b/src/main/res/drawable/img_bg_shape_white.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/src/main/res/drawable/key_number_bg.xml b/src/main/res/drawable/key_number_bg.xml new file mode 100644 index 0000000..9bb831b --- /dev/null +++ b/src/main/res/drawable/key_number_bg.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/keyboard_number.xml b/src/main/res/drawable/keyboard_number.xml new file mode 100644 index 0000000..bf12ad0 --- /dev/null +++ b/src/main/res/drawable/keyboard_number.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/keyboard_number_pressed.xml b/src/main/res/drawable/keyboard_number_pressed.xml new file mode 100644 index 0000000..7db75d5 --- /dev/null +++ b/src/main/res/drawable/keyboard_number_pressed.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/redoval.xml b/src/main/res/drawable/redoval.xml new file mode 100644 index 0000000..b6a8537 --- /dev/null +++ b/src/main/res/drawable/redoval.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/round_dot.xml b/src/main/res/drawable/round_dot.xml new file mode 100644 index 0000000..40b7be2 --- /dev/null +++ b/src/main/res/drawable/round_dot.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/shape_button.xml b/src/main/res/drawable/shape_button.xml new file mode 100644 index 0000000..8e1ca15 --- /dev/null +++ b/src/main/res/drawable/shape_button.xml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/shape_button2.xml b/src/main/res/drawable/shape_button2.xml new file mode 100644 index 0000000..2994bb8 --- /dev/null +++ b/src/main/res/drawable/shape_button2.xml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/tabbar_messages.xml b/src/main/res/drawable/tabbar_messages.xml new file mode 100644 index 0000000..cdf76a6 --- /dev/null +++ b/src/main/res/drawable/tabbar_messages.xml @@ -0,0 +1,12 @@ + + + + diff --git a/src/main/res/drawable/tabbar_mydevice.xml b/src/main/res/drawable/tabbar_mydevice.xml new file mode 100644 index 0000000..80d35a5 --- /dev/null +++ b/src/main/res/drawable/tabbar_mydevice.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/tabbar_personal.xml b/src/main/res/drawable/tabbar_personal.xml new file mode 100644 index 0000000..679c169 --- /dev/null +++ b/src/main/res/drawable/tabbar_personal.xml @@ -0,0 +1,9 @@ + + + diff --git a/src/main/res/drawable/thumb.xml b/src/main/res/drawable/thumb.xml new file mode 100644 index 0000000..57fa830 --- /dev/null +++ b/src/main/res/drawable/thumb.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/res/drawable/track.xml b/src/main/res/drawable/track.xml new file mode 100644 index 0000000..da1b10f --- /dev/null +++ b/src/main/res/drawable/track.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/.DS_Store b/src/main/res/layout/.DS_Store new file mode 100644 index 0000000..12d268e Binary files /dev/null and b/src/main/res/layout/.DS_Store differ diff --git a/src/main/res/layout/activity_device_item.xml b/src/main/res/layout/activity_device_item.xml new file mode 100644 index 0000000..b606847 --- /dev/null +++ b/src/main/res/layout/activity_device_item.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/activity_device_shared_message_list.xml b/src/main/res/layout/activity_device_shared_message_list.xml new file mode 100644 index 0000000..33aece4 --- /dev/null +++ b/src/main/res/layout/activity_device_shared_message_list.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/res/layout/activity_gos_about.xml b/src/main/res/layout/activity_gos_about.xml new file mode 100644 index 0000000..62497e6 --- /dev/null +++ b/src/main/res/layout/activity_gos_about.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/activity_gos_addshared.xml b/src/main/res/layout/activity_gos_addshared.xml new file mode 100644 index 0000000..90a93a7 --- /dev/null +++ b/src/main/res/layout/activity_gos_addshared.xml @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/res/layout/activity_gos_airlink_choose_device_workwifi.xml b/src/main/res/layout/activity_gos_airlink_choose_device_workwifi.xml new file mode 100644 index 0000000..7facd31 --- /dev/null +++ b/src/main/res/layout/activity_gos_airlink_choose_device_workwifi.xml @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +