release 715
authorsnickersun <scy@incartech.cn>
Wed, 25 Nov 2020 09:11:49 +0000 (17:11 +0800)
committersnickersun <scy@incartech.cn>
Wed, 25 Nov 2020 09:11:49 +0000 (17:11 +0800)
当网络长时间断开,或者服务器长时间无反应(12次没有响应),同时重置sim卡,重置4G网络。(原理只重置sim)

app/release/ICSer_V715_2011251709_release.apk [moved from app/release/ICSer_V714_2011202205_release.apk with 78% similarity]
app/release/output.json
app/src/main/java/com/enqualcomm/support/CoreService.java
app/src/main/java/com/enqualcomm/support/ICSmsManager.java
app/src/main/java/com/enqualcomm/support/utils/SimSignalUtil.java
app/version_code.properties

similarity index 78%
rename from app/release/ICSer_V714_2011202205_release.apk
rename to app/release/ICSer_V715_2011251709_release.apk
index 81209ef..2a40b34 100644 (file)
Binary files a/app/release/ICSer_V714_2011202205_release.apk and b/app/release/ICSer_V715_2011251709_release.apk differ
index 9f3d060..d1040a2 100644 (file)
@@ -1 +1 @@
-[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":714,"versionName":"2011202205","enabled":true,"outputFile":"ICSer_V714_2011202205_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V714_2011202205_release.apk","properties":{}}]
\ No newline at end of file
+[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":715,"versionName":"2011251709","enabled":true,"outputFile":"ICSer_V715_2011251709_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V715_2011251709_release.apk","properties":{}}]
\ No newline at end of file
index 8d552b6..4c74748 100644 (file)
-package com.enqualcomm.support;\r
-\r
-import android.app.AlarmManager;\r
-import android.app.Notification;\r
-import android.app.PendingIntent;\r
-import android.app.Service;\r
-import android.content.IClipboard;\r
-import android.content.Intent;\r
-import android.media.AudioManager;\r
-import android.os.Handler;\r
-import android.os.IBinder;\r
-\r
-import android.os.Message;\r
-import android.os.Messenger;\r
-import android.os.PowerManager;\r
-import android.os.SystemClock;\r
-import android.widget.Toast;\r
-\r
-import com.enqualcomm.support.adapter.BTHelper;\r
-import com.enqualcomm.support.bean.Contact;\r
-import com.enqualcomm.support.bean.ICLocation;\r
-import com.enqualcomm.support.bean.SleepInfo;\r
-import com.enqualcomm.support.bean.SleepRecord;\r
-import com.enqualcomm.support.service.AntiMonitorService;\r
-import com.enqualcomm.support.utils.CellInfoUtil;\r
-import com.enqualcomm.support.utils.Connection;\r
-import com.enqualcomm.support.utils.DeviceInfoUtil;\r
-import com.enqualcomm.support.utils.ICHttpUtil;\r
-import com.enqualcomm.support.utils.LedUtil;\r
-import com.enqualcomm.support.utils.StorageUtils;\r
-import com.enqualcomm.support.utils.TemperatureUtil;\r
-import com.enqualcomm.support.utils.TimeUtil;\r
-import com.enqualcomm.support.utils.VibrateUtil;\r
-import com.enqualcomm.support.utils.WakeLockUtil;\r
-import com.enqualcomm.support.utils.mqttConnection;\r
-import com.ic.jni.ICJniUtils;\r
-import com.enqualcomm.support.adapter.LBSHelper;\r
-import com.ic.protocols.protocolAPIHelper;\r
-import com.enqualcomm.support.bean.Runtime;\r
-import com.enqualcomm.support.bean.StringMessage;\r
-import com.enqualcomm.support.bean.heartRateStatus;\r
-import com.enqualcomm.support.service.CheckSIM;\r
-import com.enqualcomm.support.service.Deliver;\r
-import com.enqualcomm.support.service.HeartRateManager;\r
-import com.enqualcomm.support.service.KeepAlive;\r
-import com.enqualcomm.support.service.SendChatMessage;\r
-import com.enqualcomm.support.service.SilentManager;\r
-import com.enqualcomm.support.service.UpLoadDataPoints;\r
-import com.enqualcomm.support.service.base.AbstractConnectionService;\r
-import com.enqualcomm.support.service.base.AbstractInvokeHandlerService;\r
-import com.enqualcomm.support.utils.AlarmHelper;\r
-import com.enqualcomm.support.utils.AlarmWakeUp;\r
-import com.enqualcomm.support.utils.BatteryUtil;\r
-import com.enqualcomm.support.utils.ConnectionListener;\r
-import com.enqualcomm.support.utils.ContextProxy;\r
-import com.enqualcomm.support.utils.DBHelper;\r
-import com.enqualcomm.support.utils.FileOutputUtil;\r
-import com.enqualcomm.support.utils.ICLogger;\r
-import com.enqualcomm.support.utils.NettyConnection;\r
-import com.enqualcomm.support.utils.SharPreferenceUtil;\r
-import com.enqualcomm.support.utils.SimSignalUtil;\r
-import com.enqualcomm.support.utils.Util;\r
-\r
-import java.lang.ref.WeakReference;\r
-import chestnut.ui.Toastc;\r
-\r
-import android.content.BroadcastReceiver;\r
-import android.content.Context;\r
-import android.content.IntentFilter;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Random;\r
-import java.util.concurrent.ScheduledThreadPoolExecutor;\r
-import java.util.concurrent.TimeUnit;\r
-\r
-import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;\r
-import static com.enqualcomm.support.Constants.ACTION_ALARM_ADD_DATAPOINTS;\r
-import static com.enqualcomm.support.Constants.ACTION_ALARM_BLE_SCAN;\r
-import static com.enqualcomm.support.Constants.ACTION_ALARM_CHECK_ANTI;\r
-import static com.enqualcomm.support.Constants.ACTION_CHECK_ANTIOFF_EVENT;\r
-import static com.enqualcomm.support.Constants.ACTION_EQC_ALARM;\r
-import static com.enqualcomm.support.Constants.ACTION_HEATR_RATE_START;\r
-import static com.enqualcomm.support.Constants.ACTION_LOCAL_SOS_ACTION;\r
-import static com.enqualcomm.support.Constants.ACTION_LOCATION_ALARM;\r
-import static com.enqualcomm.support.Constants.ACTION_PRACTICE_REPORT_ALARM;\r
-import static com.enqualcomm.support.Constants.ACTION_QUERY_WEATHER;\r
-import static com.enqualcomm.support.Constants.ACTION_SEND_EMEGENCY_LOCATION_START;\r
-import static com.enqualcomm.support.Constants.ACTION_SEND_EMEGENCY_LOCATION_STOP;\r
-import static com.enqualcomm.support.Constants.ANTI_ALARM;\r
-import static com.enqualcomm.support.Constants.HEART_ALARM;\r
-import static com.enqualcomm.support.Constants.KEY_SAVE_STEP_COUNT;\r
-import static com.enqualcomm.support.Constants.KEY_STEP_COUNT;\r
-import static com.enqualcomm.support.Constants.KEY_TEMP_BODY;\r
-import static com.enqualcomm.support.Constants.KEY_TEMP_WRIST;\r
-import static com.enqualcomm.support.Constants.STEP_COUNT_ALARM_ACTION;\r
-import static com.enqualcomm.support.Constants.TEMP_ALARM;\r
-import static com.enqualcomm.support.bean.ICLocation.*;\r
-import static com.ic.protocols.protocolAPIHelper.getTemperatureMSG;\r
-\r
-\r
-public class CoreService extends Service {\r
-\r
-\r
-    private Toastc toast = null;\r
-\r
-    private static CoreService mProtocolServer=null;\r
-    private static LBSHelper lbshelper=null;\r
-\r
-    public static final String ACTION_ALARM = "com.enqualcomm.support.ACTION_ALARM";\r
-\r
-    private static final int GRAY_SERVICE_ID =android.os.Process.myPid();\r
-\r
-    private static final String MY_WAKE_LOCKTAG =CoreService.class.getSimpleName();\r
-\r
-    public static int alarmCycle = 1;\r
-\r
-    public static final int interval = 60000;\r
-\r
-    public static boolean needLocateInAfterHeartBeat=false;\r
-    private static int is_allowed_in_sleep_mode = 1;\r
-\r
-    private static boolean is_in_sleep_mode = false;\r
-\r
-    private static boolean is_wifi_network_ok = false;\r
-    // SPRD: add outdoorMode\r
-    public static final int RINGER_MODE_OUTDOOR = 3;\r
-\r
-    public static Handler mHandler=new Handler();\r
-    private static ICSmsManager smsManager=null;\r
-    public String getServerAlive(){\r
-       return DeviceInfoUtil.getDeviceInfo(runtime);\r
-    }\r
-\r
-    private BroadcastReceiver AtCallbackBroadcastReceiver = new BroadcastReceiver() {\r
-        public void onReceive(Context param1Context, Intent param1Intent) {\r
-            if (param1Intent.getAction().equals("com.eqc.intent.action.callback.at")) {\r
-                String str = param1Intent.getStringExtra("AtResult");\r
-                StringBuilder stringBuilder = new StringBuilder();\r
-                stringBuilder.append("callbackStr =");\r
-                stringBuilder.append(str);\r
-                ICLogger.i(stringBuilder.toString());\r
-                if (str.indexOf("OK") != -1) {\r
-                    String[] arrayOfString = str.split("\"");\r
-                    if (arrayOfString.length > 4) {\r
-                        str = arrayOfString[1];\r
-                        String str1 = arrayOfString[3];\r
-                        Context context = (CoreService.this.runtime.getContextProxy()).context;\r
-                        StringBuilder stringBuilder1 = new StringBuilder();\r
-                        stringBuilder1.append("AT lbsInfo LAC== ");\r
-                        stringBuilder1.append(Integer.valueOf(str, 16));\r
-                        stringBuilder1.append(",CELLID=");\r
-                        stringBuilder1.append(Integer.valueOf(str1, 16));\r
-                        if (Config.LOG_TOFILE) ICLogger.logToFile( "LBS", stringBuilder1.toString());\r
-                    }\r
-                }\r
-            }\r
-        }\r
-    };\r
-\r
-    private BroadcastReceiver TimeChangeBroadcastReceiver = new BroadcastReceiver() {\r
-        public void onReceive(Context param1Context, Intent param1Intent) {\r
-            StringBuilder stringBuilder2 = new StringBuilder();\r
-            stringBuilder2.append("broadcastReceiver  alarmCycle action==");\r
-            stringBuilder2.append(param1Intent.getAction());\r
-            if (Config.LOG_TOFILE) ICLogger.logToFile( "alarmCycle", stringBuilder2.toString());\r
-            StringBuilder stringBuilder1 = new StringBuilder();\r
-            stringBuilder1.append("时间变化");\r
-            stringBuilder1.append(param1Intent.getAction()+stringBuilder2.toString());\r
-            ICLogger.i(stringBuilder1.toString());\r
-\r
-            //只有需要确定绝对时间点启动的Alarm需要重置,相对时间点的Alarm不需要重置。防止永远不能正常登陆。\r
-            setSleepAlarm();\r
-            setWakeAlarm();\r
-//            setHeartAlarm();\r
-//           setHeartRateDetectAlarm(runtime.getPpgTestCycle());\r
-            setWeatherAlarm();\r
-            runtime.getContextProxy().sendBroadcast("com.enqualcomm.support.ACTION_ALARM_ALARM_CHANGE",runtime); //更新Alarm\r
-           // setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-            if (cmcm_call_eiot_into_powersave_mode() == 0)\r
-                AlarmWakeUp.isNeedWakeUpAlarm(runtime);\r
-        }\r
-    };\r
-    private BroadcastReceiver broadcastSOSReceiver = new BroadcastReceiver() {\r
-        public void onReceive(Context param1Context, Intent param1Intent) {\r
-\r
-            StringBuilder stringBuilder2 = new StringBuilder();\r
-            stringBuilder2.append("broadcastReceiver  action==");\r
-            stringBuilder2.append(param1Intent.getAction());\r
-            ICLogger.i(stringBuilder2.toString());\r
-\r
-            if (ACTION_SEND_EMEGENCY_LOCATION_START.equals(param1Intent.getAction())){\r
-                runtime.getLocationInstance().setWorkingMod(EMERGNECY_MOD);\r
-                //runtime.setPpgTestCycle(1);\r
-                setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-\r
-                //触发一次心率检测\r
-                setHeartRateDetectAlarm(1);\r
-\r
-\r
-                setEmegencyLocationSTOPAlarm(5);\r
-            }else if (ACTION_LOCAL_SOS_ACTION.endsWith(param1Intent.getAction())){\r
-\r
-\r
-                VibrateUtil.getInstance(runtime.getContextProxy().context).VibrateOn(true);\r
-//               if( param1Intent.getIntExtra("type", 1) == 1) {\r
-                boolean needHRSTestOnSOS = Util.getSystemProperties("persist.sys.needHRSOnSOS","false").equals("true");\r
-                if(needHRSTestOnSOS) {\r
-                    //触发一次心率检测\r
-                    setHeartRateDetectAlarm(1);\r
-                }\r
-                    runtime.setAlarmType(Runtime.AlarmType.ALARM_SOS);\r
-                    //trigger AP10 报警定位\r
-                     ICLogger.i("triggerSOSLocationProcess ");\r
-                    LocationClient.getInstance().triggerSOSLocationProcess();\r
-//                    Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(runtime));\r
-\r
-                    //开启紧急定位模式,GPS 优先1分钟一次定位,持续5分钟\r
-                    runtime.getLocationInstance().setWorkingMod(EMERGNECY_MOD);\r
-                    setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-\r
-                    //SOS模式,心率测试1分钟一次,持续5分钟\r
-                    if(needHRSTestOnSOS) {\r
-                        //只触发一次心率检测\r
-                        setHeartRateDetectAlarm(1);\r
-                    }\r
-                    //设置5分钟后结束紧急定位模式\r
-                   setEmegencyLocationSTOPAlarm(5);\r
-\r
-\r
-                   if(Config.SOSNoNeedDial==false) {\r
-                       //50ms后开始拨打电话\r
-                       mHandler.postDelayed(mTriggerSOSCALLThread,500);\r
-                   }\r
-            }else if (ACTION_QUERY_WEATHER.equals(param1Intent.getAction())) {\r
-\r
-                ICLogger.i("ACTION_QUERY_WEATHER ");\r
-                connection.send(protocolAPIHelper.getWeatherMSG(runtime));\r
-                }\r
-        }\r
-    };\r
-\r
-    private TriggerSOSCALLThread mTriggerSOSCALLThread=new TriggerSOSCALLThread();\r
-\r
-    private  class TriggerSOSCALLThread implements  Runnable{\r
-\r
-        @Override\r
-        public void run() {\r
-            trigger_SOS_Call();\r
-        }\r
-    }\r
-    private void trigger_SOS_Call(){\r
-        try {\r
-            Intent intent = new Intent("com.eqc.shutdown_sos");\r
-            intent.putExtra("type",1);\r
-            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
-            this.startActivity(intent);\r
-        }catch (Exception e){\r
-            e.printStackTrace();\r
-        }\r
-    }\r
-    private  Runnable mupdatePracticeData=new Runnable(){\r
-        @Override\r
-        public void run() {\r
-            //ICHttpUtil.uploadData(Runtime.healthInfo.getBufferDataStr(),runtime,TimeUtil.getSystemTime2(),null);\r
-            Deliver.sendLocationMSG(protocolAPIHelper.getPRACTICE());\r
-            //发送过后重置\r
-            Runtime.healthInfo.resetBuffer();\r
-        }\r
-    };\r
-\r
-    private BroadcastReceiver broadcastPracticeCMDReceiver = new BroadcastReceiver() {\r
-        public void onReceive(Context param1Context, Intent param1Intent) {\r
-            if(param1Intent.getAction().equals(Constants.ACTION_START_PRACTISE))\r
-            {\r
-                int cmd=param1Intent.getIntExtra(Constants.KeyPractice,0);\r
-                if (cmd==1){\r
-                    //开始自由锻炼\r
-                    Runtime.practising=true;\r
-                    Util.setSystemProperties( Config.KeyPractiseState,"true");\r
-                    Runtime.healthInfo.reset();\r
-                    Runtime.healthInfo.resetBuffer();\r
-                    setPracticeAlarm();\r
-\r
-                }else{\r
-                    //停止自由锻炼,恢复正常\r
-                    Runtime.practising=false;\r
-                    Util.setSystemProperties( Config.KeyPractiseState,"false");\r
-                    HeartRateManager.stopPPGtest();\r
-\r
-                    //最后检测是否还有数据需要发送\r
-                    if(Runtime.healthInfo.check_info_item_finished()){\r
-                        Runtime.healthInfo.appendBuffer(Runtime.healthInfo.getHealthInfoString());\r
-                        Runtime.healthInfo.reset();\r
-                     }\r
-                    if(Runtime.healthInfo.getInfoCount()>=0){\r
-                        //超过30次发送数据给服务器\r
-                        ICLogger.i("自由锻炼结束,发送数据给服务器 "+Runtime.healthInfo.getBufferData().length);\r
-                        mHandler.post(mupdatePracticeData);\r
-                    }\r
-\r
-                }\r
-            }\r
-        }\r
-    };\r
-\r
-    private static class ServerHandler implements ConnectionListener {\r
-        private final WeakReference<CoreService> mReference;\r
-\r
-        ServerHandler(CoreService param1CoreService) { this.mReference = new WeakReference(param1CoreService); }\r
-\r
-        @Override\r
-        public void onConnectionClose(String errorName) {\r
-            CoreService coreService = (CoreService)this.mReference.get();\r
-            if (coreService == null)\r
-                return;\r
-            ICLogger.i("onConnectionClose++ retry to connect again!  Close Error "+errorName);\r
-            coreService.connectionServiceChain.processConnectionClose(coreService.connection, coreService.runtime,errorName);\r
-        }\r
-        @Override\r
-        public void onConnectionOpen() {\r
-            CoreService coreService = (CoreService)this.mReference.get();\r
-            if (coreService == null)\r
-                return;\r
-            coreService.connectionServiceChain.processConnectionOpen(coreService.connection, coreService.runtime);\r
-            ICLogger.i("onConnectionOpen");\r
-        }\r
-\r
-        public void onReceive(StringMessage param1StringMessage) {\r
-\r
-            CoreService coreService = (CoreService)this.mReference.get();\r
-            ICLogger.i("onReceive " +param1StringMessage.cmd() +" coreService " + coreService  );\r
-            if (coreService == null)\r
-                return;\r
-            coreService.connectionServiceChain.processServerResponse(param1StringMessage, coreService.connection, coreService.runtime);\r
-            coreService.locationClient.onReceive(param1StringMessage);\r
-        }\r
-    }\r
-    Connection connection = null;\r
-    AbstractConnectionService connectionServiceChain;\r
-\r
-    AbstractInvokeHandlerService invokeHandlerServiceChain;\r
-\r
-    private boolean isBinded = false;\r
-\r
-    private AntiMonitorService antiservice;\r
-    LocationClient locationClient;\r
-\r
-    private Deliver mDeliver;\r
-\r
-    private boolean mHaveSetWeatherAlarm;\r
-\r
-    private KeepAlive mKeepAlive;\r
-\r
-    final Messenger mMessenger = new Messenger(new RequestHandler(this));\r
-\r
-\r
-    private SimSignalUtil mSignalUtil;\r
-\r
-    private BatteryUtil batteryUtil;\r
-    private long mWeatherTime;\r
-\r
-    Runtime runtime;\r
-\r
-    private BroadcastReceiver screenOnReceiver = new BroadcastReceiver() {\r
-        public void onReceive(Context param1Context, Intent param1Intent) {\r
-\r
-            if ("android.intent.action.SCREEN_ON".equals(param1Intent.getAction())) {\r
-                StringBuilder var3 = new StringBuilder();\r
-                var3.append("screen on wake is_wifi_network_ok=");\r
-                var3.append(CoreService.is_wifi_network_ok);\r
-                ICLogger.i(var3.toString());\r
-                //检测电池电量 并上报低电报警\r
-                batteryUtil.getBatteryLevel(param1Context);\r
-                if (CoreService.is_in_sleep_mode) {\r
-\r
-                    /*屏幕亮起时,如果在sleep模式(夜晚的那个睡眠模式,非系统休眠,暂时没实现,还不会跑到这里),则唤醒各个进程*/\r
-                    CoreService.is_in_sleep_mode = false;\r
-                    CoreService.is_allowed_in_sleep_mode = 0;\r
-                    if (CoreService.this.mKeepAlive != null) {\r
-                        CoreService.this.mKeepAlive.setSleepMode(false);\r
-                    }\r
-\r
-                    CoreService.this.wakeUpFromSleep();\r
-                }\r
-\r
-\r
-                //为了保证唤醒时各个状态及时更新到服务器,发送一个同步心跳包,这样用户体验更好\r
-                CoreService.this.locationClient.updateStepCount();\r
-\r
-                mHandler.postDelayed(mRetryConnectSrvThread,500);\r
-\r
-\r
-                if (CoreService.is_wifi_network_ok) {\r
-                    CoreService.is_wifi_network_ok = false;\r
-                    /*屏幕亮起时,如果wifi用户设置是开启的,则开启wifi*/\r
-//                    ICLogger.i("turnOnWifiForConnect");\r
-//                    if (!Util.isWifiIsOpen(runtime.getContextProxy().context,runtime))\r
-//                        Util.turnOnWifiForConnect(runtime.getContextProxy().context, runtime);\r
-                }\r
-            } else if ("android.intent.action.SCREEN_OFF".equals(param1Intent.getAction()) && Util.isWifiIsOpen(runtime.getContextProxy().context,runtime)) {\r
-               // CoreService.is_wifi_network_ok = true;\r
-                if (!runtime.isNoTurnOffWifiOnScreenOff()) {\r
-                    //不关闭wifi when ScreenOff\r
-                    ICLogger.i("turnOffWifiForConnect");\r
-//                    if (Util.isWifiIsOpen(runtime.getContextProxy().context,runtime))\r
-//                        Util.turnOffWifiForSleep(runtime.getContextProxy().context, runtime);\r
-                }\r
-            }\r
-        }\r
-    };\r
-\r
-    private Runnable mRetryConnectSrvThread=new Runnable(){\r
-        @Override\r
-        public void run() {\r
-            if (connection.isServerConnected()&& runtime.isServerProtocolConnected()) {\r
-                mKeepAlive.onHeartAlarm(connection, runtime);\r
-            }else{\r
-                ICLogger.i("check 发送心跳包时,如果发现服务器没有响应,或者socket连接,则重新尝试连接服务器!");\r
-                connection.disconnectServer();\r
-                startConnectionRetryTimer();\r
-            }\r
-        }\r
-    };\r
-\r
-    private int startAlarmCount = 0;\r
-\r
-    UpLoadDataPoints upLoadDataPoints;\r
-\r
-\r
-    private AbstractConnectionService getConnectionServiceChain() {\r
-//        Initialize initialize = new Initialize();\r
-        CheckSIM checkSIM = new CheckSIM();\r
-        this.mKeepAlive = new KeepAlive();\r
-        this.mDeliver = new Deliver(this.connection,this.runtime);\r
-//        initialize.setNext(checkSIM);\r
-        checkSIM.setNext(this.mKeepAlive);\r
-        this.mKeepAlive.setNext(this.mDeliver);\r
-        return checkSIM;\r
-    }\r
-\r
-\r
-\r
-    private AbstractInvokeHandlerService getInvokeHandlerServiceChain() {\r
-        ICLogger.i("getInvokeHandlerServiceChain");\r
-        SendChatMessage sendChatMessage = new SendChatMessage();\r
-        HeartRateManager heartRateManager= new HeartRateManager(this.runtime,this.connection);\r
-        antiservice = new AntiMonitorService();\r
-        SilentManager silentManager = SilentManager.getInstance();// new SilentManager();\r
-        sendChatMessage.setNext(heartRateManager);\r
-        heartRateManager.setNext(silentManager);\r
-        silentManager.setNext(antiservice);\r
-        return sendChatMessage;\r
-    }\r
-\r
-    private void resetStepCount(){\r
-        if ( ICJniUtils.isPedometerEnabled() == 0)ICJniUtils.enablePedometer();\r
-        ICJniUtils.resetStepCount();\r
-        SharPreferenceUtil.setPrefInt(this, KEY_STEP_COUNT, 0);\r
-        SharPreferenceUtil.setPrefInt(this, KEY_SAVE_STEP_COUNT, 0);\r
-        ICLogger.i("Reset StepCount , "+ICJniUtils.getStepCount());\r
-        this.runtime.setSaveStepCount(0);\r
-        this.runtime.setTotalStepCount(0);\r
-    }\r
-    private void loadStepCount() {\r
-        int i = SharPreferenceUtil.getPrefInt(this, KEY_STEP_COUNT, 0);\r
-        int j = SharPreferenceUtil.getPrefInt(this, KEY_SAVE_STEP_COUNT, 0);\r
-        if ( ICJniUtils.isPedometerEnabled() == 0)ICJniUtils.enablePedometer();\r
-        //ICJniUtils.recoverStepCount();\r
-        if (ICJniUtils.getStepCount()>i){\r
-            i=ICJniUtils.getStepCount();\r
-        }\r
-        this.runtime.setSaveStepCount(j);\r
-        this.runtime.setTotalStepCount(i);\r
-        runtime.setLastStepCountForBT(runtime.getTotalStepCount());\r
-        runtime.setLastStepCount(runtime.getTotalStepCount());\r
-    }\r
-    public void saveStepCount(){\r
-        int i = runtime.getTotalStepCount();\r
-        int j = runtime.getSaveStepCount();\r
-        SharPreferenceUtil.setPrefInt(this, KEY_STEP_COUNT, i);\r
-        SharPreferenceUtil.setPrefInt(this, KEY_SAVE_STEP_COUNT, j);\r
-        //ICJniUtils.saveStepCount();\r
-    }\r
-    private void setCleanStepCountAlarm() {\r
-        /*一天清零一次 计步*/\r
-//        AlarmHelper.setCleanStepCountAlarm(this, 23, 59, STEP_COUNT_ALARM_ACTION);\r
-        AlarmHelper.setCleanStepCountAlarm(this, 0, 0, STEP_COUNT_ALARM_ACTION);\r
-    }\r
-\r
-    private void setSleepAlarm() {\r
-        /*每5分左右 休眠*/\r
-//        AlarmHelper.setRealTimeAlarm(this, 5, SLEEP_ALARM);\r
-    }\r
-\r
-    private void setWakeAlarm() {\r
-\r
-//        /*每1 左右 唤醒自己*/\r
-//        Context context=runtime.getContextProxy().context;\r
-//        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);\r
-//        Intent intent = new Intent(context, com.enqualcomm.support.CoreService.class);\r
-//        intent.setAction(WAKE_ALARM);\r
-//        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);\r
-//        alarmManager.cancel(pendingIntent);\r
-//        long l = SystemClock.elapsedRealtime();\r
-//        StringBuilder stringBuilder = new StringBuilder();\r
-//        stringBuilder.append("SDK_INT=");\r
-//        stringBuilder.append(Build.VERSION.SDK_INT);\r
-//\r
-//        ICLogger.i(stringBuilder.toString());\r
-//\r
-//        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, l + (1 * 60 * 1000), pendingIntent);\r
-\r
-\r
-    }\r
-\r
-    private void setWeatherAlarm() {\r
-        /*每天6点20分左右 更新一次 weather*/\r
-//        AlarmHelper.setTimeAlarm(this, 6, (new Random()).nextInt(40) + 20, WEATHER_ALARM);\r
-    }\r
-\r
-\r
-    private void setPracticeAlarm() {\r
-\r
-        ICLogger.i("setPracticeAlarm "+Runtime.practice_cycle+ " seconds!");\r
-        //只有周期大于1才有效,否则就等于单次测量\r
-        if (Runtime.practice_cycle>1)\r
-            AlarmHelper.setRealTimeAlarmInSeconds(runtime.getContextProxy().context,Runtime.practice_cycle,Constants.ACTION_PRACTICE_REPORT_ALARM);\r
-        mHandler.post(mdoPracticeCheck);\r
-    }\r
-    private Runnable mdoPracticeCheck=new Runnable(){\r
-        @Override\r
-        public void run() {\r
-            //获取并设置当前步数\r
-            ICLogger.i("自由锻炼中,设置步数 "+runtime.getTotalStepCount());\r
-            Runtime.healthInfo.setStepCount(runtime.getTotalStepCount());\r
-            //开启定位\r
-            //        locationClient.triggerLocationProcess();\r
-            //开启测温\r
-            if(runtime.check_stat_do_temp_test())\r
-                TemperatureUtil.DoTempTest();\r
-\r
-            //开启测量PPG\r
-            if(runtime.check_stat_do_ppg_test())\r
-                HeartRateManager.triggerPPGtest();\r
-\r
-        }\r
-    };\r
-\r
-    private void checkconnection(){\r
-\r
-        if (!this.connection.isServerConnected())\r
-        {\r
-            startConnectionRetryTimer();\r
-        }\r
-    }\r
-    private void wakeUpFromSleep() {\r
-        this.startAlarmCount = 0;\r
-//        alarmCycle = 1;\r
-//        setAlarm(alarmCycle);\r
-//        runtime.getLocationInstance().setLocation_cycle(1);\r
-\r
-        //每次唤醒都强制设置一次定位alarm和定位一次。\r
-        setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-\r
-        this.runtime.getContextProxy().sendBroadcast(ACTION_EQC_ALARM, this.runtime);\r
-        this.connection.open();\r
-        checkconnection();\r
-        this.locationClient.onAlarm(getWakeLock(alarmCycle));\r
-        this.connectionServiceChain.processAlarmClock(this.connection, this.runtime);\r
-        this.invokeHandlerServiceChain.processAlarmClock(this.connection, this.runtime);\r
-        if (SystemClock.elapsedRealtime() - this.mWeatherTime > 60000L && this.mHaveSetWeatherAlarm) {\r
-            setWeatherAlarm();\r
-            this.mHaveSetWeatherAlarm = false;\r
-        }\r
-        Toast.makeText((this.runtime.getContextProxy()).context, "从深度睡眠中切换模式,联网中", Toast.LENGTH_SHORT).show();\r
-    }\r
-\r
-    public int cmcm_call_eiot_into_powersave_mode() { return 0; }\r
-\r
-\r
-    public PowerManager.WakeLock getWakeLock(int paramInt) {\r
-         PowerManager.WakeLock wakeLock = ((PowerManager)(this.runtime.getContextProxy()).context.getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MY_WAKE_LOCKTAG);\r
-//        wakeLock.acquire(paramInt*60*1000L);\r
-        wakeLock.acquire(3000L);\r
-        return wakeLock;\r
-    }\r
-\r
-    public IBinder onBind(Intent paramIntent) {\r
-        return this.mMessenger.getBinder();\r
-    }\r
-\r
-\r
-\r
-    public Runtime getRuntime(){\r
-        return runtime;\r
-    }\r
-    public Connection getConnection(){\r
-        return connection;\r
-    }\r
-    private static boolean server_starting=true;\r
-    @Override\r
-    public void onCreate() {\r
-\r
-        server_starting=true;\r
-        log("初始化网络协议服务");\r
-        mProtocolServer=this;\r
-        java.lang.Runtime.getRuntime().addShutdownHook(new Thread(){\r
-            @Override\r
-            public void run() {\r
-                super.run();\r
-                //设置断网状态\r
-                ICLogger.i("shutdown !");\r
-                Util.setSystemProperties("persist.sys.server_connected","false");\r
-            }\r
-        });\r
-        this.runtime = new Runtime();\r
-        this.runtime.setFileDir(getFilesDir());\r
-        this.runtime.setCacheDir(getExternalCacheDir());\r
-        this.runtime.setDBHelper(new DBHelper(getContentResolver(), this));\r
-        this.runtime.setContextProxy(new ContextProxy(this));\r
-        this.runtime.setLbsHelper(new LBSHelper(this,this.runtime.getContextProxy().getWifiManager(), this.runtime));\r
-\r
-        this.runtime.setHRS(new heartRateStatus());\r
-        this.runtime.setUseQueue(true);\r
-        this.runtime.initDnsUtil(ICApplication.getInstance().getApplicationContext());\r
-\r
-\r
-        if (Config.protocol_no==Config.PROTOCOL_MQTT)\r
-        {\r
-            connection = new mqttConnection(new ServerHandler(this), runtime);\r
-        }else {\r
-            connection = new NettyConnection(new ServerHandler(this), runtime);\r
-        }\r
-        this.connectionServiceChain = getConnectionServiceChain();\r
-        this.invokeHandlerServiceChain = getInvokeHandlerServiceChain();\r
-//        if (cmcm_call_eiot_into_powersave_mode() == 1) {\r
-//            ICLogger.i("1 into powersave return");\r
-//            return;\r
-//        }\r
-\r
-        smsManager= new ICSmsManager(runtime);\r
-\r
-        //保证获取正确的计步数据及其他参数初始化\r
-        loadStepCount();\r
-\r
-        if (Config.logBootDate(this)){\r
-            resetStepCount();\r
-        }\r
-\r
-\r
-        //初始化消息相关配置\r
-        Config.LoadMessageConfigs();\r
-\r
-        if (Config.custom_name.equals("H88")) {\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);\r
-            if (Config.getConfigInitFlag(this) == 0) {\r
-                Config.setLocationMode(this, CUSTOM_MOD8_GPS);\r
-                Config.setLocationCycle(this, 3600);\r
-                Config.setPPGTestCycle(this, 60);\r
-                Config.setTemperatureTestCycle(runtime, 60 * 60);\r
-                Config.setConfigInitFlag(this, 1);\r
-            }\r
-        }else if (Config.custom_name.equals("l004")) {\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_CUTOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ILLEGAL_CUTOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOCK_WATCH,true);\r
-\r
-            if (Config.getConfigInitFlag(this) == 0) {\r
-                Config.setLocationMode(this, CUSTOM_MOD8_GPS);\r
-                Config.setLocationCycle(this, 600);\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-\r
-            }\r
-        }else if (Config.custom_name.equals("YQ") || Config.custom_name.equals("YQ_EN")) {\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_CUTOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ILLEGAL_CUTOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOCK_WATCH,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_UNREADMSG,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_MSGREAD,true);\r
-\r
-            if (Config.getConfigInitFlag(this) == 0) {\r
-                Config.setLocationMode(this, NORMAL_MOD);\r
-                Config.setLocationCycle(this, 15*60);\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-\r
-            }\r
-        }else if (Config.custom_name.equals("AK")) {\r
-\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_SOS,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOWBATTERY,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);\r
-            Config.enableSleep=true;\r
-\r
-            if (Config.getConfigInitFlag(this)==0) {\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-\r
-//                int contactcount=runtime.getDbHelper().getContactCount(getContentResolver());\r
-//                ICLogger.i("=====Contact count "+contactcount);\r
-//                if(contactcount==0){ //如果没有SOS\r
-//                    ICLogger.i("=====add SOS 07522312120 ");\r
-//                    ArrayList<Contact> contactArray=new ArrayList<Contact>();\r
-//                    contactArray.add(new Contact(Contact.CATEGORY_SOS, "sos1", "07522312120"));\r
-//                    runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);\r
-//                }\r
-            }\r
-        }else if (Config.custom_name.equals("YT")) {\r
-\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_SOS,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOWBATTERY,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);\r
-            Config.enableSleep=true;\r
-\r
-            if (Config.getConfigInitFlag(this)==0) {\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-\r
-                int contactcount=runtime.getDbHelper().getContactCount(getContentResolver());\r
-                ICLogger.i("=====Contact count "+contactcount);\r
-                if(contactcount==0){ //如果没有SOS\r
-                    ICLogger.i("=====add hotline 96885 ");\r
-                    ArrayList<Contact> contactArray=new ArrayList<Contact>();\r
-                    contactArray.add(new Contact(Contact.CATEGORY_CALL, this.getResources().getString(R.string.hotline), "96885"));\r
-                    runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);\r
-                }\r
-            }\r
-        }else if (Config.custom_name.equals("SGL")) { //C5项目\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ESCAPE,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_CUTOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ILLEGAL_CUTOFF,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOCK_WATCH,true);\r
-            Config.forceMoveCheck = false; //对定位不进行运动检测。\r
-            if (Config.getConfigInitFlag(this)==0) {\r
-                Config.setLocationMode(this, CUSTOM_MOD8_GPS);\r
-//                Config.setLocationMode(this, CUSTOM_MOD8_WIFI);\r
-                Config.setLocationCycle(this, 5*60);\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-\r
-//                int contactcount=runtime.getDbHelper().getContactCount(getContentResolver());\r
-//                ICLogger.i("=====Contact count "+contactcount);\r
-//                if(contactcount==0){ //如果没有SOS\r
-//                    ICLogger.i("=====add SOS 07522312120 ");\r
-//                    ArrayList<Contact> contactArray=new ArrayList<Contact>();\r
-//                    contactArray.add(new Contact(Contact.CATEGORY_SOS, "sos1", "07522312120"));\r
-//                    runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);\r
-//                }\r
-            }\r
-        }else if (Config.custom_name.equals("L02") || Config.custom_name.equals("L03")||Config.custom_name.equals("L05")) { //L02\r
-            Config.forceMoveCheck = false; //即爱对gps不进行运动检测,此变量专门为了给其他协议进行强制运动检测用的。\r
-            if (Config.getConfigInitFlag(this) == 0) {\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-            }\r
-\r
-        }else if (Config.custom_name.equals("VitracK")){\r
-\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_SOS,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOWBATTERY,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);\r
-            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);\r
-            Config.enableSleep=false;\r
-            if (Config.getConfigInitFlag(this)==0) {\r
-                Config.setLocationMode(this, CUSTOM_MOD8_GPS);\r
-                Config.setLocationCycle(this, 30*60);\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-            }\r
-\r
-        }else{\r
-\r
-            if (Config.getConfigInitFlag(this)==0) {\r
-                Config.setPPGTestCycle(this, 0);\r
-                Config.setTemperatureTestCycle(runtime, 0);\r
-                Config.setConfigInitFlag(this, 1);\r
-            }\r
-        }\r
-\r
-        Config.dumpAlarmConfig();\r
-        //A9专用变量 初始化剪断,脱腕报警开关(这个开关是界面提示显示用的,上面的Config.ConfigAlarm 是上报服务器消息的开关)\r
-        runtime.setNeddReportCutoff(Config.getNeedCutOff(this));\r
-        runtime.setNeedAntioff(Config.getNeedAntiOff(this));\r
-\r
-\r
-\r
-        Config.setHeartBeatCycle(this,5); //临时设置为3分钟,给L03测试用。测试断线问题未解决,取消测试。\r
-        //初始化ServerHeartBeat Cycle\r
-        Config.loadHearBeatSetting(runtime);\r
-        //初始化PPG,LocationMod,LocationCycle\r
-        Config.loadModCycleSettings(runtime);\r
-        //初始化IP\r
-        Config.loadCustomServerAddr(this);\r
-        Config.loadServerSettings(runtime);\r
-\r
-        //读取Alarm环境配置,项目不需要的Alarm不要发送, 目前环境变量配置优先。默认值会被覆盖。\r
-        Config.loadAlarmConfig();\r
-\r
-        Config.enable_NTP_Server(this,!Config.disable_ntp_server);\r
-\r
-\r
-        //初始化温度测试相关参数\r
-        //runtime.temperature_adjustValue= TemperatureUtil.getTempAdjustValue();\r
-        Config.loadTemperatureSettings(runtime);\r
-\r
-\r
-        //加载存储的健康数据校准值\r
-        Config.loadPPG_BPH_BPL_SPO2_adjustvalue(this,runtime);\r
-\r
-        this.connectionServiceChain.processAttach(this.connection, this.runtime);\r
-        this.invokeHandlerServiceChain.processAttach(this.connection, this.runtime);\r
-//        setAlarm(alarmCycle);\r
-\r
-\r
-//        if (Config.LOG_TOFILE)  FileOutputUtil.fileOutput(runtime.getCacheDir(), "log", "初始化网络协议服务");\r
-        this.locationClient = new LocationClient(this.connection, this.runtime);\r
-        this.connection.open();\r
-\r
-        //启动inner Service\r
-        startService(new Intent(this, InnerService.class));\r
-\r
-\r
-        this.locationClient.init();\r
-\r
-\r
-        //设置本service为前台运行,不被会被清理\r
-        Notification notification = new Notification();\r
-        notification.flags = Notification.FLAG_ONGOING_EVENT;\r
-        notification.flags |= Notification.FLAG_NO_CLEAR;\r
-        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;\r
-        startForeground(GRAY_SERVICE_ID, notification);\r
-\r
-        //注册接收  时间和tiimezone 变更消息\r
-        IntentFilter intentFilter = new IntentFilter();\r
-        intentFilter.addAction("android.intent.action.TIME_SET");\r
-        intentFilter.addAction("android.intent.action.TIMEZONE_CHANGED");\r
-        registerReceiver(this.TimeChangeBroadcastReceiver, intentFilter);\r
-\r
-        //注册接收 screen on/off 消息\r
-        intentFilter = new IntentFilter();\r
-        intentFilter.addAction("android.intent.action.SCREEN_ON");\r
-        intentFilter.addAction("android.intent.action.SCREEN_OFF");\r
-        (this.runtime.getContextProxy()).context.registerReceiver(this.screenOnReceiver, intentFilter);\r
-\r
-        //注册接收  AT指令结果返回消息\r
-        intentFilter = new IntentFilter();\r
-        intentFilter.addAction("com.eqc.intent.action.callback.at");\r
-        registerReceiver(this.AtCallbackBroadcastReceiver, intentFilter);\r
-\r
-        //添加SOSMSG 接收\r
-        intentFilter = new IntentFilter();\r
-        intentFilter.addAction(ACTION_QUERY_WEATHER);\r
-        intentFilter.addAction(ACTION_SEND_EMEGENCY_LOCATION_START);\r
-        intentFilter.addAction(ACTION_LOCAL_SOS_ACTION);\r
-        registerReceiver(broadcastSOSReceiver,intentFilter);\r
-\r
-        //添加自由锻炼 接收\r
-        intentFilter = new IntentFilter();\r
-        intentFilter.addAction(Constants.ACTION_START_PRACTISE);\r
-        registerReceiver(broadcastPracticeCMDReceiver,intentFilter);\r
-\r
-        //初始化Sim信号\r
-        this.mSignalUtil = SimSignalUtil.getInstance(this);\r
-\r
-        //初始化 电池电量监控工具(内部注册接收电池变化)\r
-        batteryUtil = new BatteryUtil(this.runtime,connection);\r
-\r
-        //保证发送心跳时提前获取BatLevel数据\r
-        int batlevel=batteryUtil.getBatteryLevel(this);\r
-        runtime.setBattery(String.format("%03d",batlevel));\r
-        runtime.setBattery(batlevel);\r
-        ICLogger.i("Battery get from api "+batlevel);\r
-\r
-\r
-        boolean charging = batteryUtil.isPowerConnected(this);\r
-        runtime.setPowerConnected(charging);\r
-        ICLogger.i("Charging  "+charging);\r
-//        LedUtil.setRedLedOn(false);\r
-        if (Config.isL03Tracker){\r
-\r
-            if (runtime.isPowerConnected())         {\r
-                LedUtil.setRedLedOn(true);\r
-            }else{\r
-                LedUtil.setRedLedOn(false);\r
-            }\r
-        }\r
-        //api直接获取batterylevel取消注册 receiver, 需要重新注册一下。\r
-\r
-        batteryUtil.registerBroadReceiver();\r
-\r
-\r
-        //设置计步清零时间。\r
-        setCleanStepCountAlarm();\r
-\r
-        //设置睡眠时间(开始睡眠监控)\r
-        setSleepAlarm();\r
-        //设置起床时间(停止睡眠监控)\r
-        setWakeAlarm();\r
-\r
-\r
-        //网络协议心跳时间\r
-        setHeartAlarm();\r
-\r
-        //设置心率检测频率\r
-        setHeartRateDetectAlarm(runtime.getPpgTestCycle()); //3分钟一次\r
-\r
-        //获取天气时间\r
-        setWeatherAlarm();\r
-\r
-\r
-        //获取定位时间\r
-        needLocateInAfterHeartBeat=true;\r
-        setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-\r
-        //设置温度测量间隔时间\r
-\r
-        setTempAlarm();\r
-\r
-\r
-        //初始化佩戴检测\r
-        runtime.anti_test_cycle=Config.getCheckAntiPolingCycle(this);\r
-        if( runtime.anti_test_cycle>0){\r
-         //   setAntiAlarm();\r
-        }\r
-\r
-        //初始化蓝牙检测\r
-        runtime.bleInfo.bleScanCycle=Config.getBleScanCycle(this);\r
-        if(Config.BLEScanProtocol==1 && runtime.bleInfo.bleScanCycle>0)\r
-        {\r
-            setBleScanAlarm(runtime.bleInfo.bleScanCycle);\r
-        }\r
-\r
-        //设置来电模式\r
-        SimSignalUtil.SetRingMode(this, AudioManager.RINGER_MODE_NORMAL,true);\r
-\r
-        //备份DB数据到sd cache目录,为调试方便\r
-        Util.getDBFile();\r
-//        test(); //test function\r
-\r
- //更新MCC MNC\r
-        CellInfoUtil.setCurrentAttachCellInfo(CoreService.getInstance().runtime);\r
- //更新IMEI\r
-        DeviceInfoUtil.updateImei(runtime);\r
-\r
-        //设置断网状态\r
-        Util.setSystemProperties("persist.sys.server_connected","false");\r
-\r
-        //启动结束设置标志位,让心率和体温检测可以正常执行。\r
-        server_starting=false;\r
-\r
-        //重置缓存中的在等待命令\r
-        Deliver.resetCMDReocrdsDB();\r
-\r
-        ReConnectToServer();\r
-    }\r
-\r
-    private void test(){\r
-\r
-        ICLogger.i("周一清除所有睡眠数据Record");\r
-        runtime.getDbHelper().deleteSleepData();\r
-    }\r
-\r
-    //检查是否有未读消息需要提醒\r
-    private  void checkUnreadMessage(){\r
-\r
-        String msg=Config.getLastUnReadMessage(this);\r
-        Util.checkMesageNeedNotifi(msg,runtime);\r
-\r
-\r
-    }\r
-\r
-    //内部广播StringMessage\r
-    public static void DevliverStringMessage(String cmd){\r
-        CoreService.getInstance().connection.DeliverCMDMessageToSystem(cmd,"");\r
-    }\r
-    //内部广播StringMessage\r
-    public static void DevliverStringMessage(String cmd,String str){\r
-        CoreService.getInstance().connection.DeliverCMDMessageToSystem(cmd,str);\r
-    }\r
-\r
-    //表带剪断检测报警,此处只是设备本地提醒,并不发送报警信息给服务器。\r
-    public void checkAlarmMessage(){\r
-\r
-\r
-        if (runtime.Fence_Warning_flag>0 &&  Config.needAllwaysAlarmFenceOut){\r
-            runtime.Fence_Warning_flag++;\r
-            WakeLockUtil.ScreenOnWakeLockTemperary(runtime.getContextProxy().context);\r
-            runtime.getContextProxy().sendMsgBroadcast(runtime.getContextProxy().context.getResources().getString(R.string.alarm_out_wall),2);\r
-        }\r
-        if(runtime.Cut_off_flag>0 && Config.needAllwaysAlarmCutOff){\r
-            runtime.Cut_off_flag++;\r
-//            WakeLockUtil.ScreenOnWakeLockTemperary(runtime.getContextProxy().context);\r
-\r
-            if (Config.A9_noBroadCastActionStrip) {\r
-                if(Config.needBroadcastCutoffAlarm) {\r
-                    antiservice.send_cutoff_event_broadcast(1);\r
-                }\r
-\r
-            }\r
-        }\r
-\r
-    }\r
-\r
-    //检测久坐提醒\r
-    public void checkKeepSitting(){\r
-        String dateyyyyMMDDhhmmss=TimeUtil.getSystemTime3();\r
-        //为了更新 isInSleepRange, 下面的语句必须执行\r
-        TimeUtil.getCurrentSleepRecordDate(dateyyyyMMDDhhmmss);\r
-         if(TimeUtil.isInSleepRange == false) { //不在睡眠时间就是久坐时间段。\r
-             if (Runtime.lastSitCheckStepCount == -1){\r
-                 Runtime.lastSitCheckStepCount=runtime.getTotalStepCount();\r
-                 Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3();\r
-             }\r
-             int keepsitRange=Config.getKeepSitRangeInMinutes(this);\r
-             int minutes=(int)TimeUtil.diffBetween2DateInMinutes(Runtime.lastSitCheckTiimeyyyyMMddHHmmss,dateyyyyMMDDhhmmss);\r
-             ICLogger.i("SitCheck last SitCheckTime "+ Runtime.lastSitCheckTiimeyyyyMMddHHmmss + " , current checktime "+dateyyyyMMDDhhmmss);\r
-             ICLogger.i("SitCheck minutes "+ minutes + " , keepsitRange "+keepsitRange);\r
-             if (minutes >=keepsitRange && keepsitRange>0){\r
-                if ( (runtime.getTotalStepCount() - Runtime.lastSitCheckStepCount)/minutes < Config.KeepSitJudgementRefValue){\r
-                    //平均 每分钟活动数 小于参考久坐计步值,表示久坐\r
-                    ICLogger.i("SitCheck 平均 每分钟活动数 小于参考久坐计步值,表示久坐");\r
-                    WakeLockUtil.ScreenOnWakeLockTemperary(this);\r
-                    VibrateUtil.getInstance(this).VibrateOn(true);\r
-                    Util.mSleep(1000);\r
-                    runtime.getContextProxy().sendBroadcastSitLongAlarm(); //广播久坐消息\r
-\r
-\r
-                    //提醒后 重置 lastCheckSitTime 以及 lastSitCheckStepCount , 重新计时\r
-                    Runtime.lastSitCheckStepCount=runtime.getTotalStepCount();\r
-                    Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3();\r
-\r
-                    if(Config.isAlarmTypeEnabled(Runtime.AlarmType.ALARM_SEDENTARY)){\r
-                        runtime.setAlarmType(Runtime.AlarmType.ALARM_SEDENTARY);\r
-//                        Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(runtime));\r
-                        ICLogger.i("triggerSOSLocationProcess ");\r
-                        locationClient.triggerSOSLocationProcess();\r
-                    }\r
-                }else{\r
-                    //只要 平均每分钟活动数大于参考值,则重置 lastCheckSitTime 以及 lastSitCheckStepCount\r
-                    ICLogger.i("SitCheck 平均每分钟活动数大于参考值,则重置 lastCheckSitTime 以及 lastSitCheckStepCount");\r
-                    Runtime.lastSitCheckStepCount=runtime.getTotalStepCount();\r
-                    Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3();\r
-                }\r
-            }\r
-        }else{\r
-             Runtime.lastSitCheckStepCount=-1; //不在时间段就重置数据,以便下一次使用能过重新开始计数。\r
-        }\r
-\r
-\r
-    }\r
-\r
-    public void updateSleepDate(){\r
-        String dateyyyyMMDDhhmmss=TimeUtil.getSystemTime3();\r
-        String sleepdate=TimeUtil.getCurrentSleepRecordDate(dateyyyyMMDDhhmmss);\r
-        ICLogger.i("updateSleepDate "+sleepdate);\r
-        if(TimeUtil.isInSleepRange == true) {\r
-            runtime.getDbHelper().insertSleepRecord(new SleepRecord(dateyyyyMMDDhhmmss,sleepdate,runtime.getTotalStepCount()));\r
-            runtime.sleepDataReported=false; //只要记录过数据 就证明有数据没有report\r
-        }else{\r
-            if (runtime.sleepDataReported == false) {\r
-                //calculate sleep data and report it randomly within 1 hour\r
-                runtime.sleepDataReported = true;\r
-                int score = runtime.getDbHelper().querySleepScore(sleepdate);\r
-                if (score > 0) {\r
-                    ICLogger.i("已经有"+sleepdate+"的睡眠数据!");\r
-                } else {\r
-                    SleepInfo si = SleepInfo.getInstance();\r
-                    si.setDate(sleepdate);\r
-                    si.calculate_sleepInfo(runtime);\r
-\r
-                    runtime.getDbHelper().updateSleepInfo(si);\r
-                    if (TimeUtil.getWeek().equals("周一")){\r
-                        ICLogger.i("周一清除所有睡眠数据Record");\r
-                        runtime.getDbHelper().deleteSleepData();\r
-                    }\r
-                    Config.setSleepDate(this, sleepdate);\r
-                    Config.setSleepScore(this, si.getScore());\r
-                    Random r = new Random();\r
-                    int randomint = r.nextInt(30 - 1) + 1;\r
-                    ICLogger.i("Delayed " + randomint + " minutes , send  sleep info " + si.getCurrentDate()\r
-                            + " deep " + si.getDeepsleep_minutes()\r
-                            + " light " + si.getLightsleep_minutes()\r
-                            + " score " + si.getScore()\r
-                    );\r
-//                    Observable.timer(randomint * 60 * 1000L, TimeUnit.MILLISECONDS).subscribe(new Action1<Long>() {\r
-//                        public void call(Long param1Long) {\r
-//                        connection.send(protocolAPIHelper);\r
-                            ICLogger.i("Send  sleep info " + si.getCurrentDate()\r
-                                    + " deep " + si.getDeepsleep_minutes()\r
-                                    + " light " + si.getLightsleep_minutes()\r
-                                    + " score " + si.getScore()\r
-                            );\r
-                            if (Config.enableSleep) {\r
-                                Deliver.sendLocationMSG(protocolAPIHelper.getSleepMSG(SleepInfo.getInstance(), runtime));\r
-                            }else{\r
-                                ICLogger.i(" 没有开启睡眠协议,skip send message!");\r
-                            }\r
-//                        }\r
-//                    });\r
-\r
-                }\r
-            }\r
-        }\r
-    }\r
-    public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) {\r
-        if (paramIntent != null && paramIntent.getAction()!=null) {\r
-            StringBuilder stringBuilder = new StringBuilder();\r
-            stringBuilder.append("onStartCommand action=");\r
-            stringBuilder.append(paramIntent.getAction());\r
-            stringBuilder.append(" paramInt1=");\r
-            stringBuilder.append(paramInt1);\r
-            stringBuilder.append(" paramInt2=");\r
-            stringBuilder.append(paramInt2);\r
-            ICLogger.i(stringBuilder.toString());\r
-//            if (ACTION_ALARM.equals(paramIntent.getAction())) {\r
-            if (ACTION_LOCATION_ALARM.equals(paramIntent.getAction())) {\r
-\r
-\r
-//                    if (cmcm_call_eiot_into_powersave_mode() == 1) {\r
-//                        ICLogger.i("2 into powersave return");\r
-//                        return Service.START_NOT_STICKY;\r
-//                    }\r
-\r
-//                //wakeup后1分钟唤醒一次,5分钟后,心跳改为从配置信息读取的值,默认为3分钟\r
-//                if (this.startAlarmCount < 5 && alarmCycle == 1) {\r
-//                    this.startAlarmCount++;\r
-//                } else {\r
-//                    alarmCycle = Config.getAlarmCycle(this);\r
-//                }\r
-                AlarmWakeUp.setAlarmWakeUpTime();\r
-                boolean screenon = ((PowerManager) getSystemService(POWER_SERVICE)).isScreenOn();\r
-                if (!screenon) {\r
-                    SimSignalUtil.send_at_to_update_lbs(this.runtime);\r
-                }\r
-                //这里就是为了省电,如果wifi开启,且屏幕关闭,则wifi也关闭 ,还有获取wifi消息的时候也和它有关\r
-                if (Util.isConnectWifi((this.runtime.getContextProxy()).context) && !screenon) {\r
-                    is_wifi_network_ok = true; //如果wifi开启的,则记录wifi状态为开启,以后屏幕开启时,再根据此变量决定是否打开wifi\r
-                    Util.turnOffWifiForSleep((this.runtime.getContextProxy()).context, this.runtime);\r
-                }\r
-//                setAlarm(alarmCycle);\r
-//                if (Config.LOG_TOFILE) FileOutputUtil.fileOutput(runtime.getCacheDir(), "alarmCycle", "ALARM alarmCycle");\r
-\r
-                //发送心跳间隔广播给其他应用\r
-                this.runtime.getContextProxy().sendBroadcast(ACTION_EQC_ALARM, this.runtime);\r
-                this.locationClient.onAlarm(getWakeLock(1));\r
-                this.connectionServiceChain.processAlarmClock(this.connection, this.runtime);\r
-                this.invokeHandlerServiceChain.processAlarmClock(this.connection, this.runtime);\r
-//                if (SystemClock.elapsedRealtime() - this.mWeatherTime > 60000L && this.mHaveSetWeatherAlarm) {\r
-//                    setWeatherAlarm();\r
-//                    this.mHaveSetWeatherAlarm = false;\r
-//                    return Service.START_NOT_STICKY;\r
-//                }\r
-\r
-\r
-                //收到定时定位消息\r
-                setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-                StringBuilder stringBuilder1 = new StringBuilder();\r
-                stringBuilder1.append("LOCATION_ALARM  work mod=");\r
-                stringBuilder1.append(runtime.getLocationInstance().getWorkingMod());\r
-                if (Config.LOG_TOFILE) ICLogger.logToFile("alarmCycle", stringBuilder1.toString());\r
-//                this.locationClient.triggerLocationProcess();\r
-\r
-            }else if (Constants.ACTION_ALARM_BLE_SCAN.equals(paramIntent.getAction())) {\r
-                    //循环蓝牙扫描\r
-                setBleScanAlarm(runtime.bleInfo.bleScanCycle);\r
-\r
-            }else if (Constants.ACTION_PRACTICE_REPORT_ALARM.equals(paramIntent.getAction())) {\r
-                //alarm是延迟的,所以这个判断主要是给最后一次可能无效的测量\r
-                if (Runtime.practising==true) {\r
-                    //开始下一轮健康测量\r
-                    setPracticeAlarm();\r
-                }\r
-            }else if (Constants.ACTION_CHECK_SERVER_RESPONSE.equals(paramIntent.getAction())) {\r
-                //暂时还使用 ScheduledThreadPoolExecutor , 时间要求不是那么的严格\r
-            }else if (Constants.ACTION_RETRY_SERVER_CONNECT.equals(paramIntent.getAction())) {\r
-                //暂时还使用 ScheduledThreadPoolExecutor , 时间要求不是那么的严格\r
-            }else if (Constants.ACTION_CHECK_LOCATION_RESULT.equals(paramIntent.getAction())) {\r
-                locationClient.waitAndSendLocation();\r
-            }else if (Constants.SLEEP_ALARM.equals(paramIntent.getAction())) {\r
-                StringBuilder stringBuilder1;\r
-                ICLogger.i("SLEEP_ALARM");\r
-                is_allowed_in_sleep_mode = 1;\r
-                if (Config.LOG_TOFILE) ICLogger.logToFile("alarmCycle", "SLEEP_ALARM  alarmCycle");\r
-                setSleepAlarm();\r
-                boolean bool = ((PowerManager) getSystemService(POWER_SERVICE)).isScreenOn();\r
-                stringBuilder1 = new StringBuilder();\r
-                stringBuilder1.append("ifOpen = ");\r
-                stringBuilder1.append(bool);\r
-                ICLogger.i(stringBuilder1.toString());\r
-                if (!bool) {\r
-                    is_in_sleep_mode = true;\r
-                    if (this.mKeepAlive != null)\r
-                        this.mKeepAlive.setSleepMode(true);\r
-//                        this.connection.close();\r
-                    return Service.START_STICKY;\r
-                }\r
-            } else if (Constants.WAKE_ALARM.equals(paramIntent.getAction())) {\r
-                if (is_in_sleep_mode) {\r
-                    is_in_sleep_mode = false;\r
-                    if (Config.LOG_TOFILE)\r
-                        ICLogger.logToFile("alarmCycle", "WAKE_ALARM  alarmCycle");\r
-                    if (this.mKeepAlive != null)\r
-                        this.mKeepAlive.setSleepMode(false);\r
-                    wakeUpFromSleep();\r
-                }\r
-                is_allowed_in_sleep_mode = 1;\r
-                setWakeAlarm();\r
-                return Service.START_STICKY;\r
-            } else if (ANTI_ALARM.equals(paramIntent.getAction())) {\r
-                //测试是否佩戴\r
-                antiservice.CheckAntiByPoling();\r
-                if (Config.LOG_TOFILE)\r
-                    ICLogger.logToFile("alarmCycle", "ANTI_ALARM alarmCycle  ");\r
-                setAntiAlarm();\r
-\r
-                return Service.START_STICKY;\r
-//                if (this.mKeepAlive != null) {\r
-//\r
-//                    if (connection.isServerConnected() && runtime.isServerProtocolConnected()) {\r
-//                    }\r
-//                    return Service.START_STICKY;\r
-//                }\r
-            } else if (TEMP_ALARM.equals(paramIntent.getAction())) {\r
-\r
-                setTempAlarm();\r
-\r
-               return Service.START_STICKY;\r
-            } else if (HEART_ALARM.equals(paramIntent.getAction())) {\r
-\r
-                locationClient.updateStepCount();\r
-                updateSleepDate(); //检查睡眠\r
-                checkKeepSitting();//检查久坐\r
-                checkAlarmMessage();//检测是否有报警消息需要显示\r
-                checkUnreadMessage();//检查未读消息\r
-                if (this.mKeepAlive != null) {\r
-                    if (connection.isServerConnected() && runtime.isServerProtocolConnected()) {\r
-                        this.mKeepAlive.onHeartAlarm(this.connection, this.runtime);\r
-                        ICLogger.i("triggerBLEProcess ");\r
-                        locationClient.triggerBLEProcess();//每次心跳检测一次BLE\r
-                        Deliver.triggerSendThread();\r
-                    } else {\r
-                       // if (this.mKeepAlive.is_retry_time_above_limit()) {\r
-                            ICLogger.i("check 发送心跳包时,如果发现服务器没有响应,或者socket连接,则重新尝试连接服务器!");\r
-                            connection.disconnectServer();\r
-                            this.startConnectionRetryTimer();\r
-                       // }else{\r
-                      //      ICLogger.i("");\r
-                      //  }\r
-                    }\r
-                    //检测电池电量 并上报低电报警\r
-                    batteryUtil.getBatteryLevel(this);\r
-                    setHeartAlarm();\r
-                    if (Config.LOG_TOFILE)\r
-                        ICLogger.logToFile("alarmCycle", "HEART_ALARM alarmCycle  ");\r
-                    return Service.START_STICKY;\r
-                }\r
-            } else if (STEP_COUNT_ALARM_ACTION.equals(paramIntent.getAction())) {\r
-                ICLogger.i("Reset Count At 00:00 ");\r
-                //update stepCount and broadcast before reset\r
-                this.locationClient.updateStepCount(); //先记录下最后一次步数\r
-                runtime.getContextProxy().brodcastResetStepCount(runtime.getTotalStepCount());\r
-                updateSleepDate();//更新睡眠信息\r
-\r
-                //更新 运动控制的上次步数 然后再resetstecount\r
-                //runtime.setLastStepCount(runtime.getTotalStepCount()-runtime.getLastStepCount());\r
-                //runtime.setLastStepCountForBT(runtime.getTotalStepCount()-runtime.getLastStepCountForBT());\r
-                 resetStepCount();\r
-                //此处本来应该把刚刚reset前运动的步数设置到计步器里,继续开始计步。\r
-                // 由于计步接口没有提供设置步数。所以暂时只能清零,不能解决午夜还在运动的情况,会丢失一两次的数据。但是影响不大\r
-                runtime.setLastStepCountForBT(0);\r
-                runtime.setLastStepCount(0);\r
-                //重置后马上跟新当前步数为0, 以便及时更新睡眠信息 一分钟内更新的步数可以忽略不记,从而平滑切换 0点reset 计步数据的计算问题\r
-                this.locationClient.updateStepCount();\r
-                //更新睡眠信息\r
-                updateSleepDate();\r
-                //清除已经发送的历史记录\r
-                runtime.getDbHelper().clearCMDRecordsHaveSent();\r
-                setCleanStepCountAlarm();\r
-                Config.logBootDate(this);//重置步数的时候,要把开机时间也更新一下,否则第二天 任意时间重启都会造成计步数据清零\r
-                return Service.START_STICKY;\r
-            } else if (ACTION_HEATR_RATE_START.equals(paramIntent.getAction())) {\r
-\r
-                //此处消息从timer来\r
-                //此消息来源于BroadCaset,收到开始测试的消息。\r
-                //此时需要重置HeartRateDetect Timer\r
-                //倘若有 参数 PPGTestCycle,则根据这个数值进行设置\r
-                int ppgtestCycle=paramIntent.getIntExtra("PPGTestCycle",-1);\r
-                if (ppgtestCycle >0){\r
-                    Config.setPPGTestCycle(runtime.getContextProxy().context,ppgtestCycle);\r
-                    runtime.setPpgTestCycle(Config.getPPGTestCycle(runtime.getContextProxy().context));\r
-                    ICLogger.i("get and set PPGTestCycle "+ppgtestCycle);\r
-                }\r
-                setHeartRateDetectAlarm(runtime.getPpgTestCycle());//重置心率检测周期,并触发一次检测\r
-\r
-            } else if (ACTION_SEND_EMEGENCY_LOCATION_STOP.equals(paramIntent.getAction())) {\r
-                //stop Emegency location Stop\r
-                Config.loadModCycleSettings(runtime); //回复之前的 工作模式即可\r
-                LocationClient.setForceLocation(1);\r
-                setLocationAlarm(runtime.getLocationInstance().getWorkingMod());//同时重置alarm并触发定位\r
-\r
-            }else if(ACTION_CHECK_ANTIOFF_EVENT.equals(paramIntent.getAction())){\r
-                //只在中断式检测过程中延时用\r
-                antiservice.check_ant_event();\r
-            }\r
-\r
-            this.invokeHandlerServiceChain.processUserRequest(paramIntent, this.connection, this.runtime);\r
-\r
-        }\r
-        return Service.START_NOT_STICKY;\r
-    }\r
-\r
-    public boolean onUnbind(Intent paramIntent) { return false; }\r
-\r
-    //每一分钟设置一次\r
-    public void setAlarm(int paramInt) {\r
-//        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,paramInt,ACTION_ALARM);\r
-    }\r
-\r
-    public void setHeartRateDetectAlarm(int heartRateDetectAlarmCycle){\r
-        if (Config.noPPGSensor) {\r
-            ICLogger.i("setHeartRateDetectAlarm oPPGSensor");\r
-            return;\r
-        }\r
-        StringBuilder sb=new StringBuilder();\r
-        if (heartRateDetectAlarmCycle>1) {\r
-            AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context, heartRateDetectAlarmCycle, ACTION_HEATR_RATE_START);\r
-        }\r
-\r
-        if(runtime.check_stat_do_ppg_test()) {\r
-            if (Runtime.practising == true) {\r
-                sb.append("自由锻炼中,跳过原有的循环心率检测!");\r
-                ICLogger.i("自由锻炼中,跳过原有的循环心率检测!");\r
-            } else {\r
-                sb.append("setHeartRateDetectAlarm " + heartRateDetectAlarmCycle);\r
-                if(!server_starting)\r
-                    HeartRateManager.triggerPPGtest();\r
-            }\r
-        }\r
-        if (Config.LOG_TOFILE)ICLogger.logToFile("alarmCycle",sb.toString());\r
-    }\r
-\r
-    public void setBleScanAlarm(int cycle){\r
-        if (Config.BLEScanProtocol!=1) {\r
-            ICLogger.i("BLEScanProtocol!=1  skip setPolingCheckAntiAlarm");\r
-            return;\r
-        }\r
-        StringBuilder sb=new StringBuilder();\r
-        if (cycle>1) {\r
-            AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context, cycle, ACTION_ALARM_BLE_SCAN);\r
-        }\r
-        sb.append("setBleScanAlarm " + cycle);\r
-        locationClient.triggerBLEProcess();\r
-        ICLogger.i(sb.toString());\r
-        if (Config.LOG_TOFILE)ICLogger.logToFile("alarmCycle",sb.toString());\r
-    }\r
-\r
-    public void setEmegencyLocationSTOPAlarm(int delayTimeInMinutes){\r
-        StringBuilder sb=new StringBuilder();\r
-        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,delayTimeInMinutes, ACTION_SEND_EMEGENCY_LOCATION_STOP);\r
-        sb.append(" tEmegencyLocationSTOPAlarm  "+ACTION_SEND_EMEGENCY_LOCATION_STOP);\r
-//        ICLogger.i(sb.toString());\r
-        if (Config.LOG_TOFILE)ICLogger.logToFile("alarmCycle",sb.toString());\r
-    }\r
-    public void setLocationAlarm(int mod) {\r
-//        int mod=runtime.getLocationInstance().getWorkingMod();\r
-        StringBuilder sb=new StringBuilder();\r
-        int cycle=60;\r
-        switch(mod){\r
-            case EMERGNECY_MOD:\r
-            case REALTIME_MOD:\r
-                cycle=60;\r
-                break;\r
-            case NORMAL_MOD:\r
-                cycle=15*60;\r
-                break;\r
-            case LOWPOWER_MOD:\r
-                cycle=60*60;\r
-                break;\r
-            case CUSTOM_MOD:\r
-            case CUSTOM_MOD8_GPS:\r
-            case CUSTOM_MOD8_WIFI:\r
-                cycle=runtime.getLocationInstance().getLocation_cycle();\r
-                break;\r
-        }\r
-        if(cycle == 0)\r
-        {\r
-            ICLogger.i("locationCycle == 0 stop Location !");\r
-            Config.noLocationCycle=true;\r
-        }\r
-        if (Config.noLocationCycle==false)\r
-            AlarmHelper.setRealTimeAlarmInSeconds(runtime.getContextProxy().context,cycle, ACTION_LOCATION_ALARM);\r
-        else\r
-            ICLogger.i("skip set LocationAlarm " );\r
-        sb.append(" setLocationAlarm  "+ACTION_LOCATION_ALARM+" mod "+mod+", cycle in Seconds "+cycle);\r
-        ICLogger.i(sb.toString());\r
-        if (Config.LOG_TOFILE) FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());\r
-\r
-//        if (Runtime.practising==true) {\r
-//            ICLogger.i("自由锻炼中,跳过原有的循环定位!");\r
-//            return;\r
-//        }\r
-        ICLogger.i("triggerLocationProcess ");\r
-        locationClient.triggerLocationProcess();\r
-\r
-    }\r
-\r
-    public void setHeartAlarm(){\r
-//        int mod=runtime.getLocationInstance().getWorkingMod();\r
-        StringBuilder sb=new StringBuilder();\r
-        int cycle=runtime.getHeartBeatCycle();\r
-\r
-        //心跳指令默认设置\r
-        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,cycle, HEART_ALARM);\r
-        sb.append(" setHeartAlarm  "+HEART_ALARM+", cycle "+cycle);\r
-//        locationClient.triggerLocationProcess();\r
-        ICLogger.i(sb.toString());\r
-        FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());\r
-\r
-//        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,1, HEART_ALARM);\r
-    }\r
-    public void setAntiAlarm(){\r
-//        int mod=runtime.getLocationInstance().getWorkingMod();\r
-        StringBuilder sb=new StringBuilder();\r
-        int cycle=runtime.anti_test_cycle;\r
-        if(cycle>1) {\r
-            AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context, cycle, ANTI_ALARM);\r
-        }\r
-        sb.append(" setHeartAlarm  "+ANTI_ALARM+", cycle "+cycle);\r
-\r
-        ICLogger.i(sb.toString());\r
-        FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());\r
-    }\r
-    public void setTempAlarm(){\r
-//        int mod=runtime.getLocationInstance().getWorkingMod();\r
-        StringBuilder sb=new StringBuilder();\r
-        int cycle=runtime.temp_test_Cycle;\r
-\r
-        if(Config.noTempSensor) {\r
-            ICLogger.i("setTempAlarm noTempSensor");\r
-            return;\r
-        }\r
-        if (cycle>1) {\r
-            AlarmHelper.setRealTimeAlarmInSeconds(runtime.getContextProxy().context, cycle, TEMP_ALARM);\r
-            sb.append(" setTempAlarm  " + TEMP_ALARM + ", cycle " + cycle);\r
-        }else {\r
-            sb.append(" setTempAlarm  " + TEMP_ALARM + ", cycle " + cycle+"<=1 skip!");\r
-        }\r
-//        locationClient.triggerLocationProcess();\r
-        ICLogger.i(sb.toString());\r
-        FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());\r
-\r
-        if(runtime.check_stat_do_temp_test()) {\r
-            if (Runtime.practising == true) {\r
-                ICLogger.i("自由锻炼中,跳过原有的循环温度检测!");\r
-            } else {\r
-                if(!server_starting)\r
-                    TemperatureUtil.doTempTestInThread();\r
-            }\r
-        }\r
-\r
-    }\r
-    public void setUpLocationDataAlarm(long paramLong) {\r
-        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\r
-        Intent intent = new Intent(this, CoreService.class);\r
-        intent.setAction(ACTION_ALARM_ADD_DATAPOINTS);\r
-        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, FLAG_UPDATE_CURRENT);\r
-        alarmManager.cancel(pendingIntent);\r
-        alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + paramLong, pendingIntent);\r
-        StringBuilder stringBuilder = new StringBuilder();\r
-        stringBuilder.append("interval=");\r
-        stringBuilder.append(paramLong);\r
-        ICLogger.i(stringBuilder.toString());\r
-        AlarmHelper.setRealTimeAlarm( runtime.getContextProxy().context,(int)((System.currentTimeMillis() + paramLong)/1000),ACTION_ALARM_ADD_DATAPOINTS);\r
-    }\r
-\r
-    public static class InnerService extends Service {\r
-        public IBinder onBind(Intent param1Intent) { return null; }\r
-\r
-        /*给 API >= 18 的平台上用的灰色保活手段*/\r
-        public int onStartCommand(Intent param1Intent, int param1Int1, int param1Int2) {\r
-            startForeground(GRAY_SERVICE_ID, new Notification());\r
-            stopForeground(true);\r
-            stopSelf();\r
-            return super.onStartCommand(param1Intent, param1Int1, param1Int2);\r
-        }\r
-    }\r
-\r
-    private static class RequestHandler extends Handler {\r
-        private final WeakReference<CoreService> mReference;\r
-\r
-        RequestHandler(CoreService param1CoreService) {\r
-            this.mReference = new WeakReference(param1CoreService);\r
-        }\r
-\r
-        public void handleMessage(Message param1Message) {\r
-            CoreService coreService = (CoreService)this.mReference.get();\r
-            if (coreService == null)\r
-                return;\r
-            coreService.invokeHandlerServiceChain.processUserRequest(param1Message, coreService.connection, coreService.runtime);\r
-        }\r
-    }\r
-\r
-    private static final String TAG = "ICSrv." + CoreService.class.getSimpleName();\r
-\r
-    private ScheduledThreadPoolExecutor mTimer_retry_connect=null;\r
-\r
-    private static int retry_connect_count=0;  //当前重试次数\r
-    private static int retry_connect_max_times=6; //最大重试次数 6次 , 即只重试2分钟,下一次重试将在下一个心跳包时进行。\r
-    private static int retry_cocnnect_cycle=20; //重试间隔20秒\r
-    private void log(String msg) {\r
-        ICLogger.log(TAG,msg);\r
-    }\r
-\r
-    public static CoreService getInstance(){\r
-        return mProtocolServer;\r
-    }\r
-\r
-    public void startConnectionRetryTimer(){\r
-        //联网再重试连接服务器, 不能够联网的情况下不管是不是有sim卡,以及是否联网,都进行重试,以便处理下面情况:\r
-        //1、sim卡接触不良,掉卡,可以尝试用此法恢复\r
-        //2、网络信号不好,造成临时掉线,但是恢复慢或不恢复,可以用此法尝试恢复\r
-//        if (SimSignalUtil.checkNet(runtime.getContextProxy().context) ) {\r
-             stopConnectionRetryTimer();\r
-            if (mTimer_retry_connect == null) {\r
-                mTimer_retry_connect = new ScheduledThreadPoolExecutor(10);\r
-            }\r
-            //如果开始进行连接重\r
-                // {\r
-            // 试,证明网络断开的,那么KeepAlive也需要重连(心跳包)\r
-            retry_connect_count=0;\r
-            KeepAlive.isConnected = false;\r
-            if (mTimer_retry_connect != null) {\r
-                mTimer_retry_connect.scheduleAtFixedRate(mReConnectSrvThread, 5000, 20000, TimeUnit.MILLISECONDS); //每次都是断网才需要重连,delay 5秒重连,并且每20秒重试一次\r
-            }\r
-//        }\r
-    }\r
-    private ReConnectSrvThread mReConnectSrvThread=new ReConnectSrvThread();\r
-    private class ReConnectSrvThread implements  Runnable{\r
-        @Override\r
-        public void run() {\r
-            ReConnectToServer();\r
-        }\r
-    }\r
-\r
-    private static int no_network_Heartbeats_Count=0;\r
-\r
-    public void ReConnectToServer(){\r
-        long timeSincelastReceive=0;\r
-        if(Runtime.lastLinkReceiveStamp>0)\r
-            timeSincelastReceive=(System.currentTimeMillis()-Runtime.lastLinkReceiveStamp)/1000;\r
-        if (timeSincelastReceive>0) ICLogger.i("距离上次从服务器收到数据,已经有 " + timeSincelastReceive + " 秒!");\r
-        if (SimSignalUtil.checkNet(runtime.getContextProxy().context) ) {\r
-            //里面如果连接成功 connectionOpen 会先发送 AP00 登录包 和发送AP03 心跳包 ,\r
-            // isServerConnected 成功则停止重试, KeepAlive会检测AP03心跳包的成功与否。此处只管socket连接是否成功\r
-            if (connection.isServerConnected()) {\r
-                ICLogger.i("retry  如果连接成功则停止重试!");\r
-                no_network_Heartbeats_Count=0;\r
-                stopConnectionRetryTimer();\r
-            }else {\r
-                if (retry_connect_count >= retry_connect_max_times) {\r
-\r
-                    no_network_Heartbeats_Count++;\r
-                    ICLogger.i("retry " + retry_connect_count + " 次 >= " + retry_connect_max_times + " ,停止重试!等待下一次心跳再重试! 已经第"+no_network_Heartbeats_Count+"次心跳都没有连接服务器成功!");\r
-                    stopConnectionRetryTimer();\r
-\r
-                } else {\r
-                    retry_connect_count++;\r
-                    String ip = runtime.getDnsUtil().getServerIP_ByDNSCache(runtime.getHost());\r
-                    if (null != ip && !ip.equals(runtime.getSrvIP())) {\r
-                        runtime.setSrvIP(ip);\r
-                    }\r
-                    ICLogger.i("retry 第" + retry_connect_count + " 次 , 连接服务器!");\r
-                    this.connection.connect(this.runtime.getSrvIP(), this.runtime.getPort());\r
-\r
-                }\r
-            }\r
-        }else{\r
-            //没有网络就不用重新尝试连接网络了。网络连接后再重新尝试联网\r
-            ICLogger.i("retry "+no_network_Heartbeats_Count+" 没有网络就不用重新尝试连接网络了。网络连接后再重新尝试联网!");\r
-            no_network_Heartbeats_Count++;\r
-            stopConnectionRetryTimer();\r
-        }\r
-        if( no_network_Heartbeats_Count >12){\r
-            ICLogger.i("当前第"+no_network_Heartbeats_Count+"次心跳都没有连接服务器成功 > 10 ,重置SIM卡尝试重新注册网络!");\r
-            SimSignalUtil.send_at_to_reset_simcard(runtime); //直接下此命令不能实现断网重连,所以干脆采用关闭网络再打开的方式。\r
-            //SimSignalUtil.setAirMode(this,"OpenAirplane");\r
-            mHandler.postDelayed(reopenSim,5000); //5秒后重新链接服务器。\r
-            no_network_Heartbeats_Count=0;//重置Sim卡后重置计数。防止后面多次重置Sim卡。\r
-        }\r
-    }\r
-    private Runnable reopenSim =new Runnable(){\r
-        @Override\r
-        public void run() {\r
-            if (CoreService.getInstance()!=null) {\r
-             //   SimSignalUtil.setAirMode(CoreService.getInstance(), "CloseAirplane");\r
-                disconnect_server();\r
-                ReConnectToServer();\r
-            }\r
-        }\r
-    };\r
-    public void stopConnectionRetryTimer(){\r
-        if (mTimer_retry_connect !=null){\r
-            mTimer_retry_connect.shutdownNow();\r
-//            while(!mTimer_retry_connect.isTerminated())\r
-//            {\r
-//                ICLogger.i("Wait for thread pool terminated");\r
-//                try {\r
-//                    Thread.sleep(500);\r
-//                } catch (InterruptedException e) {\r
-//                    e.printStackTrace();\r
-//                }\r
-//            }\r
-            mTimer_retry_connect.purge();\r
-            mTimer_retry_connect = null;\r
-        }\r
-    }\r
-\r
-    private boolean needLogin(){\r
-        return true;\r
-    }\r
-\r
-\r
-\r
-\r
-    @Override\r
-    public void onDestroy() {\r
-        super.onDestroy();\r
-\r
-\r
-        saveStepCount();\r
-        this.connectionServiceChain.processDetach(this.connection, this.runtime);\r
-        this.invokeHandlerServiceChain.processDetach(this.connection, this.runtime);\r
-        this.locationClient.deinit();\r
-        this.connection.close();\r
-        unregisterReceiver(this.TimeChangeBroadcastReceiver);\r
-        unregisterReceiver(this.screenOnReceiver);\r
-        unregisterReceiver(this.AtCallbackBroadcastReceiver);\r
-        batteryUtil.unregisterBroadReceiver();\r
-\r
-    }\r
-\r
-    public void disconnect_server(){\r
-        this.connection.close();\r
-    }\r
-\r
-\r
-}\r
+package com.enqualcomm.support;
+
+import android.app.AlarmManager;
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.IClipboard;
+import android.content.Intent;
+import android.media.AudioManager;
+import android.os.Handler;
+import android.os.IBinder;
+
+import android.os.Message;
+import android.os.Messenger;
+import android.os.PowerManager;
+import android.os.SystemClock;
+import android.widget.Toast;
+
+import com.enqualcomm.support.adapter.BTHelper;
+import com.enqualcomm.support.bean.Contact;
+import com.enqualcomm.support.bean.ICLocation;
+import com.enqualcomm.support.bean.SleepInfo;
+import com.enqualcomm.support.bean.SleepRecord;
+import com.enqualcomm.support.service.AntiMonitorService;
+import com.enqualcomm.support.utils.CellInfoUtil;
+import com.enqualcomm.support.utils.Connection;
+import com.enqualcomm.support.utils.DeviceInfoUtil;
+import com.enqualcomm.support.utils.ICHttpUtil;
+import com.enqualcomm.support.utils.LedUtil;
+import com.enqualcomm.support.utils.StorageUtils;
+import com.enqualcomm.support.utils.TemperatureUtil;
+import com.enqualcomm.support.utils.TimeUtil;
+import com.enqualcomm.support.utils.VibrateUtil;
+import com.enqualcomm.support.utils.WakeLockUtil;
+import com.enqualcomm.support.utils.mqttConnection;
+import com.ic.jni.ICJniUtils;
+import com.enqualcomm.support.adapter.LBSHelper;
+import com.ic.protocols.protocolAPIHelper;
+import com.enqualcomm.support.bean.Runtime;
+import com.enqualcomm.support.bean.StringMessage;
+import com.enqualcomm.support.bean.heartRateStatus;
+import com.enqualcomm.support.service.CheckSIM;
+import com.enqualcomm.support.service.Deliver;
+import com.enqualcomm.support.service.HeartRateManager;
+import com.enqualcomm.support.service.KeepAlive;
+import com.enqualcomm.support.service.SendChatMessage;
+import com.enqualcomm.support.service.SilentManager;
+import com.enqualcomm.support.service.UpLoadDataPoints;
+import com.enqualcomm.support.service.base.AbstractConnectionService;
+import com.enqualcomm.support.service.base.AbstractInvokeHandlerService;
+import com.enqualcomm.support.utils.AlarmHelper;
+import com.enqualcomm.support.utils.AlarmWakeUp;
+import com.enqualcomm.support.utils.BatteryUtil;
+import com.enqualcomm.support.utils.ConnectionListener;
+import com.enqualcomm.support.utils.ContextProxy;
+import com.enqualcomm.support.utils.DBHelper;
+import com.enqualcomm.support.utils.FileOutputUtil;
+import com.enqualcomm.support.utils.ICLogger;
+import com.enqualcomm.support.utils.NettyConnection;
+import com.enqualcomm.support.utils.SharPreferenceUtil;
+import com.enqualcomm.support.utils.SimSignalUtil;
+import com.enqualcomm.support.utils.Util;
+
+import java.lang.ref.WeakReference;
+import chestnut.ui.Toastc;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.IntentFilter;
+
+import java.util.ArrayList;
+import java.util.Random;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
+import static com.enqualcomm.support.Constants.ACTION_ALARM_ADD_DATAPOINTS;
+import static com.enqualcomm.support.Constants.ACTION_ALARM_BLE_SCAN;
+import static com.enqualcomm.support.Constants.ACTION_ALARM_CHECK_ANTI;
+import static com.enqualcomm.support.Constants.ACTION_CHECK_ANTIOFF_EVENT;
+import static com.enqualcomm.support.Constants.ACTION_EQC_ALARM;
+import static com.enqualcomm.support.Constants.ACTION_HEATR_RATE_START;
+import static com.enqualcomm.support.Constants.ACTION_LOCAL_SOS_ACTION;
+import static com.enqualcomm.support.Constants.ACTION_LOCATION_ALARM;
+import static com.enqualcomm.support.Constants.ACTION_PRACTICE_REPORT_ALARM;
+import static com.enqualcomm.support.Constants.ACTION_QUERY_WEATHER;
+import static com.enqualcomm.support.Constants.ACTION_SEND_EMEGENCY_LOCATION_START;
+import static com.enqualcomm.support.Constants.ACTION_SEND_EMEGENCY_LOCATION_STOP;
+import static com.enqualcomm.support.Constants.ANTI_ALARM;
+import static com.enqualcomm.support.Constants.HEART_ALARM;
+import static com.enqualcomm.support.Constants.KEY_SAVE_STEP_COUNT;
+import static com.enqualcomm.support.Constants.KEY_STEP_COUNT;
+import static com.enqualcomm.support.Constants.KEY_TEMP_BODY;
+import static com.enqualcomm.support.Constants.KEY_TEMP_WRIST;
+import static com.enqualcomm.support.Constants.STEP_COUNT_ALARM_ACTION;
+import static com.enqualcomm.support.Constants.TEMP_ALARM;
+import static com.enqualcomm.support.bean.ICLocation.*;
+import static com.ic.protocols.protocolAPIHelper.getTemperatureMSG;
+
+
+public class CoreService extends Service {
+
+
+    private Toastc toast = null;
+
+    private static CoreService mProtocolServer=null;
+    private static LBSHelper lbshelper=null;
+
+    public static final String ACTION_ALARM = "com.enqualcomm.support.ACTION_ALARM";
+
+    private static final int GRAY_SERVICE_ID =android.os.Process.myPid();
+
+    private static final String MY_WAKE_LOCKTAG =CoreService.class.getSimpleName();
+
+    public static int alarmCycle = 1;
+
+    public static final int interval = 60000;
+
+    public static boolean needLocateInAfterHeartBeat=false;
+    private static int is_allowed_in_sleep_mode = 1;
+
+    private static boolean is_in_sleep_mode = false;
+
+    private static boolean is_wifi_network_ok = false;
+    // SPRD: add outdoorMode
+    public static final int RINGER_MODE_OUTDOOR = 3;
+
+    public static Handler mHandler=new Handler();
+    private static ICSmsManager smsManager=null;
+    public String getServerAlive(){
+       return DeviceInfoUtil.getDeviceInfo(runtime);
+    }
+
+    private BroadcastReceiver AtCallbackBroadcastReceiver = new BroadcastReceiver() {
+        public void onReceive(Context param1Context, Intent param1Intent) {
+            if (param1Intent.getAction().equals("com.eqc.intent.action.callback.at")) {
+                String str = param1Intent.getStringExtra("AtResult");
+                StringBuilder stringBuilder = new StringBuilder();
+                stringBuilder.append("callbackStr =");
+                stringBuilder.append(str);
+                ICLogger.i(stringBuilder.toString());
+                if (str.indexOf("OK") != -1) {
+                    String[] arrayOfString = str.split("\"");
+                    if (arrayOfString.length > 4) {
+                        str = arrayOfString[1];
+                        String str1 = arrayOfString[3];
+                        Context context = (CoreService.this.runtime.getContextProxy()).context;
+                        StringBuilder stringBuilder1 = new StringBuilder();
+                        stringBuilder1.append("AT lbsInfo LAC== ");
+                        stringBuilder1.append(Integer.valueOf(str, 16));
+                        stringBuilder1.append(",CELLID=");
+                        stringBuilder1.append(Integer.valueOf(str1, 16));
+                        if (Config.LOG_TOFILE) ICLogger.logToFile( "LBS", stringBuilder1.toString());
+                    }
+                }
+            }
+        }
+    };
+
+    private BroadcastReceiver TimeChangeBroadcastReceiver = new BroadcastReceiver() {
+        public void onReceive(Context param1Context, Intent param1Intent) {
+            StringBuilder stringBuilder2 = new StringBuilder();
+            stringBuilder2.append("broadcastReceiver  alarmCycle action==");
+            stringBuilder2.append(param1Intent.getAction());
+            if (Config.LOG_TOFILE) ICLogger.logToFile( "alarmCycle", stringBuilder2.toString());
+            StringBuilder stringBuilder1 = new StringBuilder();
+            stringBuilder1.append("时间变化");
+            stringBuilder1.append(param1Intent.getAction()+stringBuilder2.toString());
+            ICLogger.i(stringBuilder1.toString());
+
+            //只有需要确定绝对时间点启动的Alarm需要重置,相对时间点的Alarm不需要重置。防止永远不能正常登陆。
+            setSleepAlarm();
+            setWakeAlarm();
+//            setHeartAlarm();
+//           setHeartRateDetectAlarm(runtime.getPpgTestCycle());
+            setWeatherAlarm();
+            runtime.getContextProxy().sendBroadcast("com.enqualcomm.support.ACTION_ALARM_ALARM_CHANGE",runtime); //更新Alarm
+           // setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+            if (cmcm_call_eiot_into_powersave_mode() == 0)
+                AlarmWakeUp.isNeedWakeUpAlarm(runtime);
+        }
+    };
+    private BroadcastReceiver broadcastSOSReceiver = new BroadcastReceiver() {
+        public void onReceive(Context param1Context, Intent param1Intent) {
+
+            StringBuilder stringBuilder2 = new StringBuilder();
+            stringBuilder2.append("broadcastReceiver  action==");
+            stringBuilder2.append(param1Intent.getAction());
+            ICLogger.i(stringBuilder2.toString());
+
+            if (ACTION_SEND_EMEGENCY_LOCATION_START.equals(param1Intent.getAction())){
+                runtime.getLocationInstance().setWorkingMod(EMERGNECY_MOD);
+                //runtime.setPpgTestCycle(1);
+                setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+
+                //触发一次心率检测
+                setHeartRateDetectAlarm(1);
+
+
+                setEmegencyLocationSTOPAlarm(5);
+            }else if (ACTION_LOCAL_SOS_ACTION.endsWith(param1Intent.getAction())){
+
+
+                VibrateUtil.getInstance(runtime.getContextProxy().context).VibrateOn(true);
+//               if( param1Intent.getIntExtra("type", 1) == 1) {
+                boolean needHRSTestOnSOS = Util.getSystemProperties("persist.sys.needHRSOnSOS","false").equals("true");
+                if(needHRSTestOnSOS) {
+                    //触发一次心率检测
+                    setHeartRateDetectAlarm(1);
+                }
+                    runtime.setAlarmType(Runtime.AlarmType.ALARM_SOS);
+                    //trigger AP10 报警定位
+                     ICLogger.i("triggerSOSLocationProcess ");
+                    LocationClient.getInstance().triggerSOSLocationProcess();
+//                    Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(runtime));
+
+                    //开启紧急定位模式,GPS 优先1分钟一次定位,持续5分钟
+                    runtime.getLocationInstance().setWorkingMod(EMERGNECY_MOD);
+                    setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+
+                    //SOS模式,心率测试1分钟一次,持续5分钟
+                    if(needHRSTestOnSOS) {
+                        //只触发一次心率检测
+                        setHeartRateDetectAlarm(1);
+                    }
+                    //设置5分钟后结束紧急定位模式
+                   setEmegencyLocationSTOPAlarm(5);
+
+
+                   if(Config.SOSNoNeedDial==false) {
+                       //50ms后开始拨打电话
+                       mHandler.postDelayed(mTriggerSOSCALLThread,500);
+                   }
+            }else if (ACTION_QUERY_WEATHER.equals(param1Intent.getAction())) {
+
+                ICLogger.i("ACTION_QUERY_WEATHER ");
+                connection.send(protocolAPIHelper.getWeatherMSG(runtime));
+                }
+        }
+    };
+
+    private TriggerSOSCALLThread mTriggerSOSCALLThread=new TriggerSOSCALLThread();
+
+    private  class TriggerSOSCALLThread implements  Runnable{
+
+        @Override
+        public void run() {
+            trigger_SOS_Call();
+        }
+    }
+    private void trigger_SOS_Call(){
+        try {
+            Intent intent = new Intent("com.eqc.shutdown_sos");
+            intent.putExtra("type",1);
+            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            this.startActivity(intent);
+        }catch (Exception e){
+            e.printStackTrace();
+        }
+    }
+    private  Runnable mupdatePracticeData=new Runnable(){
+        @Override
+        public void run() {
+            //ICHttpUtil.uploadData(Runtime.healthInfo.getBufferDataStr(),runtime,TimeUtil.getSystemTime2(),null);
+            Deliver.sendLocationMSG(protocolAPIHelper.getPRACTICE());
+            //发送过后重置
+            Runtime.healthInfo.resetBuffer();
+        }
+    };
+
+    private BroadcastReceiver broadcastPracticeCMDReceiver = new BroadcastReceiver() {
+        public void onReceive(Context param1Context, Intent param1Intent) {
+            if(param1Intent.getAction().equals(Constants.ACTION_START_PRACTISE))
+            {
+                int cmd=param1Intent.getIntExtra(Constants.KeyPractice,0);
+                if (cmd==1){
+                    //开始自由锻炼
+                    Runtime.practising=true;
+                    Util.setSystemProperties( Config.KeyPractiseState,"true");
+                    Runtime.healthInfo.reset();
+                    Runtime.healthInfo.resetBuffer();
+                    setPracticeAlarm();
+
+                }else{
+                    //停止自由锻炼,恢复正常
+                    Runtime.practising=false;
+                    Util.setSystemProperties( Config.KeyPractiseState,"false");
+                    HeartRateManager.stopPPGtest();
+
+                    //最后检测是否还有数据需要发送
+                    if(Runtime.healthInfo.check_info_item_finished()){
+                        Runtime.healthInfo.appendBuffer(Runtime.healthInfo.getHealthInfoString());
+                        Runtime.healthInfo.reset();
+                     }
+                    if(Runtime.healthInfo.getInfoCount()>=0){
+                        //超过30次发送数据给服务器
+                        ICLogger.i("自由锻炼结束,发送数据给服务器 "+Runtime.healthInfo.getBufferData().length);
+                        mHandler.post(mupdatePracticeData);
+                    }
+
+                }
+            }
+        }
+    };
+
+    private static class ServerHandler implements ConnectionListener {
+        private final WeakReference<CoreService> mReference;
+
+        ServerHandler(CoreService param1CoreService) { this.mReference = new WeakReference(param1CoreService); }
+
+        @Override
+        public void onConnectionClose(String errorName) {
+            CoreService coreService = (CoreService)this.mReference.get();
+            if (coreService == null)
+                return;
+            ICLogger.i("onConnectionClose++ retry to connect again!  Close Error "+errorName);
+            coreService.connectionServiceChain.processConnectionClose(coreService.connection, coreService.runtime,errorName);
+        }
+        @Override
+        public void onConnectionOpen() {
+            CoreService coreService = (CoreService)this.mReference.get();
+            if (coreService == null)
+                return;
+            coreService.connectionServiceChain.processConnectionOpen(coreService.connection, coreService.runtime);
+            ICLogger.i("onConnectionOpen");
+        }
+
+        public void onReceive(StringMessage param1StringMessage) {
+
+            CoreService coreService = (CoreService)this.mReference.get();
+            ICLogger.i("onReceive " +param1StringMessage.cmd() +" coreService " + coreService  );
+            if (coreService == null)
+                return;
+            coreService.connectionServiceChain.processServerResponse(param1StringMessage, coreService.connection, coreService.runtime);
+            coreService.locationClient.onReceive(param1StringMessage);
+        }
+    }
+    Connection connection = null;
+    AbstractConnectionService connectionServiceChain;
+
+    AbstractInvokeHandlerService invokeHandlerServiceChain;
+
+    private boolean isBinded = false;
+
+    private AntiMonitorService antiservice;
+    LocationClient locationClient;
+
+    private Deliver mDeliver;
+
+    private boolean mHaveSetWeatherAlarm;
+
+    private KeepAlive mKeepAlive;
+
+    final Messenger mMessenger = new Messenger(new RequestHandler(this));
+
+
+    private SimSignalUtil mSignalUtil;
+
+    private BatteryUtil batteryUtil;
+    private long mWeatherTime;
+
+    Runtime runtime;
+
+    private BroadcastReceiver screenOnReceiver = new BroadcastReceiver() {
+        public void onReceive(Context param1Context, Intent param1Intent) {
+
+            if ("android.intent.action.SCREEN_ON".equals(param1Intent.getAction())) {
+                StringBuilder var3 = new StringBuilder();
+                var3.append("screen on wake is_wifi_network_ok=");
+                var3.append(CoreService.is_wifi_network_ok);
+                ICLogger.i(var3.toString());
+                //检测电池电量 并上报低电报警
+                batteryUtil.getBatteryLevel(param1Context);
+                if (CoreService.is_in_sleep_mode) {
+
+                    /*屏幕亮起时,如果在sleep模式(夜晚的那个睡眠模式,非系统休眠,暂时没实现,还不会跑到这里),则唤醒各个进程*/
+                    CoreService.is_in_sleep_mode = false;
+                    CoreService.is_allowed_in_sleep_mode = 0;
+                    if (CoreService.this.mKeepAlive != null) {
+                        CoreService.this.mKeepAlive.setSleepMode(false);
+                    }
+
+                    CoreService.this.wakeUpFromSleep();
+                }
+
+
+                //为了保证唤醒时各个状态及时更新到服务器,发送一个同步心跳包,这样用户体验更好
+                CoreService.this.locationClient.updateStepCount();
+
+                mHandler.postDelayed(mRetryConnectSrvThread,500);
+
+
+                if (CoreService.is_wifi_network_ok) {
+                    CoreService.is_wifi_network_ok = false;
+                    /*屏幕亮起时,如果wifi用户设置是开启的,则开启wifi*/
+//                    ICLogger.i("turnOnWifiForConnect");
+//                    if (!Util.isWifiIsOpen(runtime.getContextProxy().context,runtime))
+//                        Util.turnOnWifiForConnect(runtime.getContextProxy().context, runtime);
+                }
+            } else if ("android.intent.action.SCREEN_OFF".equals(param1Intent.getAction()) && Util.isWifiIsOpen(runtime.getContextProxy().context,runtime)) {
+               // CoreService.is_wifi_network_ok = true;
+                if (!runtime.isNoTurnOffWifiOnScreenOff()) {
+                    //不关闭wifi when ScreenOff
+                    ICLogger.i("turnOffWifiForConnect");
+//                    if (Util.isWifiIsOpen(runtime.getContextProxy().context,runtime))
+//                        Util.turnOffWifiForSleep(runtime.getContextProxy().context, runtime);
+                }
+            }
+        }
+    };
+
+    private Runnable mRetryConnectSrvThread=new Runnable(){
+        @Override
+        public void run() {
+            if (connection.isServerConnected()&& runtime.isServerProtocolConnected()) {
+                mKeepAlive.onHeartAlarm(connection, runtime);
+            }else{
+                ICLogger.i("mRetryConnectSrvThread 发送心跳包时,如果发现服务器没有响应,或者socket连接,则重新尝试连接服务器!");
+                connection.disconnectServer();
+                startConnectionRetryTimer();
+            }
+        }
+    };
+
+    private int startAlarmCount = 0;
+
+    UpLoadDataPoints upLoadDataPoints;
+
+
+    private AbstractConnectionService getConnectionServiceChain() {
+//        Initialize initialize = new Initialize();
+        CheckSIM checkSIM = new CheckSIM();
+        this.mKeepAlive = new KeepAlive();
+        this.mDeliver = new Deliver(this.connection,this.runtime);
+//        initialize.setNext(checkSIM);
+        checkSIM.setNext(this.mKeepAlive);
+        this.mKeepAlive.setNext(this.mDeliver);
+        return checkSIM;
+    }
+
+
+
+    private AbstractInvokeHandlerService getInvokeHandlerServiceChain() {
+        ICLogger.i("getInvokeHandlerServiceChain");
+        SendChatMessage sendChatMessage = new SendChatMessage();
+        HeartRateManager heartRateManager= new HeartRateManager(this.runtime,this.connection);
+        antiservice = new AntiMonitorService();
+        SilentManager silentManager = SilentManager.getInstance();// new SilentManager();
+        sendChatMessage.setNext(heartRateManager);
+        heartRateManager.setNext(silentManager);
+        silentManager.setNext(antiservice);
+        return sendChatMessage;
+    }
+
+    private void resetStepCount(){
+        if ( ICJniUtils.isPedometerEnabled() == 0)ICJniUtils.enablePedometer();
+        ICJniUtils.resetStepCount();
+        SharPreferenceUtil.setPrefInt(this, KEY_STEP_COUNT, 0);
+        SharPreferenceUtil.setPrefInt(this, KEY_SAVE_STEP_COUNT, 0);
+        ICLogger.i("Reset StepCount , "+ICJniUtils.getStepCount());
+        this.runtime.setSaveStepCount(0);
+        this.runtime.setTotalStepCount(0);
+    }
+    private void loadStepCount() {
+        int i = SharPreferenceUtil.getPrefInt(this, KEY_STEP_COUNT, 0);
+        int j = SharPreferenceUtil.getPrefInt(this, KEY_SAVE_STEP_COUNT, 0);
+        if ( ICJniUtils.isPedometerEnabled() == 0)ICJniUtils.enablePedometer();
+        //ICJniUtils.recoverStepCount();
+        if (ICJniUtils.getStepCount()>i){
+            i=ICJniUtils.getStepCount();
+        }
+        this.runtime.setSaveStepCount(j);
+        this.runtime.setTotalStepCount(i);
+        runtime.setLastStepCountForBT(runtime.getTotalStepCount());
+        runtime.setLastStepCount(runtime.getTotalStepCount());
+    }
+    public void saveStepCount(){
+        int i = runtime.getTotalStepCount();
+        int j = runtime.getSaveStepCount();
+        SharPreferenceUtil.setPrefInt(this, KEY_STEP_COUNT, i);
+        SharPreferenceUtil.setPrefInt(this, KEY_SAVE_STEP_COUNT, j);
+        //ICJniUtils.saveStepCount();
+    }
+    private void setCleanStepCountAlarm() {
+        /*一天清零一次 计步*/
+//        AlarmHelper.setCleanStepCountAlarm(this, 23, 59, STEP_COUNT_ALARM_ACTION);
+        AlarmHelper.setCleanStepCountAlarm(this, 0, 0, STEP_COUNT_ALARM_ACTION);
+    }
+
+    private void setSleepAlarm() {
+        /*每5分左右 休眠*/
+//        AlarmHelper.setRealTimeAlarm(this, 5, SLEEP_ALARM);
+    }
+
+    private void setWakeAlarm() {
+
+//        /*每1 左右 唤醒自己*/
+//        Context context=runtime.getContextProxy().context;
+//        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
+//        Intent intent = new Intent(context, com.enqualcomm.support.CoreService.class);
+//        intent.setAction(WAKE_ALARM);
+//        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+//        alarmManager.cancel(pendingIntent);
+//        long l = SystemClock.elapsedRealtime();
+//        StringBuilder stringBuilder = new StringBuilder();
+//        stringBuilder.append("SDK_INT=");
+//        stringBuilder.append(Build.VERSION.SDK_INT);
+//
+//        ICLogger.i(stringBuilder.toString());
+//
+//        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, l + (1 * 60 * 1000), pendingIntent);
+
+
+    }
+
+    private void setWeatherAlarm() {
+        /*每天6点20分左右 更新一次 weather*/
+//        AlarmHelper.setTimeAlarm(this, 6, (new Random()).nextInt(40) + 20, WEATHER_ALARM);
+    }
+
+
+    private void setPracticeAlarm() {
+
+        ICLogger.i("setPracticeAlarm "+Runtime.practice_cycle+ " seconds!");
+        //只有周期大于1才有效,否则就等于单次测量
+        if (Runtime.practice_cycle>1)
+            AlarmHelper.setRealTimeAlarmInSeconds(runtime.getContextProxy().context,Runtime.practice_cycle,Constants.ACTION_PRACTICE_REPORT_ALARM);
+        mHandler.post(mdoPracticeCheck);
+    }
+    private Runnable mdoPracticeCheck=new Runnable(){
+        @Override
+        public void run() {
+            //获取并设置当前步数
+            ICLogger.i("自由锻炼中,设置步数 "+runtime.getTotalStepCount());
+            Runtime.healthInfo.setStepCount(runtime.getTotalStepCount());
+            //开启定位
+            //        locationClient.triggerLocationProcess();
+            //开启测温
+            if(runtime.check_stat_do_temp_test())
+                TemperatureUtil.DoTempTest();
+
+            //开启测量PPG
+            if(runtime.check_stat_do_ppg_test())
+                HeartRateManager.triggerPPGtest();
+
+        }
+    };
+
+    private void checkconnection(){
+
+        if (!this.connection.isServerConnected())
+        {
+            startConnectionRetryTimer();
+        }
+    }
+    private void wakeUpFromSleep() {
+        this.startAlarmCount = 0;
+//        alarmCycle = 1;
+//        setAlarm(alarmCycle);
+//        runtime.getLocationInstance().setLocation_cycle(1);
+
+        //每次唤醒都强制设置一次定位alarm和定位一次。
+        setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+
+        this.runtime.getContextProxy().sendBroadcast(ACTION_EQC_ALARM, this.runtime);
+        this.connection.open();
+        checkconnection();
+        this.locationClient.onAlarm(getWakeLock(alarmCycle));
+        this.connectionServiceChain.processAlarmClock(this.connection, this.runtime);
+        this.invokeHandlerServiceChain.processAlarmClock(this.connection, this.runtime);
+        if (SystemClock.elapsedRealtime() - this.mWeatherTime > 60000L && this.mHaveSetWeatherAlarm) {
+            setWeatherAlarm();
+            this.mHaveSetWeatherAlarm = false;
+        }
+        Toast.makeText((this.runtime.getContextProxy()).context, "从深度睡眠中切换模式,联网中", Toast.LENGTH_SHORT).show();
+    }
+
+    public int cmcm_call_eiot_into_powersave_mode() { return 0; }
+
+
+    public PowerManager.WakeLock getWakeLock(int paramInt) {
+         PowerManager.WakeLock wakeLock = ((PowerManager)(this.runtime.getContextProxy()).context.getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MY_WAKE_LOCKTAG);
+//        wakeLock.acquire(paramInt*60*1000L);
+        wakeLock.acquire(3000L);
+        return wakeLock;
+    }
+
+    public IBinder onBind(Intent paramIntent) {
+        return this.mMessenger.getBinder();
+    }
+
+
+
+    public Runtime getRuntime(){
+        return runtime;
+    }
+    public Connection getConnection(){
+        return connection;
+    }
+    private static boolean server_starting=true;
+    @Override
+    public void onCreate() {
+
+        server_starting=true;
+        log("初始化网络协议服务");
+        mProtocolServer=this;
+        java.lang.Runtime.getRuntime().addShutdownHook(new Thread(){
+            @Override
+            public void run() {
+                super.run();
+                //设置断网状态
+                ICLogger.i("shutdown !");
+                Util.setSystemProperties("persist.sys.server_connected","false");
+            }
+        });
+        this.runtime = new Runtime();
+        this.runtime.setFileDir(getFilesDir());
+        this.runtime.setCacheDir(getExternalCacheDir());
+        this.runtime.setDBHelper(new DBHelper(getContentResolver(), this));
+        this.runtime.setContextProxy(new ContextProxy(this));
+        this.runtime.setLbsHelper(new LBSHelper(this,this.runtime.getContextProxy().getWifiManager(), this.runtime));
+
+        this.runtime.setHRS(new heartRateStatus());
+        this.runtime.setUseQueue(true);
+        this.runtime.initDnsUtil(ICApplication.getInstance().getApplicationContext());
+
+
+        if (Config.protocol_no==Config.PROTOCOL_MQTT)
+        {
+            connection = new mqttConnection(new ServerHandler(this), runtime);
+        }else {
+            connection = new NettyConnection(new ServerHandler(this), runtime);
+        }
+        this.connectionServiceChain = getConnectionServiceChain();
+        this.invokeHandlerServiceChain = getInvokeHandlerServiceChain();
+//        if (cmcm_call_eiot_into_powersave_mode() == 1) {
+//            ICLogger.i("1 into powersave return");
+//            return;
+//        }
+
+        smsManager= new ICSmsManager(runtime);
+
+        //保证获取正确的计步数据及其他参数初始化
+        loadStepCount();
+
+        if (Config.logBootDate(this)){
+            resetStepCount();
+        }
+
+
+        //初始化消息相关配置
+        Config.LoadMessageConfigs();
+
+        if (Config.custom_name.equals("H88")) {
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);
+            if (Config.getConfigInitFlag(this) == 0) {
+                Config.setLocationMode(this, CUSTOM_MOD8_GPS);
+                Config.setLocationCycle(this, 3600);
+                Config.setPPGTestCycle(this, 60);
+                Config.setTemperatureTestCycle(runtime, 60 * 60);
+                Config.setConfigInitFlag(this, 1);
+            }
+        }else if (Config.custom_name.equals("l004")) {
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_CUTOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ILLEGAL_CUTOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOCK_WATCH,true);
+
+            if (Config.getConfigInitFlag(this) == 0) {
+                Config.setLocationMode(this, CUSTOM_MOD8_GPS);
+                Config.setLocationCycle(this, 600);
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+
+            }
+        }else if (Config.custom_name.equals("YQ") || Config.custom_name.equals("YQ_EN")) {
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_CUTOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ILLEGAL_CUTOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOCK_WATCH,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_UNREADMSG,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_MSGREAD,true);
+
+            if (Config.getConfigInitFlag(this) == 0) {
+                Config.setLocationMode(this, NORMAL_MOD);
+                Config.setLocationCycle(this, 15*60);
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+
+            }
+        }else if (Config.custom_name.equals("AK")) {
+
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_SOS,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOWBATTERY,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);
+            Config.enableSleep=true;
+
+            if (Config.getConfigInitFlag(this)==0) {
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+
+//                int contactcount=runtime.getDbHelper().getContactCount(getContentResolver());
+//                ICLogger.i("=====Contact count "+contactcount);
+//                if(contactcount==0){ //如果没有SOS
+//                    ICLogger.i("=====add SOS 07522312120 ");
+//                    ArrayList<Contact> contactArray=new ArrayList<Contact>();
+//                    contactArray.add(new Contact(Contact.CATEGORY_SOS, "sos1", "07522312120"));
+//                    runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);
+//                }
+            }
+        }else if (Config.custom_name.equals("YT")) {
+
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_SOS,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOWBATTERY,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);
+            Config.enableSleep=true;
+
+            if (Config.getConfigInitFlag(this)==0) {
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+
+                int contactcount=runtime.getDbHelper().getContactCount(getContentResolver());
+                ICLogger.i("=====Contact count "+contactcount);
+                if(contactcount==0){ //如果没有SOS
+                    ICLogger.i("=====add hotline 96885 ");
+                    ArrayList<Contact> contactArray=new ArrayList<Contact>();
+                    contactArray.add(new Contact(Contact.CATEGORY_CALL, this.getResources().getString(R.string.hotline), "96885"));
+                    runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);
+                }
+            }
+        }else if (Config.custom_name.equals("SGL")) { //C5项目
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ESCAPE,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_CUTOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ILLEGAL_CUTOFF,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOCK_WATCH,true);
+            Config.forceMoveCheck = false; //对定位不进行运动检测。
+            if (Config.getConfigInitFlag(this)==0) {
+                Config.setLocationMode(this, CUSTOM_MOD8_GPS);
+//                Config.setLocationMode(this, CUSTOM_MOD8_WIFI);
+                Config.setLocationCycle(this, 5*60);
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+
+//                int contactcount=runtime.getDbHelper().getContactCount(getContentResolver());
+//                ICLogger.i("=====Contact count "+contactcount);
+//                if(contactcount==0){ //如果没有SOS
+//                    ICLogger.i("=====add SOS 07522312120 ");
+//                    ArrayList<Contact> contactArray=new ArrayList<Contact>();
+//                    contactArray.add(new Contact(Contact.CATEGORY_SOS, "sos1", "07522312120"));
+//                    runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);
+//                }
+            }
+        }else if (Config.custom_name.equals("L02") || Config.custom_name.equals("L03")||Config.custom_name.equals("L05")) { //L02
+            Config.forceMoveCheck = false; //即爱对gps不进行运动检测,此变量专门为了给其他协议进行强制运动检测用的。
+            if (Config.getConfigInitFlag(this) == 0) {
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+            }
+
+        }else if (Config.custom_name.equals("VitracK")){
+
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_SOS,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_LOWBATTERY,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_WEARED,true);
+            Config.ConfigAlarm(Runtime.AlarmType.ALARM_ANTIOFF,true);
+            Config.enableSleep=false;
+            if (Config.getConfigInitFlag(this)==0) {
+                Config.setLocationMode(this, CUSTOM_MOD8_GPS);
+                Config.setLocationCycle(this, 30*60);
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+            }
+
+        }else{
+
+            if (Config.getConfigInitFlag(this)==0) {
+                Config.setPPGTestCycle(this, 0);
+                Config.setTemperatureTestCycle(runtime, 0);
+                Config.setConfigInitFlag(this, 1);
+            }
+        }
+
+        Config.dumpAlarmConfig();
+        //A9专用变量 初始化剪断,脱腕报警开关(这个开关是界面提示显示用的,上面的Config.ConfigAlarm 是上报服务器消息的开关)
+        runtime.setNeddReportCutoff(Config.getNeedCutOff(this));
+        runtime.setNeedAntioff(Config.getNeedAntiOff(this));
+
+
+
+        Config.setHeartBeatCycle(this,5); //临时设置为3分钟,给L03测试用。测试断线问题未解决,取消测试。
+        //初始化ServerHeartBeat Cycle
+        Config.loadHearBeatSetting(runtime);
+        //初始化PPG,LocationMod,LocationCycle
+        Config.loadModCycleSettings(runtime);
+        //初始化IP
+        Config.loadCustomServerAddr(this);
+        Config.loadServerSettings(runtime);
+
+        //读取Alarm环境配置,项目不需要的Alarm不要发送, 目前环境变量配置优先。默认值会被覆盖。
+        Config.loadAlarmConfig();
+
+        Config.enable_NTP_Server(this,!Config.disable_ntp_server);
+
+
+        //初始化温度测试相关参数
+        //runtime.temperature_adjustValue= TemperatureUtil.getTempAdjustValue();
+        Config.loadTemperatureSettings(runtime);
+
+
+        //加载存储的健康数据校准值
+        Config.loadPPG_BPH_BPL_SPO2_adjustvalue(this,runtime);
+
+        this.connectionServiceChain.processAttach(this.connection, this.runtime);
+        this.invokeHandlerServiceChain.processAttach(this.connection, this.runtime);
+//        setAlarm(alarmCycle);
+
+
+//        if (Config.LOG_TOFILE)  FileOutputUtil.fileOutput(runtime.getCacheDir(), "log", "初始化网络协议服务");
+        this.locationClient = new LocationClient(this.connection, this.runtime);
+        this.connection.open();
+
+        //启动inner Service
+        startService(new Intent(this, InnerService.class));
+
+
+        this.locationClient.init();
+
+
+        //设置本service为前台运行,不被会被清理
+        Notification notification = new Notification();
+        notification.flags = Notification.FLAG_ONGOING_EVENT;
+        notification.flags |= Notification.FLAG_NO_CLEAR;
+        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
+        startForeground(GRAY_SERVICE_ID, notification);
+
+        //注册接收  时间和tiimezone 变更消息
+        IntentFilter intentFilter = new IntentFilter();
+        intentFilter.addAction("android.intent.action.TIME_SET");
+        intentFilter.addAction("android.intent.action.TIMEZONE_CHANGED");
+        registerReceiver(this.TimeChangeBroadcastReceiver, intentFilter);
+
+        //注册接收 screen on/off 消息
+        intentFilter = new IntentFilter();
+        intentFilter.addAction("android.intent.action.SCREEN_ON");
+        intentFilter.addAction("android.intent.action.SCREEN_OFF");
+        (this.runtime.getContextProxy()).context.registerReceiver(this.screenOnReceiver, intentFilter);
+
+        //注册接收  AT指令结果返回消息
+        intentFilter = new IntentFilter();
+        intentFilter.addAction("com.eqc.intent.action.callback.at");
+        registerReceiver(this.AtCallbackBroadcastReceiver, intentFilter);
+
+        //添加SOSMSG 接收
+        intentFilter = new IntentFilter();
+        intentFilter.addAction(ACTION_QUERY_WEATHER);
+        intentFilter.addAction(ACTION_SEND_EMEGENCY_LOCATION_START);
+        intentFilter.addAction(ACTION_LOCAL_SOS_ACTION);
+        registerReceiver(broadcastSOSReceiver,intentFilter);
+
+        //添加自由锻炼 接收
+        intentFilter = new IntentFilter();
+        intentFilter.addAction(Constants.ACTION_START_PRACTISE);
+        registerReceiver(broadcastPracticeCMDReceiver,intentFilter);
+
+        //初始化Sim信号
+        this.mSignalUtil = SimSignalUtil.getInstance(this);
+
+        //初始化 电池电量监控工具(内部注册接收电池变化)
+        batteryUtil = new BatteryUtil(this.runtime,connection);
+
+        //保证发送心跳时提前获取BatLevel数据
+        int batlevel=batteryUtil.getBatteryLevel(this);
+        runtime.setBattery(String.format("%03d",batlevel));
+        runtime.setBattery(batlevel);
+        ICLogger.i("Battery get from api "+batlevel);
+
+
+        boolean charging = batteryUtil.isPowerConnected(this);
+        runtime.setPowerConnected(charging);
+        ICLogger.i("Charging  "+charging);
+//        LedUtil.setRedLedOn(false);
+        if (Config.isL03Tracker){
+
+            if (runtime.isPowerConnected())         {
+                LedUtil.setRedLedOn(true);
+            }else{
+                LedUtil.setRedLedOn(false);
+            }
+        }
+        //api直接获取batterylevel取消注册 receiver, 需要重新注册一下。
+
+        batteryUtil.registerBroadReceiver();
+
+
+        //设置计步清零时间。
+        setCleanStepCountAlarm();
+
+        //设置睡眠时间(开始睡眠监控)
+        setSleepAlarm();
+        //设置起床时间(停止睡眠监控)
+        setWakeAlarm();
+
+
+        //网络协议心跳时间
+        setHeartAlarm();
+
+        //设置心率检测频率
+        setHeartRateDetectAlarm(runtime.getPpgTestCycle()); //3分钟一次
+
+        //获取天气时间
+        setWeatherAlarm();
+
+
+        //获取定位时间
+        needLocateInAfterHeartBeat=true;
+        setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+
+        //设置温度测量间隔时间
+
+        setTempAlarm();
+
+
+        //初始化佩戴检测
+        runtime.anti_test_cycle=Config.getCheckAntiPolingCycle(this);
+        if( runtime.anti_test_cycle>0){
+         //   setAntiAlarm();
+        }
+
+        //初始化蓝牙检测
+        runtime.bleInfo.bleScanCycle=Config.getBleScanCycle(this);
+        if(Config.BLEScanProtocol==1 && runtime.bleInfo.bleScanCycle>0)
+        {
+            setBleScanAlarm(runtime.bleInfo.bleScanCycle);
+        }
+
+        //设置来电模式
+        SimSignalUtil.SetRingMode(this, AudioManager.RINGER_MODE_NORMAL,true);
+
+        //备份DB数据到sd cache目录,为调试方便
+        Util.getDBFile();
+//        test(); //test function
+
+ //更新MCC MNC
+        CellInfoUtil.setCurrentAttachCellInfo(CoreService.getInstance().runtime);
+ //更新IMEI
+        DeviceInfoUtil.updateImei(runtime);
+
+        //设置断网状态
+        Util.setSystemProperties("persist.sys.server_connected","false");
+
+        //启动结束设置标志位,让心率和体温检测可以正常执行。
+        server_starting=false;
+
+        //重置缓存中的在等待命令
+        Deliver.resetCMDReocrdsDB();
+
+        ReConnectToServer();
+    }
+
+    private void test(){
+
+        ICLogger.i("周一清除所有睡眠数据Record");
+        runtime.getDbHelper().deleteSleepData();
+    }
+
+    //检查是否有未读消息需要提醒
+    private  void checkUnreadMessage(){
+
+        String msg=Config.getLastUnReadMessage(this);
+        Util.checkMesageNeedNotifi(msg,runtime);
+
+
+    }
+
+    //内部广播StringMessage
+    public static void DevliverStringMessage(String cmd){
+        CoreService.getInstance().connection.DeliverCMDMessageToSystem(cmd,"");
+    }
+    //内部广播StringMessage
+    public static void DevliverStringMessage(String cmd,String str){
+        CoreService.getInstance().connection.DeliverCMDMessageToSystem(cmd,str);
+    }
+
+    //表带剪断检测报警,此处只是设备本地提醒,并不发送报警信息给服务器。
+    public void checkAlarmMessage(){
+
+
+        if (runtime.Fence_Warning_flag>0 &&  Config.needAllwaysAlarmFenceOut){
+            runtime.Fence_Warning_flag++;
+            WakeLockUtil.ScreenOnWakeLockTemperary(runtime.getContextProxy().context);
+            runtime.getContextProxy().sendMsgBroadcast(runtime.getContextProxy().context.getResources().getString(R.string.alarm_out_wall),2);
+        }
+        if(runtime.Cut_off_flag>0 && Config.needAllwaysAlarmCutOff){
+            runtime.Cut_off_flag++;
+//            WakeLockUtil.ScreenOnWakeLockTemperary(runtime.getContextProxy().context);
+
+            if (Config.A9_noBroadCastActionStrip) {
+                if(Config.needBroadcastCutoffAlarm) {
+                    antiservice.send_cutoff_event_broadcast(1);
+                }
+
+            }
+        }
+
+    }
+
+    //检测久坐提醒
+    public void checkKeepSitting(){
+        String dateyyyyMMDDhhmmss=TimeUtil.getSystemTime3();
+        //为了更新 isInSleepRange, 下面的语句必须执行
+        TimeUtil.getCurrentSleepRecordDate(dateyyyyMMDDhhmmss);
+         if(TimeUtil.isInSleepRange == false) { //不在睡眠时间就是久坐时间段。
+             if (Runtime.lastSitCheckStepCount == -1){
+                 Runtime.lastSitCheckStepCount=runtime.getTotalStepCount();
+                 Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3();
+             }
+             int keepsitRange=Config.getKeepSitRangeInMinutes(this);
+             int minutes=(int)TimeUtil.diffBetween2DateInMinutes(Runtime.lastSitCheckTiimeyyyyMMddHHmmss,dateyyyyMMDDhhmmss);
+             ICLogger.i("SitCheck last SitCheckTime "+ Runtime.lastSitCheckTiimeyyyyMMddHHmmss + " , current checktime "+dateyyyyMMDDhhmmss);
+             ICLogger.i("SitCheck minutes "+ minutes + " , keepsitRange "+keepsitRange);
+             if (minutes >=keepsitRange && keepsitRange>0){
+                if ( (runtime.getTotalStepCount() - Runtime.lastSitCheckStepCount)/minutes < Config.KeepSitJudgementRefValue){
+                    //平均 每分钟活动数 小于参考久坐计步值,表示久坐
+                    ICLogger.i("SitCheck 平均 每分钟活动数 小于参考久坐计步值,表示久坐");
+                    WakeLockUtil.ScreenOnWakeLockTemperary(this);
+                    VibrateUtil.getInstance(this).VibrateOn(true);
+                    Util.mSleep(1000);
+                    runtime.getContextProxy().sendBroadcastSitLongAlarm(); //广播久坐消息
+
+
+                    //提醒后 重置 lastCheckSitTime 以及 lastSitCheckStepCount , 重新计时
+                    Runtime.lastSitCheckStepCount=runtime.getTotalStepCount();
+                    Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3();
+
+                    if(Config.isAlarmTypeEnabled(Runtime.AlarmType.ALARM_SEDENTARY)){
+                        runtime.setAlarmType(Runtime.AlarmType.ALARM_SEDENTARY);
+//                        Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(runtime));
+                        ICLogger.i("triggerSOSLocationProcess ");
+                        locationClient.triggerSOSLocationProcess();
+                    }
+                }else{
+                    //只要 平均每分钟活动数大于参考值,则重置 lastCheckSitTime 以及 lastSitCheckStepCount
+                    ICLogger.i("SitCheck 平均每分钟活动数大于参考值,则重置 lastCheckSitTime 以及 lastSitCheckStepCount");
+                    Runtime.lastSitCheckStepCount=runtime.getTotalStepCount();
+                    Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3();
+                }
+            }
+        }else{
+             Runtime.lastSitCheckStepCount=-1; //不在时间段就重置数据,以便下一次使用能过重新开始计数。
+        }
+
+
+    }
+
+    public void updateSleepDate(){
+        String dateyyyyMMDDhhmmss=TimeUtil.getSystemTime3();
+        String sleepdate=TimeUtil.getCurrentSleepRecordDate(dateyyyyMMDDhhmmss);
+        ICLogger.i("updateSleepDate "+sleepdate);
+        if(TimeUtil.isInSleepRange == true) {
+            runtime.getDbHelper().insertSleepRecord(new SleepRecord(dateyyyyMMDDhhmmss,sleepdate,runtime.getTotalStepCount()));
+            runtime.sleepDataReported=false; //只要记录过数据 就证明有数据没有report
+        }else{
+            if (runtime.sleepDataReported == false) {
+                //calculate sleep data and report it randomly within 1 hour
+                runtime.sleepDataReported = true;
+                int score = runtime.getDbHelper().querySleepScore(sleepdate);
+                if (score > 0) {
+                    ICLogger.i("已经有"+sleepdate+"的睡眠数据!");
+                } else {
+                    SleepInfo si = SleepInfo.getInstance();
+                    si.setDate(sleepdate);
+                    si.calculate_sleepInfo(runtime);
+
+                    runtime.getDbHelper().updateSleepInfo(si);
+                    if (TimeUtil.getWeek().equals("周一")){
+                        ICLogger.i("周一清除所有睡眠数据Record");
+                        runtime.getDbHelper().deleteSleepData();
+                    }
+                    Config.setSleepDate(this, sleepdate);
+                    Config.setSleepScore(this, si.getScore());
+                    Random r = new Random();
+                    int randomint = r.nextInt(30 - 1) + 1;
+                    ICLogger.i("Delayed " + randomint + " minutes , send  sleep info " + si.getCurrentDate()
+                            + " deep " + si.getDeepsleep_minutes()
+                            + " light " + si.getLightsleep_minutes()
+                            + " score " + si.getScore()
+                    );
+//                    Observable.timer(randomint * 60 * 1000L, TimeUnit.MILLISECONDS).subscribe(new Action1<Long>() {
+//                        public void call(Long param1Long) {
+//                        connection.send(protocolAPIHelper);
+                            ICLogger.i("Send  sleep info " + si.getCurrentDate()
+                                    + " deep " + si.getDeepsleep_minutes()
+                                    + " light " + si.getLightsleep_minutes()
+                                    + " score " + si.getScore()
+                            );
+                            if (Config.enableSleep) {
+                                Deliver.sendLocationMSG(protocolAPIHelper.getSleepMSG(SleepInfo.getInstance(), runtime));
+                            }else{
+                                ICLogger.i(" 没有开启睡眠协议,skip send message!");
+                            }
+//                        }
+//                    });
+
+                }
+            }
+        }
+    }
+    public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) {
+        if (paramIntent != null && paramIntent.getAction()!=null) {
+            StringBuilder stringBuilder = new StringBuilder();
+            stringBuilder.append("onStartCommand action=");
+            stringBuilder.append(paramIntent.getAction());
+            stringBuilder.append(" paramInt1=");
+            stringBuilder.append(paramInt1);
+            stringBuilder.append(" paramInt2=");
+            stringBuilder.append(paramInt2);
+            ICLogger.i(stringBuilder.toString());
+//            if (ACTION_ALARM.equals(paramIntent.getAction())) {
+            if (ACTION_LOCATION_ALARM.equals(paramIntent.getAction())) {
+
+
+//                    if (cmcm_call_eiot_into_powersave_mode() == 1) {
+//                        ICLogger.i("2 into powersave return");
+//                        return Service.START_NOT_STICKY;
+//                    }
+
+//                //wakeup后1分钟唤醒一次,5分钟后,心跳改为从配置信息读取的值,默认为3分钟
+//                if (this.startAlarmCount < 5 && alarmCycle == 1) {
+//                    this.startAlarmCount++;
+//                } else {
+//                    alarmCycle = Config.getAlarmCycle(this);
+//                }
+                AlarmWakeUp.setAlarmWakeUpTime();
+                boolean screenon = ((PowerManager) getSystemService(POWER_SERVICE)).isScreenOn();
+                if (!screenon) {
+                    SimSignalUtil.send_at_to_update_lbs(this.runtime);
+                }
+                //这里就是为了省电,如果wifi开启,且屏幕关闭,则wifi也关闭 ,还有获取wifi消息的时候也和它有关
+                if (Util.isConnectWifi((this.runtime.getContextProxy()).context) && !screenon) {
+                    is_wifi_network_ok = true; //如果wifi开启的,则记录wifi状态为开启,以后屏幕开启时,再根据此变量决定是否打开wifi
+                    Util.turnOffWifiForSleep((this.runtime.getContextProxy()).context, this.runtime);
+                }
+//                setAlarm(alarmCycle);
+//                if (Config.LOG_TOFILE) FileOutputUtil.fileOutput(runtime.getCacheDir(), "alarmCycle", "ALARM alarmCycle");
+
+                //发送心跳间隔广播给其他应用
+                this.runtime.getContextProxy().sendBroadcast(ACTION_EQC_ALARM, this.runtime);
+                this.locationClient.onAlarm(getWakeLock(1));
+                this.connectionServiceChain.processAlarmClock(this.connection, this.runtime);
+                this.invokeHandlerServiceChain.processAlarmClock(this.connection, this.runtime);
+//                if (SystemClock.elapsedRealtime() - this.mWeatherTime > 60000L && this.mHaveSetWeatherAlarm) {
+//                    setWeatherAlarm();
+//                    this.mHaveSetWeatherAlarm = false;
+//                    return Service.START_NOT_STICKY;
+//                }
+
+
+                //收到定时定位消息
+                setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+                StringBuilder stringBuilder1 = new StringBuilder();
+                stringBuilder1.append("LOCATION_ALARM  work mod=");
+                stringBuilder1.append(runtime.getLocationInstance().getWorkingMod());
+                if (Config.LOG_TOFILE) ICLogger.logToFile("alarmCycle", stringBuilder1.toString());
+//                this.locationClient.triggerLocationProcess();
+
+            }else if (Constants.ACTION_ALARM_BLE_SCAN.equals(paramIntent.getAction())) {
+                    //循环蓝牙扫描
+                setBleScanAlarm(runtime.bleInfo.bleScanCycle);
+
+            }else if (Constants.ACTION_PRACTICE_REPORT_ALARM.equals(paramIntent.getAction())) {
+                //alarm是延迟的,所以这个判断主要是给最后一次可能无效的测量
+                if (Runtime.practising==true) {
+                    //开始下一轮健康测量
+                    setPracticeAlarm();
+                }
+            }else if (Constants.ACTION_CHECK_SERVER_RESPONSE.equals(paramIntent.getAction())) {
+                //暂时还使用 ScheduledThreadPoolExecutor , 时间要求不是那么的严格
+            }else if (Constants.ACTION_RETRY_SERVER_CONNECT.equals(paramIntent.getAction())) {
+                //暂时还使用 ScheduledThreadPoolExecutor , 时间要求不是那么的严格
+            }else if (Constants.ACTION_CHECK_LOCATION_RESULT.equals(paramIntent.getAction())) {
+                locationClient.waitAndSendLocation();
+            }else if (Constants.SLEEP_ALARM.equals(paramIntent.getAction())) {
+                StringBuilder stringBuilder1;
+                ICLogger.i("SLEEP_ALARM");
+                is_allowed_in_sleep_mode = 1;
+                if (Config.LOG_TOFILE) ICLogger.logToFile("alarmCycle", "SLEEP_ALARM  alarmCycle");
+                setSleepAlarm();
+                boolean bool = ((PowerManager) getSystemService(POWER_SERVICE)).isScreenOn();
+                stringBuilder1 = new StringBuilder();
+                stringBuilder1.append("ifOpen = ");
+                stringBuilder1.append(bool);
+                ICLogger.i(stringBuilder1.toString());
+                if (!bool) {
+                    is_in_sleep_mode = true;
+                    if (this.mKeepAlive != null)
+                        this.mKeepAlive.setSleepMode(true);
+//                        this.connection.close();
+                    return Service.START_STICKY;
+                }
+            } else if (Constants.WAKE_ALARM.equals(paramIntent.getAction())) {
+                if (is_in_sleep_mode) {
+                    is_in_sleep_mode = false;
+                    if (Config.LOG_TOFILE)
+                        ICLogger.logToFile("alarmCycle", "WAKE_ALARM  alarmCycle");
+                    if (this.mKeepAlive != null)
+                        this.mKeepAlive.setSleepMode(false);
+                    wakeUpFromSleep();
+                }
+                is_allowed_in_sleep_mode = 1;
+                setWakeAlarm();
+                return Service.START_STICKY;
+            } else if (ANTI_ALARM.equals(paramIntent.getAction())) {
+                //测试是否佩戴
+                antiservice.CheckAntiByPoling();
+                if (Config.LOG_TOFILE)
+                    ICLogger.logToFile("alarmCycle", "ANTI_ALARM alarmCycle  ");
+                setAntiAlarm();
+
+                return Service.START_STICKY;
+//                if (this.mKeepAlive != null) {
+//
+//                    if (connection.isServerConnected() && runtime.isServerProtocolConnected()) {
+//                    }
+//                    return Service.START_STICKY;
+//                }
+            } else if (TEMP_ALARM.equals(paramIntent.getAction())) {
+
+                setTempAlarm();
+
+               return Service.START_STICKY;
+            } else if (HEART_ALARM.equals(paramIntent.getAction())) {
+
+                locationClient.updateStepCount();
+                updateSleepDate(); //检查睡眠
+                checkKeepSitting();//检查久坐
+                checkAlarmMessage();//检测是否有报警消息需要显示
+                checkUnreadMessage();//检查未读消息
+                if (this.mKeepAlive != null) {
+                    if (connection.isServerConnected() && runtime.isServerProtocolConnected()) {
+                        this.mKeepAlive.onHeartAlarm(this.connection, this.runtime);
+                        ICLogger.i("triggerBLEProcess ");
+                        locationClient.triggerBLEProcess();//每次心跳检测一次BLE
+                        Deliver.triggerSendThread();
+                    } else {
+                       // if (this.mKeepAlive.is_retry_time_above_limit()) {
+                            ICLogger.i("check 发送心跳包时,如果发现服务器没有响应,或者socket连接,则重新尝试连接服务器!");
+                            connection.disconnectServer();
+                            this.startConnectionRetryTimer();
+                       // }else{
+                      //      ICLogger.i("");
+                      //  }
+                    }
+                    //检测电池电量 并上报低电报警
+                    batteryUtil.getBatteryLevel(this);
+                    setHeartAlarm();
+                    if (Config.LOG_TOFILE)
+                        ICLogger.logToFile("alarmCycle", "HEART_ALARM alarmCycle  ");
+                    return Service.START_STICKY;
+                }
+            } else if (STEP_COUNT_ALARM_ACTION.equals(paramIntent.getAction())) {
+                ICLogger.i("Reset Count At 00:00 ");
+                //update stepCount and broadcast before reset
+                this.locationClient.updateStepCount(); //先记录下最后一次步数
+                runtime.getContextProxy().brodcastResetStepCount(runtime.getTotalStepCount());
+                updateSleepDate();//更新睡眠信息
+
+                //更新 运动控制的上次步数 然后再resetstecount
+                //runtime.setLastStepCount(runtime.getTotalStepCount()-runtime.getLastStepCount());
+                //runtime.setLastStepCountForBT(runtime.getTotalStepCount()-runtime.getLastStepCountForBT());
+                 resetStepCount();
+                //此处本来应该把刚刚reset前运动的步数设置到计步器里,继续开始计步。
+                // 由于计步接口没有提供设置步数。所以暂时只能清零,不能解决午夜还在运动的情况,会丢失一两次的数据。但是影响不大
+                runtime.setLastStepCountForBT(0);
+                runtime.setLastStepCount(0);
+                //重置后马上跟新当前步数为0, 以便及时更新睡眠信息 一分钟内更新的步数可以忽略不记,从而平滑切换 0点reset 计步数据的计算问题
+                this.locationClient.updateStepCount();
+                //更新睡眠信息
+                updateSleepDate();
+                //清除已经发送的历史记录
+                runtime.getDbHelper().clearCMDRecordsHaveSent();
+                setCleanStepCountAlarm();
+                Config.logBootDate(this);//重置步数的时候,要把开机时间也更新一下,否则第二天 任意时间重启都会造成计步数据清零
+                return Service.START_STICKY;
+            } else if (ACTION_HEATR_RATE_START.equals(paramIntent.getAction())) {
+
+                //此处消息从timer来
+                //此消息来源于BroadCaset,收到开始测试的消息。
+                //此时需要重置HeartRateDetect Timer
+                //倘若有 参数 PPGTestCycle,则根据这个数值进行设置
+                int ppgtestCycle=paramIntent.getIntExtra("PPGTestCycle",-1);
+                if (ppgtestCycle >0){
+                    Config.setPPGTestCycle(runtime.getContextProxy().context,ppgtestCycle);
+                    runtime.setPpgTestCycle(Config.getPPGTestCycle(runtime.getContextProxy().context));
+                    ICLogger.i("get and set PPGTestCycle "+ppgtestCycle);
+                }
+                setHeartRateDetectAlarm(runtime.getPpgTestCycle());//重置心率检测周期,并触发一次检测
+
+            } else if (ACTION_SEND_EMEGENCY_LOCATION_STOP.equals(paramIntent.getAction())) {
+                //stop Emegency location Stop
+                Config.loadModCycleSettings(runtime); //回复之前的 工作模式即可
+                LocationClient.setForceLocation(1);
+                setLocationAlarm(runtime.getLocationInstance().getWorkingMod());//同时重置alarm并触发定位
+
+            }else if(ACTION_CHECK_ANTIOFF_EVENT.equals(paramIntent.getAction())){
+                //只在中断式检测过程中延时用
+                antiservice.check_ant_event();
+            }
+
+            this.invokeHandlerServiceChain.processUserRequest(paramIntent, this.connection, this.runtime);
+
+        }
+        return Service.START_NOT_STICKY;
+    }
+
+    public boolean onUnbind(Intent paramIntent) { return false; }
+
+    //每一分钟设置一次
+    public void setAlarm(int paramInt) {
+//        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,paramInt,ACTION_ALARM);
+    }
+
+    public void setHeartRateDetectAlarm(int heartRateDetectAlarmCycle){
+        if (Config.noPPGSensor) {
+            ICLogger.i("setHeartRateDetectAlarm oPPGSensor");
+            return;
+        }
+        StringBuilder sb=new StringBuilder();
+        if (heartRateDetectAlarmCycle>1) {
+            AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context, heartRateDetectAlarmCycle, ACTION_HEATR_RATE_START);
+        }
+
+        if(runtime.check_stat_do_ppg_test()) {
+            if (Runtime.practising == true) {
+                sb.append("自由锻炼中,跳过原有的循环心率检测!");
+                ICLogger.i("自由锻炼中,跳过原有的循环心率检测!");
+            } else {
+                sb.append("setHeartRateDetectAlarm " + heartRateDetectAlarmCycle);
+                if(!server_starting)
+                    HeartRateManager.triggerPPGtest();
+            }
+        }
+        if (Config.LOG_TOFILE)ICLogger.logToFile("alarmCycle",sb.toString());
+    }
+
+    public void setBleScanAlarm(int cycle){
+        if (Config.BLEScanProtocol!=1) {
+            ICLogger.i("BLEScanProtocol!=1  skip setPolingCheckAntiAlarm");
+            return;
+        }
+        StringBuilder sb=new StringBuilder();
+        if (cycle>1) {
+            AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context, cycle, ACTION_ALARM_BLE_SCAN);
+        }
+        sb.append("setBleScanAlarm " + cycle);
+        locationClient.triggerBLEProcess();
+        ICLogger.i(sb.toString());
+        if (Config.LOG_TOFILE)ICLogger.logToFile("alarmCycle",sb.toString());
+    }
+
+    public void setEmegencyLocationSTOPAlarm(int delayTimeInMinutes){
+        StringBuilder sb=new StringBuilder();
+        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,delayTimeInMinutes, ACTION_SEND_EMEGENCY_LOCATION_STOP);
+        sb.append(" tEmegencyLocationSTOPAlarm  "+ACTION_SEND_EMEGENCY_LOCATION_STOP);
+//        ICLogger.i(sb.toString());
+        if (Config.LOG_TOFILE)ICLogger.logToFile("alarmCycle",sb.toString());
+    }
+    public void setLocationAlarm(int mod) {
+//        int mod=runtime.getLocationInstance().getWorkingMod();
+        StringBuilder sb=new StringBuilder();
+        int cycle=60;
+        switch(mod){
+            case EMERGNECY_MOD:
+            case REALTIME_MOD:
+                cycle=60;
+                break;
+            case NORMAL_MOD:
+                cycle=15*60;
+                break;
+            case LOWPOWER_MOD:
+                cycle=60*60;
+                break;
+            case CUSTOM_MOD:
+            case CUSTOM_MOD8_GPS:
+            case CUSTOM_MOD8_WIFI:
+                cycle=runtime.getLocationInstance().getLocation_cycle();
+                break;
+        }
+        if(cycle == 0)
+        {
+            ICLogger.i("locationCycle == 0 stop Location !");
+            Config.noLocationCycle=true;
+        }
+        if (Config.noLocationCycle==false)
+            AlarmHelper.setRealTimeAlarmInSeconds(runtime.getContextProxy().context,cycle, ACTION_LOCATION_ALARM);
+        else
+            ICLogger.i("skip set LocationAlarm " );
+        sb.append(" setLocationAlarm  "+ACTION_LOCATION_ALARM+" mod "+mod+", cycle in Seconds "+cycle);
+        ICLogger.i(sb.toString());
+        if (Config.LOG_TOFILE) FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());
+
+//        if (Runtime.practising==true) {
+//            ICLogger.i("自由锻炼中,跳过原有的循环定位!");
+//            return;
+//        }
+        ICLogger.i("triggerLocationProcess ");
+        locationClient.triggerLocationProcess();
+
+    }
+
+    public void setHeartAlarm(){
+//        int mod=runtime.getLocationInstance().getWorkingMod();
+        StringBuilder sb=new StringBuilder();
+        int cycle=runtime.getHeartBeatCycle();
+
+        //心跳指令默认设置
+        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,cycle, HEART_ALARM);
+        sb.append(" setHeartAlarm  "+HEART_ALARM+", cycle "+cycle);
+//        locationClient.triggerLocationProcess();
+        ICLogger.i(sb.toString());
+        FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());
+
+//        AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,1, HEART_ALARM);
+    }
+    public void setAntiAlarm(){
+//        int mod=runtime.getLocationInstance().getWorkingMod();
+        StringBuilder sb=new StringBuilder();
+        int cycle=runtime.anti_test_cycle;
+        if(cycle>1) {
+            AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context, cycle, ANTI_ALARM);
+        }
+        sb.append(" setHeartAlarm  "+ANTI_ALARM+", cycle "+cycle);
+
+        ICLogger.i(sb.toString());
+        FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());
+    }
+    public void setTempAlarm(){
+//        int mod=runtime.getLocationInstance().getWorkingMod();
+        StringBuilder sb=new StringBuilder();
+        int cycle=runtime.temp_test_Cycle;
+
+        if(Config.noTempSensor) {
+            ICLogger.i("setTempAlarm noTempSensor");
+            return;
+        }
+        if (cycle>1) {
+            AlarmHelper.setRealTimeAlarmInSeconds(runtime.getContextProxy().context, cycle, TEMP_ALARM);
+            sb.append(" setTempAlarm  " + TEMP_ALARM + ", cycle " + cycle);
+        }else {
+            sb.append(" setTempAlarm  " + TEMP_ALARM + ", cycle " + cycle+"<=1 skip!");
+        }
+//        locationClient.triggerLocationProcess();
+        ICLogger.i(sb.toString());
+        FileOutputUtil.fileOutput(runtime.getCacheDir(),"alarmCycle",sb.toString());
+
+        if(runtime.check_stat_do_temp_test()) {
+            if (Runtime.practising == true) {
+                ICLogger.i("自由锻炼中,跳过原有的循环温度检测!");
+            } else {
+                if(!server_starting)
+                    TemperatureUtil.doTempTestInThread();
+            }
+        }
+
+    }
+    public void setUpLocationDataAlarm(long paramLong) {
+        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
+        Intent intent = new Intent(this, CoreService.class);
+        intent.setAction(ACTION_ALARM_ADD_DATAPOINTS);
+        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, FLAG_UPDATE_CURRENT);
+        alarmManager.cancel(pendingIntent);
+        alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + paramLong, pendingIntent);
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append("interval=");
+        stringBuilder.append(paramLong);
+        ICLogger.i(stringBuilder.toString());
+        AlarmHelper.setRealTimeAlarm( runtime.getContextProxy().context,(int)((System.currentTimeMillis() + paramLong)/1000),ACTION_ALARM_ADD_DATAPOINTS);
+    }
+
+    public static class InnerService extends Service {
+        public IBinder onBind(Intent param1Intent) { return null; }
+
+        /*给 API >= 18 的平台上用的灰色保活手段*/
+        public int onStartCommand(Intent param1Intent, int param1Int1, int param1Int2) {
+            startForeground(GRAY_SERVICE_ID, new Notification());
+            stopForeground(true);
+            stopSelf();
+            return super.onStartCommand(param1Intent, param1Int1, param1Int2);
+        }
+    }
+
+    private static class RequestHandler extends Handler {
+        private final WeakReference<CoreService> mReference;
+
+        RequestHandler(CoreService param1CoreService) {
+            this.mReference = new WeakReference(param1CoreService);
+        }
+
+        public void handleMessage(Message param1Message) {
+            CoreService coreService = (CoreService)this.mReference.get();
+            if (coreService == null)
+                return;
+            coreService.invokeHandlerServiceChain.processUserRequest(param1Message, coreService.connection, coreService.runtime);
+        }
+    }
+
+    private static final String TAG = "ICSrv." + CoreService.class.getSimpleName();
+
+    private ScheduledThreadPoolExecutor mTimer_retry_connect=null;
+
+    private static int retry_connect_count=0;  //当前重试次数
+    private static int retry_connect_max_times=6; //最大重试次数 6次 , 即只重试2分钟,下一次重试将在下一个心跳包时进行。
+    private static int retry_cocnnect_cycle=20; //重试间隔20秒
+    private void log(String msg) {
+        ICLogger.log(TAG,msg);
+    }
+
+    public static CoreService getInstance(){
+        return mProtocolServer;
+    }
+
+    public void startConnectionRetryTimer(){
+        //联网再重试连接服务器, 不能够联网的情况下不管是不是有sim卡,以及是否联网,都进行重试,以便处理下面情况:
+        //1、sim卡接触不良,掉卡,可以尝试用此法恢复
+        //2、网络信号不好,造成临时掉线,但是恢复慢或不恢复,可以用此法尝试恢复
+//        if (SimSignalUtil.checkNet(runtime.getContextProxy().context) ) {
+             stopConnectionRetryTimer();
+            if (mTimer_retry_connect == null) {
+                mTimer_retry_connect = new ScheduledThreadPoolExecutor(10);
+            }
+            //如果开始进行连接重
+                // {
+            // 试,证明网络断开的,那么KeepAlive也需要重连(心跳包)
+            retry_connect_count=0;
+            KeepAlive.isConnected = false;
+            if (mTimer_retry_connect != null) {
+                mTimer_retry_connect.remove(mReConnectSrvThread);
+                mTimer_retry_connect.scheduleAtFixedRate(mReConnectSrvThread, 5000, 20000, TimeUnit.MILLISECONDS); //每次都是断网才需要重连,delay 5秒重连,并且每20秒重试一次
+            }
+//        }
+    }
+    private ReConnectSrvThread mReConnectSrvThread=new ReConnectSrvThread();
+    private class ReConnectSrvThread implements  Runnable{
+        @Override
+        public void run() {
+            ReConnectToServer();
+        }
+    }
+
+    private static int no_network_Heartbeats_Count=0;
+
+    public void ReConnectToServer(){
+        long timeSincelastReceive=0;
+        if(Runtime.lastLinkReceiveStamp>0)
+            timeSincelastReceive=(System.currentTimeMillis()-Runtime.lastLinkReceiveStamp)/1000;
+        if (timeSincelastReceive>0) ICLogger.i("距离上次从服务器收到数据,已经有 " + timeSincelastReceive + " 秒!");
+        if (SimSignalUtil.checkNet(runtime.getContextProxy().context) ) {
+            //里面如果连接成功 connectionOpen 会先发送 AP00 登录包 和发送AP03 心跳包 ,
+            // isServerConnected 成功则停止重试, KeepAlive会检测AP03心跳包的成功与否。此处只管socket连接是否成功
+            if (connection.isServerConnected()) {
+                ICLogger.i("retry  如果连接成功则停止重试!");
+                no_network_Heartbeats_Count=0;
+                stopConnectionRetryTimer();
+            }else {
+                if (retry_connect_count >= retry_connect_max_times) {
+
+                    no_network_Heartbeats_Count++;
+                    ICLogger.i("retry " + retry_connect_count + " 次 >= " + retry_connect_max_times + " ,停止重试!等待下一次心跳再重试! 已经第"+no_network_Heartbeats_Count+"次心跳都没有连接服务器成功!");
+                    stopConnectionRetryTimer();
+
+                } else {
+                    retry_connect_count++;
+                    String ip = runtime.getDnsUtil().getServerIP_ByDNSCache(runtime.getHost());
+                    if (null != ip && !ip.equals(runtime.getSrvIP())) {
+                        runtime.setSrvIP(ip);
+                    }
+                    ICLogger.i("retry 第" + retry_connect_count + " 次 , 连接服务器!");
+                    this.connection.connect(this.runtime.getSrvIP(), this.runtime.getPort());
+
+                }
+            }
+        }else{
+            //没有网络就不用重新尝试连接网络了。网络连接后再重新尝试联网
+            ICLogger.i("retry "+no_network_Heartbeats_Count+" 没有网络就不用重新尝试连接网络了。网络连接后再重新尝试联网!");
+            no_network_Heartbeats_Count++;
+            stopConnectionRetryTimer();
+        }
+        if( no_network_Heartbeats_Count >12){
+            ICLogger.i("当前第"+no_network_Heartbeats_Count+"次心跳都没有连接服务器成功 > 10 ,重置SIM卡尝试重新注册网络!");
+            SimSignalUtil.send_at_to_reset_simcard(runtime); //直接下此命令不能实现断网重连,所以干脆采用关闭网络再打开的方式。
+            SimSignalUtil.setAirMode(this,"OpenAirplane");
+            mHandler.postDelayed(reopenSim,5000); //5秒后重新链接服务器。
+            no_network_Heartbeats_Count=0;//重置Sim卡后重置计数。防止后面多次重置Sim卡。
+        }
+    }
+    private Runnable reopenSim =new Runnable(){
+        @Override
+        public void run() {
+            if (CoreService.getInstance()!=null) {
+                SimSignalUtil.setAirMode(CoreService.getInstance(), "CloseAirplane");
+             //   disconnect_server();
+              //  ReConnectToServer();
+            }
+        }
+    };
+    public void stopConnectionRetryTimer(){
+        if (mTimer_retry_connect !=null){
+            mTimer_retry_connect.shutdownNow();
+//            while(!mTimer_retry_connect.isTerminated())
+//            {
+//                ICLogger.i("Wait for thread pool terminated");
+//                try {
+//                    Thread.sleep(500);
+//                } catch (InterruptedException e) {
+//                    e.printStackTrace();
+//                }
+//            }
+            mTimer_retry_connect.purge();
+            mTimer_retry_connect = null;
+        }
+    }
+
+    private boolean needLogin(){
+        return true;
+    }
+
+
+
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+
+
+        saveStepCount();
+        this.connectionServiceChain.processDetach(this.connection, this.runtime);
+        this.invokeHandlerServiceChain.processDetach(this.connection, this.runtime);
+        this.locationClient.deinit();
+        this.connection.close();
+        unregisterReceiver(this.TimeChangeBroadcastReceiver);
+        unregisterReceiver(this.screenOnReceiver);
+        unregisterReceiver(this.AtCallbackBroadcastReceiver);
+        batteryUtil.unregisterBroadReceiver();
+
+    }
+
+    public void disconnect_server(){
+        this.connection.close();
+    }
+
+
+}
index f00f18e..9faafc4 100644 (file)
-package com.enqualcomm.support;\r
-\r
-import android.app.Activity;\r
-import android.app.PendingIntent;\r
-import android.content.BroadcastReceiver;\r
-import android.content.ComponentName;\r
-import android.content.ContentResolver;\r
-import android.content.Context;\r
-import android.content.ContextWrapper;\r
-import android.content.Intent;\r
-import android.content.IntentFilter;\r
-import android.database.Cursor;\r
-import android.net.Uri;\r
-import android.os.Bundle;\r
-import android.os.Environment;\r
-import android.os.Handler;\r
-import android.os.Message;\r
-import android.os.SystemClock;\r
-import android.telephony.SmsManager;\r
-import android.telephony.SmsMessage;\r
-import android.text.TextUtils;\r
-import android.widget.Toast;\r
-\r
-import com.enqualcomm.support.bean.Contact;\r
-import com.enqualcomm.support.bean.ICLocation;\r
-import com.enqualcomm.support.bean.Runtime;\r
-import com.enqualcomm.support.bean.StringMessage;\r
-import com.enqualcomm.support.service.AudioService;\r
-import com.enqualcomm.support.service.Deliver;\r
-import com.enqualcomm.support.service.SmsDatabaseChaneObserver;\r
-import com.enqualcomm.support.utils.APNUtil;\r
-import com.enqualcomm.support.utils.CameraUtil;\r
-import com.enqualcomm.support.utils.CellInfoUtil;\r
-import com.enqualcomm.support.utils.ContextProxy;\r
-import com.enqualcomm.support.utils.DeviceInfoUtil;\r
-import com.enqualcomm.support.utils.ICAudioManager;\r
-import com.enqualcomm.support.utils.ICHttpUtil;\r
-import com.enqualcomm.support.utils.ICLogger;\r
-import com.enqualcomm.support.utils.SendEmail;\r
-import com.enqualcomm.support.utils.ServiceUtil;\r
-import com.enqualcomm.support.utils.SimSignalUtil;\r
-import com.enqualcomm.support.utils.TimeUtil;\r
-import com.enqualcomm.support.utils.Util;\r
-import com.enqualcomm.support.utils.VibrateUtil;\r
-import com.enqualcomm.support.utils.ftpUtils;\r
-import com.ic.protocols.protocolAPIHelper;\r
-\r
-import java.io.File;\r
-import java.net.MalformedURLException;\r
-import java.net.URL;\r
-import java.util.ArrayList;\r
-import java.util.Iterator;\r
-import java.util.concurrent.TimeUnit;\r
-\r
-import chestnut.utils.PhoneUtils;\r
-\r
-import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;\r
-import static com.enqualcomm.support.Config.upload_logs_via_ftp;\r
-import static com.enqualcomm.support.Constants.ACTION_SMSCMD;\r
-import static com.enqualcomm.support.Constants.ACTION_SMSCMD_Reply;\r
-import static com.enqualcomm.support.Constants.ACTION_SMSCMD_TEST;\r
-import static com.enqualcomm.support.Constants.ACTION_SMS_RECEIVED;\r
-import static com.enqualcomm.support.Constants.ACTION_START_FOTA_UPDATE;\r
-import static com.enqualcomm.support.Constants.DIALOG_ACTION;\r
-import static com.enqualcomm.support.Constants.KeyReplyData;\r
-import static com.enqualcomm.support.Constants.contact;\r
-import static com.enqualcomm.support.utils.DeviceInfoUtil.getDeviceVersion;\r
-import static com.enqualcomm.support.utils.SimSignalUtil.send_at_cmd;\r
-import static com.enqualcomm.support.utils.SimSignalUtil.send_at_setImei0;\r
-import static com.enqualcomm.support.utils.SimSignalUtil.send_at_setImei1;\r
-\r
-\r
-public class ICSmsManager  extends BroadcastReceiver {\r
-\r
-    private static String cell_number_to_reply=""; //this number is use for ACTION_SMSCMD_Reply\r
-\r
-    private static long preTimeMillis;\r
-    private Context mContext = null;\r
-    Runtime runtime;\r
-\r
-    Handler mHandler=new Handler(new Handler.Callback() {\r
-        @Override\r
-        public boolean handleMessage(Message message) {\r
-\r
-            if (message.what==100){\r
-\r
-                Bundle param = message.getData();\r
-                if (param!=null){\r
-\r
-                    String from = param.getString("SMSFrom");\r
-                    String smsmessage = param.getString("SMSData");\r
-\r
-                    long currenttime = System.currentTimeMillis();\r
-//                    if (currenttime - ICSmsManager.preTimeMillis > 30000L) {\r
-                        ICSmsManager.preTimeMillis = currenttime;\r
-                        (new Thread(new Runnable() {\r
-                            public void run() {\r
-                                SystemClock.sleep(3000L);\r
-                                ICLogger.i("收到" + from + "短信:" + smsmessage);\r
-//                         Toast.makeText(context, "收到" + from + "短信:" + smsmessage, Toast.LENGTH_LONG).show();\r
-                                if (handleSMS_CMD(from, smsmessage) == false) {\r
-                                    //说明不是sms命令,提示短信接收。\r
-                                    ContextProxy.sendMsgBroadcast(mContext, smsmessage, 1);\r
-                                }\r
-                            }\r
-                        })).start();\r
-//                    }\r
-\r
-\r
-                }\r
-\r
-\r
-            }\r
-\r
-\r
-\r
-            return false;\r
-        }\r
-    });\r
-\r
-    ReplayLocation replayLocation=new ReplayLocation();\r
-\r
-    @Override\r
-    public void onReceive(Context context, Intent intent) {\r
-\r
-        if (CoreService.getInstance()==null) {\r
-            ICLogger.i("CoreService still not started , skip SMS cmd!");\r
-            return;\r
-        }\r
-        mContext=context;\r
-        runtime=CoreService.getInstance().runtime;\r
-\r
-\r
-        String action = intent.getAction();\r
-        ICLogger.i(" onReceive Action "+action);\r
-        if (ACTION_SMSCMD.equals(action)) {\r
-            String cmd = intent.getStringExtra("smsCmd");\r
-            handleSMS_CMD("", cmd);\r
-        }else if (ACTION_SMSCMD_Reply.equals(action)) {\r
-            String replydata = intent.getStringExtra(KeyReplyData);\r
-            sendSMS(cell_number_to_reply, replydata);\r
-            cell_number_to_reply = "";\r
-        }else if (ACTION_SMSCMD_TEST.equals(action)){\r
-            String cmd = intent.getStringExtra("cmd");\r
-            String arg = intent.getStringExtra("arg1");\r
-            handle_test_cmd(cmd,arg);\r
-        }else if (ACTION_SMS_RECEIVED.equals(action)) {\r
-            long currenttime = System.currentTimeMillis();\r
-//            if (currenttime - ICSmsManager.preTimeMillis > 30000L) {\r
-                ICSmsManager.preTimeMillis = currenttime;\r
-//                (new Thread(new Runnable() {\r
-//                    public void run() {\r
-                        SystemClock.sleep(3000L);\r
-                        if (intent == null || intent.getAction() == null) return;\r
-\r
-                        //长短信会被分拆送来,因此可能会有多个PDU。Protocol Description Unit是短信的工业标准。 \r
-                        Object[] pduArray = (Object[]) intent.getExtras().get("pdus");\r
-                        ICLogger.i("pdu number=" + pduArray.length);\r
-                        String message = "";\r
-                        String from = null;\r
-                        for (int i = 0; i < pduArray.length; i++) {\r
-                            SmsMessage sms = SmsMessage.createFromPdu((byte[]) pduArray[i]);//将PDU转换为SmsMessage格式\r
-                            ICLogger.i("From : " + sms.getDisplayOriginatingAddress());\r
-                            ICLogger.i("SMS : " + sms.getDisplayMessageBody());\r
-                            from = sms.getDisplayOriginatingAddress();\r
-                            message += sms.getDisplayMessageBody();\r
-                        }\r
-                        ICLogger.i("收到" + from + "短信:" + message);\r
-//                         Toast.makeText(context, "收到" + from + "短信:" + message, Toast.LENGTH_LONG).show();\r
-                        if (handleSMS_CMD(from, message) == false) {\r
-                            //说明不是sms命令,提示短信接收。\r
-                            ContextProxy.sendMsgBroadcast(context, message, 1);\r
-                        }\r
-//                    }\r
-//                })).start();\r
-//            }\r
-        }\r
-\r
-    }\r
-\r
-    public class ReplayLocation implements LocationClient.LocationResponseUrl {\r
-\r
-        @Override\r
-        public void replyCallBack(String locationResponseUrl) {\r
-\r
-            LocationClient locationClient=LocationClient.getInstance();\r
-            if (locationClient!=null){\r
-                locationClient.setLocationResponse(null);\r
-            }\r
-            sendSMS(cell_number_to_reply,"http://maps.google.com/?q="+locationResponseUrl);\r
-            cell_number_to_reply="";\r
-\r
-        }\r
-    }\r
-    public ICSmsManager( ) {\r
-\r
-\r
-    }\r
-\r
-    public ICSmsManager( Runtime _runtime) {\r
-        this.runtime = _runtime;\r
-        this.mContext = runtime.getContextProxy().context;\r
-        IntentFilter intentfilter=new IntentFilter();\r
-        intentfilter.addAction(ACTION_SMSCMD_Reply);\r
-        this.mContext.registerReceiver(this,intentfilter);\r
-//        registerSmsDatabaseChangeObserver(mContext);\r
-    }\r
-\r
-    public void sendSMS(String phonenumber, String msg) {\r
-        android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();\r
-        Iterator msgit = smsManager.divideMessage(msg).iterator();\r
-\r
-        while(msgit.hasNext()) {\r
-            String message= (String)msgit.next();\r
-            ICLogger.i("reply message to "+phonenumber+", "+message);\r
-            if (phonenumber!=null && !phonenumber.isEmpty()) {\r
-                smsManager.sendTextMessage(phonenumber, (String) null, message, (PendingIntent) null, (PendingIntent) null);\r
-            }\r
-        }\r
-    }\r
-\r
-    private boolean isAdminNumber(String phoneNumb){\r
-\r
-        return true;\r
-    }\r
-\r
-    private void broadCastStartFotaUpdate(Context context){\r
-\r
-        Intent intent = new Intent();\r
-        intent.setAction(ACTION_START_FOTA_UPDATE);\r
-        context.sendBroadcast(intent);\r
-\r
-    }\r
-\r
-\r
-    //1:短信设置服务器\r
-    //#ip#=198.11.183.28,5088#\r
-    //回复 ip set ok\r
-    //\r
-    //2:短信写IMEI\r
-    //#imei:108111804000475\r
-    //回复  imri write ok\r
-    //\r
-    //3:  短信增加APN\r
-    //#apn#=MCC,MNC,apn name,apn name,user name,password#\r
-    //回复  APN set ok\r
-    //\r
-    //4:远程查询软件版本和IMEI号码\r
-    //#status#\r
-    //回复\r
-    //IMEI: 353503535035350\r
-    //SW: L02_20200208_V1\r
-\r
-\r
-    public String RemoveEncrypedHeader(String sms){\r
-        String smsPWD=Config.getSMSPwd(mContext);\r
-        if(!smsPWD.equals("none")){\r
-            if (!sms.startsWith(smsPWD)){\r
-                ICLogger.i("开头不是密码!");\r
-            }else{\r
-                //ICLogger.i("开头不是密码!");\r
-                return sms;\r
-            }\r
-        }else{\r
-            return sms;\r
-        }\r
-        return sms;\r
-    }\r
-\r
-    /*\r
-    *  return false表示不是命令, true表示是命令,且已经执行\r
-    * */\r
-    public boolean handleSMS_CMD(String phonenumber, String sms){\r
-        if (isAdminNumber(phonenumber)) {\r
-\r
-            String ENCRYPED_HEADER = Config.getSMSPwd(mContext);\r
-            if (ENCRYPED_HEADER.equals(Config.DefaultSMSPassword)) {\r
-                ENCRYPED_HEADER = "";\r
-            }\r
-\r
-            if (sms == null || sms.trim().isEmpty()) return false;\r
-\r
-            ICLogger.i("received SMSCMD "+sms);\r
-            sms=sms.trim();\r
-            if (sms.equals(ENCRYPED_HEADER + "#logctl#=upload,all")){\r
-                sms=ENCRYPED_HEADER+"#logctl#=upload,SDLog:Android/ic";\r
-            }\r
-            //$HX,SSER,OK,91.201.4.79,5018,C,589883\r
-            if (sms.startsWith(ENCRYPED_HEADER+"$HX,SSER,OK,")){\r
-                String[] tmplist=sms.split(",");\r
-                if (tmplist.length==7){\r
-                    String ServeriIp=tmplist[3];\r
-                    String ServerPort=tmplist[4];\r
-                    String imeiend=tmplist[6];\r
-                    if (runtime.IMEI().endsWith(imeiend)) {\r
-                        sms=ENCRYPED_HEADER+"#IP#="+ServeriIp+":"+ServerPort+"#";\r
-                        ICLogger.i("收到客户自定义 服务器IP设置命令,转化为 #IP#命令!");\r
-                    }else{\r
-                        sendSMS(phonenumber, imeiend+" IMEI 校验错误!");\r
-                        return true;\r
-                    }\r
-                }else{\r
-                    ICLogger.i(" 设置 Server IP 命令错误。");\r
-                    sendSMS(phonenumber, sms+" 格式错误!");\r
-                    return true;\r
-                }\r
-            }\r
-            if (sms.startsWith(ENCRYPED_HEADER+"#apn#=") && sms.endsWith("#")) {\r
-                String[] tmp = sms.split("#");\r
-                if (tmp.length == 3) {\r
-                    String[] apnvalues = tmp[2].replace("=", "").split(",");\r
-                    if (apnvalues.length == 4) {\r
-                        String mcc = apnvalues[0];\r
-                        String mnc = apnvalues[1];\r
-                        String apnName = apnvalues[2];\r
-                        String apn = apnvalues[3];\r
-                        String user = "";\r
-                        String password = "";\r
-                        if (APNUtil.addVPN(mcc, mnc, apnName, apn, user, password, mContext) == true) {\r
-                            sendSMS(phonenumber, "apn add success!");\r
-                        } else {\r
-                            sendSMS(phonenumber, "apn add failed!");\r
-                        }\r
-                    } else if (apnvalues.length == 6) {\r
-                        String mcc = apnvalues[0];\r
-                        String mnc = apnvalues[1];\r
-                        String apnName = apnvalues[2];\r
-                        String apn = apnvalues[3];\r
-                        String user = apnvalues[4];\r
-                        String password = apnvalues[5];\r
-                        if (APNUtil.addVPN(mcc, mnc, apnName, apn, user, password, mContext) == true) {\r
-                            sendSMS(phonenumber, "apn add success!");\r
-                        } else {\r
-                            sendSMS(phonenumber, "apn add failed!");\r
-                        }\r
-                    } else if (apnvalues.length == 1) {\r
-                        if (apnvalues[0].equals("current")) {\r
-\r
-                            String apnstr = APNUtil.getCurrentAPN(mContext);\r
-                            sendSMS(phonenumber, apnstr);\r
-                        }else  if (apnvalues[0].equals("check")) {\r
-                            String mcc=runtime.getLocationInstance().getMCC();\r
-                            String mnc=runtime.getLocationInstance().getMNC();\r
-                            String apnstr = APNUtil.checkAPN(mcc,mnc,mContext);\r
-                            sendSMS(phonenumber, apnstr);\r
-                        } else {\r
-                            sendSMS(phonenumber, "apn cmd format error!");\r
-                        }\r
-                    } else {\r
-                        sendSMS(phonenumber, "apn cmd format error!");\r
-                    }\r
-                } else {\r
-\r
-                    sendSMS(phonenumber, "apn cmd format error!");\r
-\r
-                }\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#deviceinfo#")) {\r
-//                ICLogger.i("SMS " + sms + " reply " + DeviceInfoUtil.getDeviceVersion(runtime));\r
-//                sendSMS(phonenumber, DeviceInfoUtil.getDeviceVersion(runtime));\r
-                ICLogger.i("SMS " + sms + " reply " + DeviceInfoUtil.getShortDeviceInfo(runtime));\r
-                sendSMS(phonenumber, DeviceInfoUtil.getShortDeviceInfo(runtime));\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#status#")) {\r
-                String reply = "IMEI=" + runtime.IMEI() + "\nSW:" + DeviceInfoUtil.getVersionCode(mContext) + " " + DeviceInfoUtil.getSWVersionDisplayName()+"\nBattery:"+runtime.getBattery()+"%";\r
-\r
-                ICLogger.i("SMS " + sms + " reply \n" + reply);\r
-                sendSMS(phonenumber, reply);\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#atcmd#=")) {\r
-                String cmd = sms.substring(8);\r
-                ICLogger.i("atcmd  " + cmd);\r
-                if (cmd.length() >0 ) {\r
-                    send_at_cmd(runtime,cmd);\r
-                    sendSMS(phonenumber, "run At cmd "+cmd+"!");\r
-                }  else {\r
-                    sendSMS(phonenumber, "At cmd empty error!");\r
-                }\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#imei:")) {\r
-                String imei = sms.substring(6);\r
-                ICLogger.i("SMS " + sms + " imei=" + imei);\r
-                if (imei.length() == 15) {\r
-                    send_at_setImei0(runtime,imei);\r
-                    Config.setIMEI(mContext, imei);\r
-                    runtime.setImeiAndCid(imei, "");\r
-                    sendSMS(phonenumber, "set IMEI " + imei + " success !");\r
-                    CoreService.getInstance().disconnect_server();\r
-                    CoreService.getInstance().ReConnectToServer();\r
-                } else if (imei.equals("reset")) {\r
-                    Config.setIMEI(mContext, "");\r
-                    runtime.setImeiAndCid(PhoneUtils.getIMEI(mContext), "");\r
-                    sendSMS(phonenumber, "reset IMEI to " + PhoneUtils.getIMEI(mContext) + " success !");\r
-                    CoreService.getInstance().disconnect_server();\r
-                    CoreService.getInstance().ReConnectToServer();\r
-                } else if (imei.equals("current")) {\r
-                    sendSMS(phonenumber, "Current IMEI " + runtime.IMEI());\r
-                } else {\r
-                    sendSMS(phonenumber, "set IMEI " + imei + "  failed ! len!=15");\r
-                }\r
-            } else if ((sms.startsWith(ENCRYPED_HEADER+"#ip#=") || sms.startsWith(ENCRYPED_HEADER+"#host#=")) && sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                String reply = "";\r
-                ICLogger.i(sms + " len " + tmp.length);\r
-                if (tmp.length == 2) {\r
-                    if (tmp[1].equals("reset#")) {\r
-                        Config.setCustomServer(mContext,false, protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());\r
-                        reply = "reset ServerIP to " + protocolAPIHelper.getDefaultServerIP() + ":" + protocolAPIHelper.getDefaultServerPort() + " success! ";\r
-                        Config.loadServerSettings(runtime);\r
-                        CoreService.getInstance().disconnect_server();\r
-                        CoreService.getInstance().ReConnectToServer();\r
-                    } else if (tmp[1].equals("current#")) {\r
-                        reply = "current serverAddress:" + runtime.getHost() + ":" + runtime.getPort();\r
-                    } else {\r
-                        //分析 以 , 为分界的格式\r
-                        String[] ipstr = tmp[1].split(",");\r
-                        if (ipstr.length == 2) {\r
-                            String ip = ipstr[0];\r
-                            int port = Integer.valueOf(ipstr[1].replace("#", ""));\r
-                            Config.setCustomServer(mContext,true,ip,port);\r
-                            reply = sms + " success! ";\r
-                            Config.loadServerSettings(runtime);\r
-                            CoreService.getInstance().disconnect_server();\r
-                            CoreService.getInstance().ReConnectToServer();\r
-                        } else {\r
-                            //分析以 : 为分界的格式\r
-                            ipstr = tmp[1].split(":");\r
-                            if (ipstr.length == 2) {\r
-                                String ip = ipstr[0];\r
-                                int port = Integer.valueOf(ipstr[1].replace("#", ""));\r
-                                Config.setCustomServer(mContext,true,ip,port);\r
-                                reply = sms + " success! ";\r
-                                Config.loadServerSettings(runtime);\r
-                                CoreService.getInstance().disconnect_server();\r
-                                CoreService.getInstance().ReConnectToServer();\r
-                            } else {\r
-                                reply = sms + " falied! ";\r
-                            }\r
-                        }\r
-                    }\r
-                } else {\r
-                    reply = sms + " falied! ";\r
-                }\r
-                sendSMS(phonenumber, reply);\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#setlocation#=") && sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if (tmp[1].equals("reset#")) {\r
-                        Config.loadModCycleSettings(runtime);//恢复初始设置\r
-                        sendSMS(phonenumber, "reset to Location Mode=" + runtime.getLocationInstance().getWorkingMod() + ", Cycle=" + runtime.getLocationInstance().getLocation_cycle());\r
-                    } else {\r
-                        String[] t = tmp[1].replace("#", "").split(",");\r
-                        if (t.length == 2) {\r
-                            int mod = 0;\r
-                            int cycle = 0;\r
-                            try {\r
-                                mod = Integer.valueOf(t[0]);\r
-                                cycle = Integer.valueOf(t[1]);\r
-                            } catch (Exception e) {\r
-                                e.printStackTrace();\r
-                                ICLogger.e(e.getMessage(),e);\r
-                            }\r
-                            if ( mod > 0 && cycle >= 30) {\r
-                                switch (mod) {\r
-                                    case ICLocation.NORMAL_MOD:\r
-                                        cycle = 60 * 15;\r
-                                        break;\r
-                                    case ICLocation.LOWPOWER_MOD:\r
-                                        cycle = 60 * 60;\r
-                                        break;\r
-                                    case ICLocation.REALTIME_MOD:\r
-                                    case ICLocation.EMERGNECY_MOD:\r
-                                        cycle = 60;\r
-                                        break;\r
-                                    case ICLocation.CUSTOM_MOD:\r
-                                    case ICLocation.CUSTOM_MOD8_GPS:\r
-                                    case ICLocation.CUSTOM_MOD8_WIFI:\r
-                                        break;\r
-                                    default:\r
-                                        sendSMS(phonenumber, "set to Location Failed ,value range should be Mod in (1,2,3,4,5,8,9) and cycle >=30!");\r
-                                        return true;\r
-                                }\r
-                                LocationClient.setForceLocation(1); //短信设置的至少强制执行第一次定位。否则NORMAL_MOD和LOWPOWER_MOD如果没有运动就无法正常定位\r
-                                runtime.getLocationInstance().setLocation_cycle(cycle);\r
-                                runtime.getLocationInstance().setWorkingMod(mod);\r
-                                CoreService.getInstance().setLocationAlarm(runtime.getLocationInstance().getWorkingMod());\r
-                                if (mod == 4) {\r
-                                    CoreService.getInstance().setEmegencyLocationSTOPAlarm(5);\r
-                                }\r
-                                sendSMS(phonenumber, "set to Location Mode=" + runtime.getLocationInstance().getWorkingMod() + ", Cycle=" + runtime.getLocationInstance().getLocation_cycle());\r
-                            } else {\r
-                                sendSMS(phonenumber, "set to Location Failed ,value range should be Mod in (1,2,3,4,5,8,9) and cycle >=30!");\r
-                            }\r
-\r
-                        } else {\r
-                            sendSMS(phonenumber, "setlocation format error!");\r
-                        }\r
-                    }\r
-\r
-                } else {\r
-                    sendSMS(phonenumber, "setlocation format error!");\r
-                }\r
-\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#skipmovecheck#=")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if (tmp[1].equals("current")) {\r
-                        sendSMS(phonenumber, "SkipMoveCheck " + LocationClient.getSkipMoveCheck() + "!");\r
-                    } else if (tmp[1].equals("true")) {\r
-                        LocationClient.setSkipMoveCheck(true);\r
-                        sendSMS(phonenumber, "set SkipMoveCheck " + LocationClient.getSkipMoveCheck() + " success!");\r
-                    } else if (tmp[1].equals("false")) {\r
-                        LocationClient.setSkipMoveCheck(false);\r
-                        sendSMS(phonenumber, "set SkipMoveCheck " + LocationClient.getSkipMoveCheck() + " success!");\r
-                    } else {\r
-                        sendSMS(phonenumber, "skipmovecheck format error!");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "skipmovecheck format error!");\r
-                }\r
-            }else if(sms.startsWith(ENCRYPED_HEADER+"#wifictl#=")){\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if (tmp[1].equals("current")) {\r
-                        sendSMS(phonenumber, "Current Wifi Setting SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ "!");\r
-                    } else if (tmp[1].equals("reset")) {\r
-                        Config.setWiFiSSID(mContext,Config.DefaultWiFiSSID);\r
-                        Config.setWiFiPasswd(mContext,Config.DefaultWiFiPWD);\r
-                        sendSMS(phonenumber, "reset Wifi Setting to SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ "!");\r
-                    } else if (tmp[1].startsWith("connect,")) {\r
-\r
-                        String tmplist[]=tmp[1].split(",");\r
-                        if (tmplist.length==4){\r
-                            String SSID=tmplist[1];\r
-                            String PWD=tmplist[2];\r
-                            String encyptType=tmplist[3];\r
-                            Config.setWiFiSSID(mContext,SSID);\r
-                            Config.setWiFiPasswd(mContext,PWD);\r
-                            sendSMS(phonenumber, "set and connect to Wifi SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ ", encryptType "+encyptType+"!");\r
-                            //connect to wifi\r
-                            new Handler().postDelayed(new Runnable() {\r
-                                @Override\r
-                                public void run() {\r
-                                    Deliver.connectToWifi(SSID,PWD,encyptType);\r
-                                }\r
-                            }, 500);\r
-                        }else {\r
-                            sendSMS(phonenumber, "WiFi Control format error!");\r
-                        }\r
-                    } else if (tmp[1].startsWith("noTurnOffWhenScreenOff,")) {\r
-\r
-                        String tmplist[]=tmp[1].split(",");\r
-                        if (tmplist.length==2){\r
-                            String enabled=tmplist[1];\r
-                            boolean isenabled=enabled.toLowerCase().equals("true")?true:false;\r
-                          runtime.setNoTurnOffOnScreenOff(isenabled);\r
-                          StringBuilder sb=new StringBuilder();\r
-                          if (isenabled && !Util.isWifiIsOpen(runtime.getContextProxy().context,runtime)){\r
-                              Util.turnOnWifiForConnect(runtime.getContextProxy().context,runtime);\r
-                              sb.append(" Turn On Wifi first and ");\r
-                          }\r
-                          sb.append("set noTurnOffWhenScreenOff " + enabled);\r
-                          sendSMS(phonenumber,sb.toString() );\r
-\r
-                        }else {\r
-                            sendSMS(phonenumber, "WiFi Control format error!");\r
-                        }\r
-                    } else {\r
-                        sendSMS(phonenumber, "WiFi Control format error!");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "WiFi Control format error!");\r
-                }\r
-            }else if(sms.startsWith(ENCRYPED_HEADER+"#logctl#=")){\r
-\r
-                final boolean needshowToast=sms.contains("SDLogInfo:");\r
-                Handler mhandler=new Handler(){\r
-                    @Override\r
-                    public void handleMessage(Message msg) {\r
-\r
-                        switch(msg.what){\r
-                            case 0:\r
-                                sendSMS(phonenumber, "Upload  Failed!");\r
-                                if (needshowToast) {\r
-                                    Util.ShowToast(runtime, "Upload cmd  Failed!");\r
-                                }\r
-                                break;\r
-\r
-                            case 1:\r
-                                sendSMS(phonenumber, "Upload  success!");\r
-                                if (needshowToast) {\r
-                                    Util.ShowToast(runtime, "Upload cmd  success!");\r
-                                }\r
-                                break;\r
-                        }\r
-\r
-                        super.handleMessage(msg);\r
-                    }\r
-                };\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if (tmp[1].equals("current")) {\r
-                        sendSMS(phonenumber, "Current FtpLogServer " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));\r
-                    }else  if (tmp[1].equals("reset")) {\r
-\r
-                        Config.setFtpServer(mContext, Config.DefaultLogFtpServer);\r
-                        Config.setFtpUser(mContext, Config.DefaultLogFtpUser);\r
-                        Config.setFtpPWD(mContext, Config.DefaultLogFtpPWD);\r
-                        sendSMS(phonenumber, "reset FtpLogServer to " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));\r
-                    }else if (tmp[1].startsWith("upload,")){\r
-\r
-                        String cmdl[] = tmp[1].split(",");\r
-                        if (cmdl.length == 2) {\r
-                            String logfile=cmdl[1];\r
-\r
-                            if (!logfile.isEmpty()&& ( logfile.startsWith("SDLog:")||logfile.startsWith("SDLogInfo:"))){\r
-\r
-                                String sdfilelist[] = logfile.split(":");\r
-                                if (sdfilelist.length==2) {\r
-                                    String fileOrDir=sdfilelist[1];\r
-                                    new Handler().postDelayed(new Runnable() {\r
-                                        @Override\r
-                                        public void run() {\r
-                                            String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileOrDir;\r
-                                            URL serverurl = null;\r
-                                            try {\r
-                                                serverurl = new URL(Util.getServerLogfilePath(Config.getFtpServer(mContext), TimeUtil.getSystemTime3(), logfile, runtime));\r
-                                            } catch (MalformedURLException e) {\r
-                                                e.printStackTrace();\r
-                                                ICLogger.e(e.getMessage(),e);\r
-                                            }\r
-                                            if ( new File(filepath).exists()) {\r
-                                                Util.getDBFile();\r
-                                                sendSMS(phonenumber,"start Upload " + filepath + " to " + Config.getFtpServer(mContext) + " ...");\r
-\r
-                                                if (logfile.startsWith("SDLogInfo:")){\r
-                                                    Util.ShowToast(runtime,"start Upload " + filepath + " to " + Config.getFtpServer(mContext) + " ...");\r
-                                                }\r
-                                                String logtime = TimeUtil.getSystemTime3();\r
-\r
-                                                if (upload_logs_via_ftp) {\r
-                                                    if (ftpUtils.upload(serverurl, Config.getFtpUser(mContext), Config.getFtpPWD(mContext), new File(filepath))) {\r
-                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");\r
-\r
-                                                        if (logfile.startsWith("SDLogInfo:")){\r
-                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");\r
-                                                        }\r
-                                                    } else {\r
-                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");\r
-                                                        if (logfile.startsWith("SDLogInfo:")){\r
-                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");\r
-                                                        }\r
-                                                    }\r
-                                                } else {\r
-                                                    if (ICHttpUtil.uploadFile(filepath, runtime, logtime,mhandler)) {\r
-//                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");\r
-//                                                        if (logfile.startsWith("SDLogInfo:")){\r
-//                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");\r
-//                                                        }\r
-                                                    } else {\r
-//                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");\r
-//                                                        if (logfile.startsWith("SDLogInfo:")){\r
-//                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");\r
-//                                                        }\r
-                                                    }\r
-                                                }\r
-                                            } else {\r
-                                                sendSMS(phonenumber, filepath + " not exist !");\r
-                                                if (logfile.startsWith("SDLogInfo:")){\r
-                                                    Util.ShowToast(runtime,filepath + " not exist !");\r
-                                                }\r
-                                            }\r
-                                        }\r
-                                    }, 500);\r
-\r
-                                }else{\r
-                                    sendSMS(phonenumber,  " SDLog format error !");\r
-                                }\r
-\r
-                            }else{\r
-                                new Handler().postDelayed(new Runnable() {\r
-                                    @Override\r
-                                    public void run() {\r
-                                        String filepath = Util.getLogfilePath(runtime, logfile);\r
-                                        URL serverurl = null;\r
-                                        try {\r
-                                            serverurl = new URL(Util.getServerLogfilePath(Config.getFtpServer(mContext), TimeUtil.getSystemTime3(), logfile,runtime));\r
-                                        } catch (MalformedURLException e) {\r
-                                            e.printStackTrace();\r
-                                            ICLogger.e(e.getMessage(),e);\r
-                                        }\r
-                                        if (Util.LogfileExist(runtime, logfile)) {\r
-                                            Util.getDBFile();\r
-                                            sendSMS(phonenumber, "start Upload " + logfile + " to " + Config.getFtpServer(mContext) +" ...");\r
-                                            String logtime=TimeUtil.getSystemTime3();\r
-\r
-                                            if (upload_logs_via_ftp) {\r
-                                                if (ftpUtils.upload(serverurl, Config.getFtpUser(mContext), Config.getFtpPWD(mContext), new File(filepath))) {\r
-                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " success!");\r
-                                                } else {\r
-                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " failed!");\r
-                                                }\r
-                                            }else{\r
-                                                if (ICHttpUtil.uploadFile(filepath,runtime,logtime,mhandler)) {\r
-//                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " success!");\r
-                                                } else {\r
-//                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " failed!");\r
-                                                }\r
-                                            }\r
-                                        } else {\r
-                                            sendSMS(phonenumber, logfile + " not exist !");\r
-                                        }\r
-                                    }\r
-                                }, 500);\r
-\r
-                            }\r
-\r
-//                            sendSMS(phonenumber, "upload FtpLogServer to " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));\r
-\r
-                        }else{\r
-                            sendSMS(phonenumber, "upload logfile format error!");\r
-                        }\r
-\r
-                    } else {\r
-                        String cmdl[] = tmp[1].split(",");\r
-                        if (cmdl.length == 3) {\r
-                            Config.setFtpServer(mContext,cmdl[0]);\r
-                            Config.setFtpUser(mContext,cmdl[1]);\r
-                            Config.setFtpPWD(mContext,cmdl[2]);\r
-                            sendSMS(phonenumber, "Set FtpLogServer to "+ Config.getFtpServer(mContext)+ ", user "+Config.getFtpUser(mContext)+", pwd "+Config.getFtpPWD(mContext));\r
-\r
-                        } else {\r
-                            sendSMS(phonenumber, "set LogFtpServer format error! "+sms);\r
-                        }\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "set LogFtp ctl format error! "+sms);\r
-                }\r
-\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#TP#=")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if (tmp[1].equals("getver")) {\r
-                        if (Util.is_FT6236U_upgrade_firmware_support()){\r
-                            Util.FT6236U_getVer();\r
-                            String ver=Util.FT6236U_getVer();\r
-                            sendSMS(phonenumber, " Current FT6236U Firmware Version is "+ver+"!");\r
-                        }else {\r
-                            sendSMS(phonenumber, " system Not Support FT6236U upgrade Firmware!");\r
-                        }\r
-                    } else if (tmp[1].equals("upgrade")) {\r
-                        if (Util.is_FT6236U_upgrade_firmware_support()){\r
-                            Util.FT6236U_getVer();\r
-                            String ver=Util.FT6236U_getVer();\r
-                            if (ver.startsWith("A1")) {\r
-                                if (Util.FT6236U_upgrade_firmware()) {\r
-                                    Util.FT6236U_getVer();\r
-                                    ver = Util.FT6236U_getVer();\r
-                                    sendSMS(phonenumber, " Current FT6236U Firmware Version is " + ver + "!");\r
-                                } else {\r
-                                    sendSMS(phonenumber, " FT6236U Firmware upgrade failed !");\r
-                                }\r
-                            }else{\r
-                                sendSMS(phonenumber, " FT6236U current Firmware version is "+ver+"  , upgrade only support A1 to A3  !");\r
-                            }\r
-                        }else {\r
-                            sendSMS(phonenumber, " system Not Support FT6236U upgrade Firmware!");\r
-                        }\r
-                    } else {\r
-                        sendSMS(phonenumber, "TP cmd format error!");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "TP cmd format error!");\r
-                }\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#USB#=")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if(tmp[1].equals("current"))\r
-                    {\r
-                       String conf= Util.getSystemProperties("sys.usb.config");\r
-                        sendSMS(phonenumber, "Current USB config is "+conf+"!");\r
-                    }else if(tmp[1].equals("mtp")||tmp[1].equals("adb")||tmp[1].equals("mtp,adb")||tmp[1].equals("adb,mtp")||tmp[1].equals("none")) {\r
-                        sendSMS(phonenumber, "Set USB config to "+tmp[1]+"!");\r
-                        Util.setSystemProperties("sys.usb.config", "none");\r
-\r
-                        Util.setSystemProperties("sys.usb.config", tmp[1]);\r
-                    }else{\r
-                        sendSMS(phonenumber, "USB cmd format error only support current|adb|mtp|adb,mtp|mtp,adb|none !");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "USB cmd format error!");\r
-                }\r
-\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#ShowInfo#")) {\r
-                Intent intent=new Intent();\r
-                ComponentName var3 = new ComponentName("com.enqualcomm.support", "com.enqualcomm.support.DeviceInfoActivity");\r
-                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);\r
-                intent.setComponent(var3);\r
-                runtime.getContextProxy().context.startActivity(intent);\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#FactoryResetCheckSim#")) {\r
-                sendSMS(phonenumber, "do FactoryResetCheckSim ok!");\r
-                CoreService.DevliverStringMessage("FactoryResetCheckSim");\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#poweroffCheckSim#")) {\r
-                sendSMS(phonenumber, "do poweroffCheckSim ok!");\r
-                CoreService.DevliverStringMessage("poweroffCheckSim");\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#factoryreset#")|| sms.startsWith(ENCRYPED_HEADER+"#reset#")) {\r
-                sendSMS(phonenumber, "do factoryreset ok!");\r
-                CoreService.DevliverStringMessage("FactoryReset");\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#reboot#")) {\r
-                sendSMS(phonenumber, "do reboot ok!");\r
-                CoreService.DevliverStringMessage("Reboot");\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#poweroff#")) {\r
-                sendSMS(phonenumber, "do poweroff ok!");\r
-                CoreService.DevliverStringMessage("poweroff");\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#packagevers#")) {\r
-                sendSMS(phonenumber, DeviceInfoUtil.getPackageVersions(mContext));\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#getWeather#")) {\r
-                sendSMS(phonenumber, "do get Weather!");\r
-                CoreService.DevliverStringMessage("getWeather");\r
-           } else if (sms.startsWith(ENCRYPED_HEADER+"#showui#")) {\r
-                Util.setSystemProperties("persist.sys.debugprotocol","true");\r
-                Intent intent=new Intent();\r
-//                intent.setClassName(MainActivity.class.getPackage().getName(),MainActivity.class.getName());\r
-                intent.setClass(mContext,MainActivity.class);\r
-                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
-                mContext.startActivity(intent);\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#PW=")&& sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    if(tmp[1].equals(Config.DefaultSMSPassword+"#"))\r
-                    {\r
-                        Config.setSMSPwd(mContext,Config.DefaultSMSPassword);\r
-                        sendSMS(phonenumber, "Cancel SMS PW ok!");\r
-                    }else{\r
-                        Config.setSMSPwd(mContext,tmp[1].replace("#",""));\r
-                        sendSMS(phonenumber, "SET SMS PW ok "+Config.getSMSPwd(mContext));\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "set SMSCMD PWD format error!");\r
-                }\r
-            } else if (sms.startsWith(ENCRYPED_HEADER+"#sos=")&& sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String str_sosNums=tmp[1].replace("#","");\r
-                    String[] soslist=str_sosNums.split(";");\r
-                    if (soslist.length>=1 && soslist.length<=3  ) {\r
-                        String phNum1 = soslist[0];\r
-                        String phNum2 ="";\r
-                        String phNum3 = "";\r
-                        if (soslist.length>1) phNum2=soslist[1];\r
-                        if (soslist.length>2) phNum3=soslist[2];\r
-\r
-                        ArrayList<Contact> contactArray=new ArrayList<Contact>();\r
-                        if (!phNum1.isEmpty())  contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos1",phNum1));\r
-                        if (!phNum2.isEmpty())  contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos2",phNum2));\r
-                        if (!phNum3.isEmpty())  contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos3",phNum3));\r
-\r
-                        runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);\r
-\r
-                        sendSMS(phonenumber, "set SOS number ok!");\r
-\r
-                    }else{\r
-                        sendSMS(phonenumber, "set SOS number format Error!");\r
-                    }\r
-\r
-                } else {\r
-                    sendSMS(phonenumber, "set SMSCMD PWD format error!");\r
-                }\r
-            } else if (sms.equals(ENCRYPED_HEADER+"#listen#")) {\r
-                sendSMS(phonenumber, "start listen !");\r
-//                CellInfoUtil.dialSilent(runtime.getContextProxy().context,phonenumber);\r
-                ICAudioManager.needMute=true;\r
-                new Handler().postDelayed(new Runnable() {\r
-                    @Override\r
-                    public void run() {\r
-                        SimSignalUtil.send_at_cmd(runtime,"atd"+phonenumber+";");\r
-                    }\r
-                }, 2000);\r
-\r
-            } else if (sms.equals(ENCRYPED_HEADER+"#location#")) {\r
-\r
-                sendSMS(phonenumber, "start location mode "+runtime.getLocationInstance().getWorkingMod()+"!");\r
-                cell_number_to_reply=phonenumber;\r
-                LocationClient locationClient=LocationClient.getInstance();\r
-                if (locationClient!=null){\r
-                    locationClient.setLocationResponse(replayLocation);\r
-                    ICLogger.i("triggerLocationProcess ");\r
-                    locationClient.triggerLocationProcess();\r
-                }\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#setLogSrv#=")&& sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String strtmp=tmp[1].replace("#","");\r
-\r
-                    if (strtmp.contains("/")){\r
-                        /* #setLogSrv#=http://icfota.snicker.com.cn:8089/UploadFile.jsp*/\r
-                        Config.setLogServerIP(mContext,strtmp,8089);\r
-                        sendSMS(phonenumber, "set setLogSrv to "+strtmp+"!");\r
-                    }else {\r
-                        /* #setLogSrv#=icfota.snicker.com.cn:8089 */\r
-                         String[] ipstr = strtmp.split(":");\r
-                        if (ipstr.length == 2) {\r
-                            String ip = ipstr[0];\r
-                            int port = Integer.valueOf(ipstr[1].replace("#", ""));\r
-                            Config.setLogServerIP(mContext,ip,port);\r
-                            sendSMS(phonenumber, "set setLogSrv to "+strtmp+"!");\r
-                        } else {\r
-                            sendSMS(phonenumber, " setLogSrv cmd Format error!");\r
-                        }\r
-                    }\r
-\r
-                } else {\r
-                    sendSMS(phonenumber, " setLogSrv cmd Format error!");\r
-                }\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#setFotaSrv#=")&& sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String strtmp=tmp[1].replace("#","");\r
-                    Config.setFotaServerUrl(mContext,strtmp);\r
-                    Util.setSystemProperties(Constants.PersistFotaServer2Url,strtmp);\r
-                    sendSMS(phonenumber, "set setFotaSrv2 to "+strtmp+"!");\r
-                } else {\r
-                    sendSMS(phonenumber, " setFotaSrv cmd Format error!");\r
-                }\r
-            } else if (sms.equals(ENCRYPED_HEADER+"#FotaUpdate#")) {\r
-\r
-                cell_number_to_reply=phonenumber;\r
-                broadCastStartFotaUpdate(mContext);\r
-                sendSMS(phonenumber, "start fota update !");\r
-            } else if (sms.equals(ENCRYPED_HEADER+"#FotaUpdateWiFi#=")){\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String tmplist[]=tmp[1].split(",");\r
-                    if (tmplist.length==3){\r
-\r
-                        String SSID=tmplist[0];\r
-                        String PWD=tmplist[1];\r
-                        String encyptType=tmplist[2];\r
-                        Config.setWiFiSSID(mContext,SSID);\r
-                        Config.setWiFiPasswd(mContext,PWD);\r
-                        runtime.setNoTurnOffOnScreenOff(true);\r
-                        StringBuilder sb=new StringBuilder();\r
-                        if ( !Util.isWifiIsOpen(runtime.getContextProxy().context,runtime)){\r
-                            Util.turnOnWifiForConnect(runtime.getContextProxy().context,runtime);\r
-                        }\r
-                        sb.append("connect to Wifi SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ ", encryptType "+encyptType+"!");\r
-                        sb.append(" And start to Update");\r
-                        cell_number_to_reply=phonenumber;\r
-                        sendSMS(phonenumber, sb.toString());\r
-                        //connect to wifi\r
-                        new Handler().postDelayed(new Runnable() {\r
-                            @Override\r
-                            public void run() {\r
-                                Deliver.connectToWifi(SSID,PWD,encyptType);\r
-                                broadCastStartFotaUpdate(mContext);\r
-                            }\r
-                        }, 500);\r
-                    }else {\r
-                        sendSMS(phonenumber, "FotaUpdateWiFi Control format error!");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, "FotaUpdateWiFi Control format error!");\r
-                }\r
-\r
-\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#nolocationcycle#=")&& sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String strtmp=tmp[1].replace("#","");\r
-                    if (strtmp.equalsIgnoreCase("false")){\r
-                        Util.setSystemProperties("persist.sys.NoLocationCycle","false");\r
-                        Config.getNoLocationCycleFlag();\r
-                        sendSMS(phonenumber, "set noLocationCycle false! and trigger one Location");\r
-                        LocationClient locationClient=LocationClient.getInstance();\r
-                        if (locationClient!=null){\r
-                            ICLogger.i("triggerLocationProcess ");\r
-                            locationClient.triggerLocationProcess();\r
-                        }\r
-                    }else if (strtmp.equalsIgnoreCase("true")){\r
-                        Util.setSystemProperties("persist.sys.NoLocationCycle","true");\r
-                        Config.getNoLocationCycleFlag();\r
-                        sendSMS(phonenumber, "set noLocationCycle true!");\r
-                    }else if (strtmp.equalsIgnoreCase("current")){\r
-                        sendSMS(phonenumber, "current noLocationCycle "+Config.getNoLocationCycleFlag()+"!");\r
-                    }else {\r
-                        sendSMS(phonenumber, " nolocationcycle cmd Format error!");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, " nolocationcycle cmd Format error!");\r
-                }\r
-            }else if (sms.startsWith(ENCRYPED_HEADER+"#setprotocol#=")&& sms.endsWith("#")) {\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String strtmp=tmp[1].replace("#","");\r
-                    if (strtmp.equalsIgnoreCase("beehome")){\r
-                        if(Config.protocol_no!=Config.PROTOCOL_BEEHOME) {\r
-                            Util.setSystemProperties("persist.sys.protocol_no", "1");\r
-                            Config.getProtocolNumber();\r
-                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());\r
-                            Config.loadServerSettings(runtime);\r
-                            sendSMS(phonenumber, "set setprotocol to Beehome Protocol! device will reboot later !");\r
-                            CoreService.DevliverStringMessage("Reboot");\r
-//                            CoreService.getInstance().disconnect_server();\r
-//                            CoreService.getInstance().ReConnectToServer();\r
-                        }else{\r
-                            sendSMS(phonenumber, "current is Beehome Protocol!");\r
-                        }\r
-\r
-                    }else if(strtmp.equalsIgnoreCase("jiai")){\r
-                        if(Config.protocol_no!=Config.PROTOCOL_JIAI) {\r
-                            Util.setSystemProperties("persist.sys.protocol_no", "0");\r
-                            Config.getProtocolNumber();\r
-                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());\r
-                            Config.loadServerSettings(runtime);\r
-                            sendSMS(phonenumber, "set setprotocol to JiAi Protocol! device will reboot later !");\r
-                            CoreService.DevliverStringMessage("Reboot");\r
-//                            CoreService.getInstance().disconnect_server();\r
-//                            CoreService.getInstance().ReConnectToServer();\r
-                        }else\r
-                        {\r
-                            sendSMS(phonenumber, "current is JiAi Protocol!");\r
-                        }\r
-                    }else if(strtmp.equalsIgnoreCase("ic")){\r
-                        if(Config.protocol_no!=Config.PROTOCOL_IC) {\r
-                            Util.setSystemProperties("persist.sys.protocol_no", "2");\r
-                            Config.getProtocolNumber();\r
-                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());\r
-                            Config.loadServerSettings(runtime);\r
-                            sendSMS(phonenumber, "set setprotocol to IC Protocol! device will reboot later !");\r
-                            CoreService.DevliverStringMessage("Reboot");\r
-//                            CoreService.getInstance().disconnect_server();\r
-//                            CoreService.getInstance().ReConnectToServer();\r
-                        }else\r
-                        {\r
-                            sendSMS(phonenumber, "current is IC Protocol!");\r
-                        }\r
-                    }else if(strtmp.equalsIgnoreCase("fzd")){\r
-                        if(Config.protocol_no!=Config.PROTOCOL_FZD) {\r
-                            Util.setSystemProperties("persist.sys.protocol_no", "3");\r
-                            Config.getProtocolNumber();\r
-                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());\r
-                            Config.loadServerSettings(runtime);\r
-                            sendSMS(phonenumber, "set setprotocol to fzd Protocol! device will reboot later !");\r
-                            CoreService.DevliverStringMessage("Reboot");\r
-//                            CoreService.getInstance().disconnect_server();\r
-//                            CoreService.getInstance().ReConnectToServer();\r
-                        }else\r
-                        {\r
-                            sendSMS(phonenumber, "current is fzd Protocol!");\r
-                        }\r
-                    }else if(strtmp.equalsIgnoreCase("mqtt")){\r
-                        if(Config.protocol_no!=Config.PROTOCOL_MQTT) {\r
-                            Util.setSystemProperties("persist.sys.protocol_no", "4");\r
-                            Config.getProtocolNumber();\r
-                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());\r
-                            Config.loadServerSettings(runtime);\r
-                            sendSMS(phonenumber, "set setprotocol to mqtt Protocol! device will reboot later !");\r
-                            CoreService.DevliverStringMessage("Reboot");\r
-//                            CoreService.getInstance().disconnect_server();\r
-//                            CoreService.getInstance().ReConnectToServer();\r
-                        }else\r
-                        {\r
-                            sendSMS(phonenumber, "current is mqtt Protocol!");\r
-                        }\r
-                    }else if(TextUtils.isDigitsOnly(strtmp)) {\r
-                        int protocolno=Integer.parseInt(strtmp);\r
-                        switch (protocolno) {\r
-                            case 0:\r
-                            case 1:\r
-                            case 2:\r
-                            case 3:\r
-                            case 4:\r
-                                Util.setSystemProperties("persist.sys.protocol_no", strtmp);\r
-                                Config.getProtocolNumber();\r
-                                Config.loadServerSettings(runtime);\r
-                                sendSMS(phonenumber, "set setprotocol to Protocol"+protocolno+"! \r\nYou may also need to set server ip for this protocol !\r\n May need reboot device too.");\r
-                                CoreService.getInstance().disconnect_server();\r
-                                CoreService.getInstance().ReConnectToServer();\r
-                            break;\r
-                            default:\r
-                                sendSMS(phonenumber, "setprotocol only support  Protocol 0/1/2/3/4 by now! ");\r
-                                break;\r
-                        }\r
-\r
-                    }else{\r
-                        sendSMS(phonenumber, " only support protocol jiAi , ic , beehome , fzd , mqtt !");\r
-                    }\r
-                } else {\r
-                    sendSMS(phonenumber, " setprotocol cmd Format error!");\r
-                }\r
-\r
-            }else if(sms.startsWith(ENCRYPED_HEADER+"#maillog#=")){\r
-                String tmp[] = sms.split("=");\r
-                if (tmp.length == 2) {\r
-                    String mailaddr=tmp[1];\r
-                    if (!mailaddr.contains("@"))\r
-                    {\r
-                        sendSMS(phonenumber, "mail address error !");\r
-\r
-                    }else {\r
-                        new Handler().postDelayed(new Runnable() {\r
-                            @Override\r
-                            public void run() {\r
-                                String logfile = "";\r
-                                String fileOrDir = "Android/ic";\r
-\r
-                                Util.getDBFile();\r
-\r
-                                logfile = Util.zipfiles(fileOrDir);\r
-                                if (new File(logfile).exists()) {\r
-\r
-                                    sendSMS(phonenumber, "mail " + fileOrDir + " to " + mailaddr + " ...");\r
-                                    Util.ShowToast(runtime,"mail " + fileOrDir + " to " + mailaddr + " ...");\r
-\r
-                                    String logtime = TimeUtil.getSystemTime3();\r
-                                    if (SendEmail.getInstance().sendLogViaMail(logfile,mailaddr, logtime)) {\r
-                                        sendSMS(phonenumber, "mail " + fileOrDir + " to " + mailaddr + " success!");\r
-//                                        Util.ShowToast(runtime,"mail " + fileOrDir + " to " + mailaddr + " success!");\r
-                                    } else {\r
-                                        sendSMS(phonenumber, "mail " + fileOrDir + " to " + mailaddr + " failed!");\r
-//                                        Util.ShowToast(runtime,"mail " + fileOrDir + " to " + mailaddr + " failed!");\r
-                                    }\r
-\r
-                                } else {\r
-                                    sendSMS(phonenumber, fileOrDir + " not exist !");\r
-//                                    if (logfile.startsWith("SDLogInfo:")) {\r
-//                                        Util.ShowToast(runtime, fileOrDir + " not exist !");\r
-//                                    }\r
-                                }\r
-                            }\r
-\r
-\r
-\r
-                        }, 500);\r
-\r
-                    }\r
-\r
-//                            sendSMS(phonenumber, "upload FtpLogServer to " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));\r
-\r
-            }else{\r
-                sendSMS(phonenumber, "upload logfile format error!");\r
-            }\r
-\r
-\r
-            }else if(sms.startsWith(ENCRYPED_HEADER+"#capture#")) {\r
-\r
-                    new Handler().post(new Runnable() {\r
-                        @Override\r
-                        public void run() {\r
-                            (new CameraUtil(mContext)).getPictur("capture"+TimeUtil.getSystemTime3());\r
-                        }\r
-                    });\r
-\r
-            }else if(sms.startsWith(ENCRYPED_HEADER+"#monitor#")) {\r
-\r
-                new Handler().post(new Runnable() {\r
-                    @Override\r
-                    public void run() {\r
-                        CoreService.getInstance().DevliverStringMessage("StartMonitor","10");\r
-                    }\r
-                });\r
-\r
-\r
-                /***\r
-                 *   }else if(sms.startsWith(ENCRYPED_HEADER+"#logctl#=")){\r
-                 *   。。。。。\r
-                 * 添加新命令道这里\r
-                 */\r
-            }else {\r
-                return false;\r
-            }\r
-            return true;\r
-        }else{\r
-            return false;\r
-        }\r
-    }\r
-    public final Uri SMS_MESSAGE_URI = Uri.parse("content://sms");\r
-    private SmsDatabaseChaneObserver mSmsDBChangeObserver;\r
-    private void registerSmsDatabaseChangeObserver(Context contextWrapper) {\r
-        //因为,某些机型修改rom导致没有getContentResolver\r
-        try {\r
-            mSmsDBChangeObserver = new SmsDatabaseChaneObserver(contextWrapper.getContentResolver(), mHandler);\r
-            contextWrapper.getContentResolver().registerContentObserver(SMS_MESSAGE_URI, true, mSmsDBChangeObserver);\r
-        } catch (Throwable e) {\r
-            ICLogger.e(e.getMessage(),e);\r
-        }\r
-    }\r
-\r
-    private void unregisterSmsDatabaseChangeObserver(Context contextWrapper) {\r
-        try {\r
-            contextWrapper.getContentResolver().unregisterContentObserver(mSmsDBChangeObserver);\r
-        } catch (Exception e) {\r
-            e.printStackTrace();\r
-        }\r
-    }\r
-\r
-\r
-    private void handle_test_cmd(String cmd,String arg){\r
-\r
-        ICLogger.i("receive test Cmd "+cmd+" arg "+arg);\r
-        if(cmd.startsWith("testDialog,")) {\r
-            String list[]=cmd.split(",");\r
-            int msgtype=0;\r
-            try {\r
-                msgtype = Integer.parseInt(list[1]);\r
-            }catch ( Exception e){}\r
-            if(CoreService.getInstance()!=null)\r
-            CoreService.getInstance().getRuntime().getContextProxy().sendMsgBroadcast(arg, msgtype);\r
-        }else if(cmd.startsWith("playnotifiy")) {\r
-\r
-            AudioService.getInstance().play(runtime.getContextProxy().context.getAssets(), "ring_msg.mp3");\r
-            VibrateUtil.getInstance(runtime.getContextProxy().context).VibrateOn(true);\r
-\r
-        }else if(cmd.startsWith("DeliverSMS")) {\r
-\r
-           if(CoreService.getInstance()!=null){\r
-               Deliver.sendLocationMSG(protocolAPIHelper.getLBSLocationMSG(runtime));\r
-           }\r
-\r
-        }else if(cmd.startsWith("resetsim")) {\r
-\r
-            if(CoreService.getInstance()!=null){\r
-                SimSignalUtil.send_at_to_reset_simcard(CoreService.getInstance().runtime);\r
-            }\r
-\r
-        }else if(cmd.startsWith("airplane")) {\r
-\r
-            if(CoreService.getInstance()!=null){\r
-                SimSignalUtil.setAirMode(CoreService.getInstance(), "OpenAirplane");\r
-                new Handler().postDelayed(new Runnable() {\r
-                    @Override\r
-                    public void run() {\r
-                        SimSignalUtil.setAirMode(CoreService.getInstance(),"CloseAirplane");\r
-                    }\r
-                },5000);\r
-            }\r
-        }else if(cmd.startsWith("testCMDRecords")) {\r
-\r
-            if(CoreService.getInstance()!=null){\r
-                StringMessage msg=protocolAPIHelper.getLBSLocationMSG(runtime);\r
-                runtime.getDbHelper().insertCMDRecord(msg);\r
-                Deliver.dumpMessage(msg);\r
-                Util.mSleep(2000);\r
-                msg=protocolAPIHelper.getLBSLocationMSG(runtime);\r
-                runtime.getDbHelper().insertCMDRecord(msg);\r
-                Deliver.dumpMessage(msg);\r
-                Util.mSleep(2000);\r
-                msg=protocolAPIHelper.getLBSLocationMSG(runtime);\r
-                runtime.getDbHelper().insertCMDRecord(msg);\r
-                Deliver.dumpMessage(msg);\r
-\r
-                Deliver.triggerSendThread();\r
-                /*\r
-                msg=runtime.getDbHelper().queryNotSentCMDRecord();\r
-                Deliver.dumpMessage(msg);\r
-                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),1);\r
-                msg=runtime.getDbHelper().queryWaitCMDRecord();\r
-                Deliver.dumpMessage(msg);\r
-                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),2);\r
-                Deliver.dumpMessage(msg);\r
-\r
-                msg=runtime.getDbHelper().queryNotSentCMDRecord();\r
-                Deliver.dumpMessage(msg);\r
-                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),1);\r
-                msg=runtime.getDbHelper().queryWaitCMDRecord();\r
-                Deliver.dumpMessage(msg);\r
-                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),2);\r
-                Deliver.dumpMessage(msg);\r
-\r
-                msg=runtime.getDbHelper().queryNotSentCMDRecord();\r
-                Deliver.dumpMessage(msg);\r
-                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),1);\r
-                msg=runtime.getDbHelper().queryWaitCMDRecord();\r
-                Deliver.dumpMessage(msg);\r
-                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),2);\r
-                Deliver.dumpMessage(msg);\r
-*/\r
-\r
-            }\r
-\r
-        }\r
-    }\r
+package com.enqualcomm.support;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.Handler;
+import android.os.Message;
+import android.os.SystemClock;
+import android.telephony.SmsManager;
+import android.telephony.SmsMessage;
+import android.text.TextUtils;
+import android.widget.Toast;
+
+import com.enqualcomm.support.bean.Contact;
+import com.enqualcomm.support.bean.ICLocation;
+import com.enqualcomm.support.bean.Runtime;
+import com.enqualcomm.support.bean.StringMessage;
+import com.enqualcomm.support.service.AudioService;
+import com.enqualcomm.support.service.Deliver;
+import com.enqualcomm.support.service.SmsDatabaseChaneObserver;
+import com.enqualcomm.support.utils.APNUtil;
+import com.enqualcomm.support.utils.CameraUtil;
+import com.enqualcomm.support.utils.CellInfoUtil;
+import com.enqualcomm.support.utils.ContextProxy;
+import com.enqualcomm.support.utils.DeviceInfoUtil;
+import com.enqualcomm.support.utils.ICAudioManager;
+import com.enqualcomm.support.utils.ICHttpUtil;
+import com.enqualcomm.support.utils.ICLogger;
+import com.enqualcomm.support.utils.SendEmail;
+import com.enqualcomm.support.utils.ServiceUtil;
+import com.enqualcomm.support.utils.SimSignalUtil;
+import com.enqualcomm.support.utils.TimeUtil;
+import com.enqualcomm.support.utils.Util;
+import com.enqualcomm.support.utils.VibrateUtil;
+import com.enqualcomm.support.utils.ftpUtils;
+import com.ic.protocols.protocolAPIHelper;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.concurrent.TimeUnit;
+
+import chestnut.utils.PhoneUtils;
+
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+import static com.enqualcomm.support.Config.upload_logs_via_ftp;
+import static com.enqualcomm.support.Constants.ACTION_SMSCMD;
+import static com.enqualcomm.support.Constants.ACTION_SMSCMD_Reply;
+import static com.enqualcomm.support.Constants.ACTION_SMSCMD_TEST;
+import static com.enqualcomm.support.Constants.ACTION_SMS_RECEIVED;
+import static com.enqualcomm.support.Constants.ACTION_START_FOTA_UPDATE;
+import static com.enqualcomm.support.Constants.DIALOG_ACTION;
+import static com.enqualcomm.support.Constants.KeyReplyData;
+import static com.enqualcomm.support.Constants.contact;
+import static com.enqualcomm.support.utils.DeviceInfoUtil.getDeviceVersion;
+import static com.enqualcomm.support.utils.SimSignalUtil.send_at_cmd;
+import static com.enqualcomm.support.utils.SimSignalUtil.send_at_setImei0;
+import static com.enqualcomm.support.utils.SimSignalUtil.send_at_setImei1;
+
+
+public class ICSmsManager  extends BroadcastReceiver {
+
+    private static String cell_number_to_reply=""; //this number is use for ACTION_SMSCMD_Reply
+
+    private static long preTimeMillis;
+    private Context mContext = null;
+    Runtime runtime;
+
+    Handler mHandler=new Handler(new Handler.Callback() {
+        @Override
+        public boolean handleMessage(Message message) {
+
+            if (message.what==100){
+
+                Bundle param = message.getData();
+                if (param!=null){
+
+                    String from = param.getString("SMSFrom");
+                    String smsmessage = param.getString("SMSData");
+
+                    long currenttime = System.currentTimeMillis();
+//                    if (currenttime - ICSmsManager.preTimeMillis > 30000L) {
+                        ICSmsManager.preTimeMillis = currenttime;
+                        (new Thread(new Runnable() {
+                            public void run() {
+                                SystemClock.sleep(3000L);
+                                ICLogger.i("收到" + from + "短信:" + smsmessage);
+//                         Toast.makeText(context, "收到" + from + "短信:" + smsmessage, Toast.LENGTH_LONG).show();
+                                if (handleSMS_CMD(from, smsmessage) == false) {
+                                    //说明不是sms命令,提示短信接收。
+                                    ContextProxy.sendMsgBroadcast(mContext, smsmessage, 1);
+                                }
+                            }
+                        })).start();
+//                    }
+
+
+                }
+
+
+            }
+
+
+
+            return false;
+        }
+    });
+
+    ReplayLocation replayLocation=new ReplayLocation();
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+
+        if (CoreService.getInstance()==null) {
+            ICLogger.i("CoreService still not started , skip SMS cmd!");
+            return;
+        }
+        mContext=context;
+        runtime=CoreService.getInstance().runtime;
+
+
+        String action = intent.getAction();
+        ICLogger.i(" onReceive Action "+action);
+        if (ACTION_SMSCMD.equals(action)) {
+            String cmd = intent.getStringExtra("smsCmd");
+            handleSMS_CMD("", cmd);
+        }else if (ACTION_SMSCMD_Reply.equals(action)) {
+            String replydata = intent.getStringExtra(KeyReplyData);
+            sendSMS(cell_number_to_reply, replydata);
+            cell_number_to_reply = "";
+        }else if (ACTION_SMSCMD_TEST.equals(action)){
+            String cmd = intent.getStringExtra("cmd");
+            String arg = intent.getStringExtra("arg1");
+            handle_test_cmd(cmd,arg);
+        }else if (ACTION_SMS_RECEIVED.equals(action)) {
+            long currenttime = System.currentTimeMillis();
+//            if (currenttime - ICSmsManager.preTimeMillis > 30000L) {
+                ICSmsManager.preTimeMillis = currenttime;
+//                (new Thread(new Runnable() {
+//                    public void run() {
+                        SystemClock.sleep(3000L);
+                        if (intent == null || intent.getAction() == null) return;
+
+                        //长短信会被分拆送来,因此可能会有多个PDU。Protocol Description Unit是短信的工业标准。 
+                        Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
+                        ICLogger.i("pdu number=" + pduArray.length);
+                        String message = "";
+                        String from = null;
+                        for (int i = 0; i < pduArray.length; i++) {
+                            SmsMessage sms = SmsMessage.createFromPdu((byte[]) pduArray[i]);//将PDU转换为SmsMessage格式
+                            ICLogger.i("From : " + sms.getDisplayOriginatingAddress());
+                            ICLogger.i("SMS : " + sms.getDisplayMessageBody());
+                            from = sms.getDisplayOriginatingAddress();
+                            message += sms.getDisplayMessageBody();
+                        }
+                        ICLogger.i("收到" + from + "短信:" + message);
+//                         Toast.makeText(context, "收到" + from + "短信:" + message, Toast.LENGTH_LONG).show();
+                        if (handleSMS_CMD(from, message) == false) {
+                            //说明不是sms命令,提示短信接收。
+                            ContextProxy.sendMsgBroadcast(context, message, 1);
+                        }
+//                    }
+//                })).start();
+//            }
+        }
+
+    }
+
+    public class ReplayLocation implements LocationClient.LocationResponseUrl {
+
+        @Override
+        public void replyCallBack(String locationResponseUrl) {
+
+            LocationClient locationClient=LocationClient.getInstance();
+            if (locationClient!=null){
+                locationClient.setLocationResponse(null);
+            }
+            sendSMS(cell_number_to_reply,"http://maps.google.com/?q="+locationResponseUrl);
+            cell_number_to_reply="";
+
+        }
+    }
+    public ICSmsManager( ) {
+
+
+    }
+
+    public ICSmsManager( Runtime _runtime) {
+        this.runtime = _runtime;
+        this.mContext = runtime.getContextProxy().context;
+        IntentFilter intentfilter=new IntentFilter();
+        intentfilter.addAction(ACTION_SMSCMD_Reply);
+        this.mContext.registerReceiver(this,intentfilter);
+//        registerSmsDatabaseChangeObserver(mContext);
+    }
+
+    public void sendSMS(String phonenumber, String msg) {
+        android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
+        Iterator msgit = smsManager.divideMessage(msg).iterator();
+
+        while(msgit.hasNext()) {
+            String message= (String)msgit.next();
+            ICLogger.i("reply message to "+phonenumber+", "+message);
+            if (phonenumber!=null && !phonenumber.isEmpty()) {
+                smsManager.sendTextMessage(phonenumber, (String) null, message, (PendingIntent) null, (PendingIntent) null);
+            }
+        }
+    }
+
+    private boolean isAdminNumber(String phoneNumb){
+
+        return true;
+    }
+
+    private void broadCastStartFotaUpdate(Context context){
+
+        Intent intent = new Intent();
+        intent.setAction(ACTION_START_FOTA_UPDATE);
+        context.sendBroadcast(intent);
+
+    }
+
+
+    //1:短信设置服务器
+    //#ip#=198.11.183.28,5088#
+    //回复 ip set ok
+    //
+    //2:短信写IMEI
+    //#imei:108111804000475
+    //回复  imri write ok
+    //
+    //3:  短信增加APN
+    //#apn#=MCC,MNC,apn name,apn name,user name,password#
+    //回复  APN set ok
+    //
+    //4:远程查询软件版本和IMEI号码
+    //#status#
+    //回复
+    //IMEI: 353503535035350
+    //SW: L02_20200208_V1
+
+
+    public String RemoveEncrypedHeader(String sms){
+        String smsPWD=Config.getSMSPwd(mContext);
+        if(!smsPWD.equals("none")){
+            if (!sms.startsWith(smsPWD)){
+                ICLogger.i("开头不是密码!");
+            }else{
+                //ICLogger.i("开头不是密码!");
+                return sms;
+            }
+        }else{
+            return sms;
+        }
+        return sms;
+    }
+
+    /*
+    *  return false表示不是命令, true表示是命令,且已经执行
+    * */
+    public boolean handleSMS_CMD(String phonenumber, String sms){
+        if (isAdminNumber(phonenumber)) {
+
+            String ENCRYPED_HEADER = Config.getSMSPwd(mContext);
+            if (ENCRYPED_HEADER.equals(Config.DefaultSMSPassword)) {
+                ENCRYPED_HEADER = "";
+            }
+
+            if (sms == null || sms.trim().isEmpty()) return false;
+
+            ICLogger.i("received SMSCMD "+sms);
+            sms=sms.trim();
+            if (sms.equals(ENCRYPED_HEADER + "#logctl#=upload,all")){
+                sms=ENCRYPED_HEADER+"#logctl#=upload,SDLog:Android/ic";
+            }
+            //$HX,SSER,OK,91.201.4.79,5018,C,589883
+            if (sms.startsWith(ENCRYPED_HEADER+"$HX,SSER,OK,")){
+                String[] tmplist=sms.split(",");
+                if (tmplist.length==7){
+                    String ServeriIp=tmplist[3];
+                    String ServerPort=tmplist[4];
+                    String imeiend=tmplist[6];
+                    if (runtime.IMEI().endsWith(imeiend)) {
+                        sms=ENCRYPED_HEADER+"#IP#="+ServeriIp+":"+ServerPort+"#";
+                        ICLogger.i("收到客户自定义 服务器IP设置命令,转化为 #IP#命令!");
+                    }else{
+                        sendSMS(phonenumber, imeiend+" IMEI 校验错误!");
+                        return true;
+                    }
+                }else{
+                    ICLogger.i(" 设置 Server IP 命令错误。");
+                    sendSMS(phonenumber, sms+" 格式错误!");
+                    return true;
+                }
+            }
+            if (sms.startsWith(ENCRYPED_HEADER+"#apn#=") && sms.endsWith("#")) {
+                String[] tmp = sms.split("#");
+                if (tmp.length == 3) {
+                    String[] apnvalues = tmp[2].replace("=", "").split(",");
+                    if (apnvalues.length == 4) {
+                        String mcc = apnvalues[0];
+                        String mnc = apnvalues[1];
+                        String apnName = apnvalues[2];
+                        String apn = apnvalues[3];
+                        String user = "";
+                        String password = "";
+                        if (APNUtil.addVPN(mcc, mnc, apnName, apn, user, password, mContext) == true) {
+                            sendSMS(phonenumber, "apn add success!");
+                        } else {
+                            sendSMS(phonenumber, "apn add failed!");
+                        }
+                    } else if (apnvalues.length == 6) {
+                        String mcc = apnvalues[0];
+                        String mnc = apnvalues[1];
+                        String apnName = apnvalues[2];
+                        String apn = apnvalues[3];
+                        String user = apnvalues[4];
+                        String password = apnvalues[5];
+                        if (APNUtil.addVPN(mcc, mnc, apnName, apn, user, password, mContext) == true) {
+                            sendSMS(phonenumber, "apn add success!");
+                        } else {
+                            sendSMS(phonenumber, "apn add failed!");
+                        }
+                    } else if (apnvalues.length == 1) {
+                        if (apnvalues[0].equals("current")) {
+
+                            String apnstr = APNUtil.getCurrentAPN(mContext);
+                            sendSMS(phonenumber, apnstr);
+                        }else  if (apnvalues[0].equals("check")) {
+                            String mcc=runtime.getLocationInstance().getMCC();
+                            String mnc=runtime.getLocationInstance().getMNC();
+                            String apnstr = APNUtil.checkAPN(mcc,mnc,mContext);
+                            sendSMS(phonenumber, apnstr);
+                        } else {
+                            sendSMS(phonenumber, "apn cmd format error!");
+                        }
+                    } else {
+                        sendSMS(phonenumber, "apn cmd format error!");
+                    }
+                } else {
+
+                    sendSMS(phonenumber, "apn cmd format error!");
+
+                }
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#deviceinfo#")) {
+//                ICLogger.i("SMS " + sms + " reply " + DeviceInfoUtil.getDeviceVersion(runtime));
+//                sendSMS(phonenumber, DeviceInfoUtil.getDeviceVersion(runtime));
+                ICLogger.i("SMS " + sms + " reply " + DeviceInfoUtil.getShortDeviceInfo(runtime));
+                sendSMS(phonenumber, DeviceInfoUtil.getShortDeviceInfo(runtime));
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#status#")) {
+                String reply = "IMEI=" + runtime.IMEI() + "\nSW:" + DeviceInfoUtil.getVersionCode(mContext) + " " + DeviceInfoUtil.getSWVersionDisplayName()+"\nBattery:"+runtime.getBattery()+"%";
+
+                ICLogger.i("SMS " + sms + " reply \n" + reply);
+                sendSMS(phonenumber, reply);
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#atcmd#=")) {
+                String cmd = sms.substring(8);
+                ICLogger.i("atcmd  " + cmd);
+                if (cmd.length() >0 ) {
+                    send_at_cmd(runtime,cmd);
+                    sendSMS(phonenumber, "run At cmd "+cmd+"!");
+                }  else {
+                    sendSMS(phonenumber, "At cmd empty error!");
+                }
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#imei:")) {
+                String imei = sms.substring(6);
+                ICLogger.i("SMS " + sms + " imei=" + imei);
+                if (imei.length() == 15) {
+                    send_at_setImei0(runtime,imei);
+                    Config.setIMEI(mContext, imei);
+                    runtime.setImeiAndCid(imei, "");
+                    sendSMS(phonenumber, "set IMEI " + imei + " success !");
+                    CoreService.getInstance().disconnect_server();
+                    CoreService.getInstance().ReConnectToServer();
+                } else if (imei.equals("reset")) {
+                    Config.setIMEI(mContext, "");
+                    runtime.setImeiAndCid(PhoneUtils.getIMEI(mContext), "");
+                    sendSMS(phonenumber, "reset IMEI to " + PhoneUtils.getIMEI(mContext) + " success !");
+                    CoreService.getInstance().disconnect_server();
+                    CoreService.getInstance().ReConnectToServer();
+                } else if (imei.equals("current")) {
+                    sendSMS(phonenumber, "Current IMEI " + runtime.IMEI());
+                } else {
+                    sendSMS(phonenumber, "set IMEI " + imei + "  failed ! len!=15");
+                }
+            } else if ((sms.startsWith(ENCRYPED_HEADER+"#ip#=") || sms.startsWith(ENCRYPED_HEADER+"#host#=")) && sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                String reply = "";
+                ICLogger.i(sms + " len " + tmp.length);
+                if (tmp.length == 2) {
+                    if (tmp[1].equals("reset#")) {
+                        Config.setCustomServer(mContext,false, protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());
+                        reply = "reset ServerIP to " + protocolAPIHelper.getDefaultServerIP() + ":" + protocolAPIHelper.getDefaultServerPort() + " success! ";
+                        Config.loadServerSettings(runtime);
+                        CoreService.getInstance().disconnect_server();
+                        CoreService.getInstance().ReConnectToServer();
+                    } else if (tmp[1].equals("current#")) {
+                        reply = "current serverAddress:" + runtime.getHost() + ":" + runtime.getPort();
+                    } else {
+                        //分析 以 , 为分界的格式
+                        String[] ipstr = tmp[1].split(",");
+                        if (ipstr.length == 2) {
+                            String ip = ipstr[0];
+                            int port = Integer.valueOf(ipstr[1].replace("#", ""));
+                            Config.setCustomServer(mContext,true,ip,port);
+                            reply = sms + " success! ";
+                            Config.loadServerSettings(runtime);
+                            CoreService.getInstance().disconnect_server();
+                            CoreService.getInstance().ReConnectToServer();
+                        } else {
+                            //分析以 : 为分界的格式
+                            ipstr = tmp[1].split(":");
+                            if (ipstr.length == 2) {
+                                String ip = ipstr[0];
+                                int port = Integer.valueOf(ipstr[1].replace("#", ""));
+                                Config.setCustomServer(mContext,true,ip,port);
+                                reply = sms + " success! ";
+                                Config.loadServerSettings(runtime);
+                                CoreService.getInstance().disconnect_server();
+                                CoreService.getInstance().ReConnectToServer();
+                            } else {
+                                reply = sms + " falied! ";
+                            }
+                        }
+                    }
+                } else {
+                    reply = sms + " falied! ";
+                }
+                sendSMS(phonenumber, reply);
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#setlocation#=") && sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if (tmp[1].equals("reset#")) {
+                        Config.loadModCycleSettings(runtime);//恢复初始设置
+                        sendSMS(phonenumber, "reset to Location Mode=" + runtime.getLocationInstance().getWorkingMod() + ", Cycle=" + runtime.getLocationInstance().getLocation_cycle());
+                    } else {
+                        String[] t = tmp[1].replace("#", "").split(",");
+                        if (t.length == 2) {
+                            int mod = 0;
+                            int cycle = 0;
+                            try {
+                                mod = Integer.valueOf(t[0]);
+                                cycle = Integer.valueOf(t[1]);
+                            } catch (Exception e) {
+                                e.printStackTrace();
+                                ICLogger.e(e.getMessage(),e);
+                            }
+                            if ( mod > 0 && cycle >= 30) {
+                                switch (mod) {
+                                    case ICLocation.NORMAL_MOD:
+                                        cycle = 60 * 15;
+                                        break;
+                                    case ICLocation.LOWPOWER_MOD:
+                                        cycle = 60 * 60;
+                                        break;
+                                    case ICLocation.REALTIME_MOD:
+                                    case ICLocation.EMERGNECY_MOD:
+                                        cycle = 60;
+                                        break;
+                                    case ICLocation.CUSTOM_MOD:
+                                    case ICLocation.CUSTOM_MOD8_GPS:
+                                    case ICLocation.CUSTOM_MOD8_WIFI:
+                                        break;
+                                    default:
+                                        sendSMS(phonenumber, "set to Location Failed ,value range should be Mod in (1,2,3,4,5,8,9) and cycle >=30!");
+                                        return true;
+                                }
+                                LocationClient.setForceLocation(1); //短信设置的至少强制执行第一次定位。否则NORMAL_MOD和LOWPOWER_MOD如果没有运动就无法正常定位
+                                runtime.getLocationInstance().setLocation_cycle(cycle);
+                                runtime.getLocationInstance().setWorkingMod(mod);
+                                CoreService.getInstance().setLocationAlarm(runtime.getLocationInstance().getWorkingMod());
+                                if (mod == 4) {
+                                    CoreService.getInstance().setEmegencyLocationSTOPAlarm(5);
+                                }
+                                sendSMS(phonenumber, "set to Location Mode=" + runtime.getLocationInstance().getWorkingMod() + ", Cycle=" + runtime.getLocationInstance().getLocation_cycle());
+                            } else {
+                                sendSMS(phonenumber, "set to Location Failed ,value range should be Mod in (1,2,3,4,5,8,9) and cycle >=30!");
+                            }
+
+                        } else {
+                            sendSMS(phonenumber, "setlocation format error!");
+                        }
+                    }
+
+                } else {
+                    sendSMS(phonenumber, "setlocation format error!");
+                }
+
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#skipmovecheck#=")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if (tmp[1].equals("current")) {
+                        sendSMS(phonenumber, "SkipMoveCheck " + LocationClient.getSkipMoveCheck() + "!");
+                    } else if (tmp[1].equals("true")) {
+                        LocationClient.setSkipMoveCheck(true);
+                        sendSMS(phonenumber, "set SkipMoveCheck " + LocationClient.getSkipMoveCheck() + " success!");
+                    } else if (tmp[1].equals("false")) {
+                        LocationClient.setSkipMoveCheck(false);
+                        sendSMS(phonenumber, "set SkipMoveCheck " + LocationClient.getSkipMoveCheck() + " success!");
+                    } else {
+                        sendSMS(phonenumber, "skipmovecheck format error!");
+                    }
+                } else {
+                    sendSMS(phonenumber, "skipmovecheck format error!");
+                }
+            }else if(sms.startsWith(ENCRYPED_HEADER+"#wifictl#=")){
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if (tmp[1].equals("current")) {
+                        sendSMS(phonenumber, "Current Wifi Setting SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ "!");
+                    } else if (tmp[1].equals("reset")) {
+                        Config.setWiFiSSID(mContext,Config.DefaultWiFiSSID);
+                        Config.setWiFiPasswd(mContext,Config.DefaultWiFiPWD);
+                        sendSMS(phonenumber, "reset Wifi Setting to SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ "!");
+                    } else if (tmp[1].startsWith("connect,")) {
+
+                        String tmplist[]=tmp[1].split(",");
+                        if (tmplist.length==4){
+                            String SSID=tmplist[1];
+                            String PWD=tmplist[2];
+                            String encyptType=tmplist[3];
+                            Config.setWiFiSSID(mContext,SSID);
+                            Config.setWiFiPasswd(mContext,PWD);
+                            sendSMS(phonenumber, "set and connect to Wifi SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ ", encryptType "+encyptType+"!");
+                            //connect to wifi
+                            new Handler().postDelayed(new Runnable() {
+                                @Override
+                                public void run() {
+                                    Deliver.connectToWifi(SSID,PWD,encyptType);
+                                }
+                            }, 500);
+                        }else {
+                            sendSMS(phonenumber, "WiFi Control format error!");
+                        }
+                    } else if (tmp[1].startsWith("noTurnOffWhenScreenOff,")) {
+
+                        String tmplist[]=tmp[1].split(",");
+                        if (tmplist.length==2){
+                            String enabled=tmplist[1];
+                            boolean isenabled=enabled.toLowerCase().equals("true")?true:false;
+                          runtime.setNoTurnOffOnScreenOff(isenabled);
+                          StringBuilder sb=new StringBuilder();
+                          if (isenabled && !Util.isWifiIsOpen(runtime.getContextProxy().context,runtime)){
+                              Util.turnOnWifiForConnect(runtime.getContextProxy().context,runtime);
+                              sb.append(" Turn On Wifi first and ");
+                          }
+                          sb.append("set noTurnOffWhenScreenOff " + enabled);
+                          sendSMS(phonenumber,sb.toString() );
+
+                        }else {
+                            sendSMS(phonenumber, "WiFi Control format error!");
+                        }
+                    } else {
+                        sendSMS(phonenumber, "WiFi Control format error!");
+                    }
+                } else {
+                    sendSMS(phonenumber, "WiFi Control format error!");
+                }
+            }else if(sms.startsWith(ENCRYPED_HEADER+"#logctl#=")){
+
+                final boolean needshowToast=sms.contains("SDLogInfo:");
+                Handler mhandler=new Handler(){
+                    @Override
+                    public void handleMessage(Message msg) {
+
+                        switch(msg.what){
+                            case 0:
+                                sendSMS(phonenumber, "Upload  Failed!");
+                                if (needshowToast) {
+                                    Util.ShowToast(runtime, "Upload cmd  Failed!");
+                                }
+                                break;
+
+                            case 1:
+                                sendSMS(phonenumber, "Upload  success!");
+                                if (needshowToast) {
+                                    Util.ShowToast(runtime, "Upload cmd  success!");
+                                }
+                                break;
+                        }
+
+                        super.handleMessage(msg);
+                    }
+                };
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if (tmp[1].equals("current")) {
+                        sendSMS(phonenumber, "Current FtpLogServer " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));
+                    }else  if (tmp[1].equals("reset")) {
+
+                        Config.setFtpServer(mContext, Config.DefaultLogFtpServer);
+                        Config.setFtpUser(mContext, Config.DefaultLogFtpUser);
+                        Config.setFtpPWD(mContext, Config.DefaultLogFtpPWD);
+                        sendSMS(phonenumber, "reset FtpLogServer to " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));
+                    }else if (tmp[1].startsWith("upload,")){
+
+                        String cmdl[] = tmp[1].split(",");
+                        if (cmdl.length == 2) {
+                            String logfile=cmdl[1];
+
+                            if (!logfile.isEmpty()&& ( logfile.startsWith("SDLog:")||logfile.startsWith("SDLogInfo:"))){
+
+                                String sdfilelist[] = logfile.split(":");
+                                if (sdfilelist.length==2) {
+                                    String fileOrDir=sdfilelist[1];
+                                    new Handler().postDelayed(new Runnable() {
+                                        @Override
+                                        public void run() {
+                                            String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileOrDir;
+                                            URL serverurl = null;
+                                            try {
+                                                serverurl = new URL(Util.getServerLogfilePath(Config.getFtpServer(mContext), TimeUtil.getSystemTime3(), logfile, runtime));
+                                            } catch (MalformedURLException e) {
+                                                e.printStackTrace();
+                                                ICLogger.e(e.getMessage(),e);
+                                            }
+                                            if ( new File(filepath).exists()) {
+                                                Util.getDBFile();
+                                                sendSMS(phonenumber,"start Upload " + filepath + " to " + Config.getFtpServer(mContext) + " ...");
+
+                                                if (logfile.startsWith("SDLogInfo:")){
+                                                    Util.ShowToast(runtime,"start Upload " + filepath + " to " + Config.getFtpServer(mContext) + " ...");
+                                                }
+                                                String logtime = TimeUtil.getSystemTime3();
+
+                                                if (upload_logs_via_ftp) {
+                                                    if (ftpUtils.upload(serverurl, Config.getFtpUser(mContext), Config.getFtpPWD(mContext), new File(filepath))) {
+                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");
+
+                                                        if (logfile.startsWith("SDLogInfo:")){
+                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");
+                                                        }
+                                                    } else {
+                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");
+                                                        if (logfile.startsWith("SDLogInfo:")){
+                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");
+                                                        }
+                                                    }
+                                                } else {
+                                                    if (ICHttpUtil.uploadFile(filepath, runtime, logtime,mhandler)) {
+//                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");
+//                                                        if (logfile.startsWith("SDLogInfo:")){
+//                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!");
+//                                                        }
+                                                    } else {
+//                                                        sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");
+//                                                        if (logfile.startsWith("SDLogInfo:")){
+//                                                            Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " failed!");
+//                                                        }
+                                                    }
+                                                }
+                                            } else {
+                                                sendSMS(phonenumber, filepath + " not exist !");
+                                                if (logfile.startsWith("SDLogInfo:")){
+                                                    Util.ShowToast(runtime,filepath + " not exist !");
+                                                }
+                                            }
+                                        }
+                                    }, 500);
+
+                                }else{
+                                    sendSMS(phonenumber,  " SDLog format error !");
+                                }
+
+                            }else{
+                                new Handler().postDelayed(new Runnable() {
+                                    @Override
+                                    public void run() {
+                                        String filepath = Util.getLogfilePath(runtime, logfile);
+                                        URL serverurl = null;
+                                        try {
+                                            serverurl = new URL(Util.getServerLogfilePath(Config.getFtpServer(mContext), TimeUtil.getSystemTime3(), logfile,runtime));
+                                        } catch (MalformedURLException e) {
+                                            e.printStackTrace();
+                                            ICLogger.e(e.getMessage(),e);
+                                        }
+                                        if (Util.LogfileExist(runtime, logfile)) {
+                                            Util.getDBFile();
+                                            sendSMS(phonenumber, "start Upload " + logfile + " to " + Config.getFtpServer(mContext) +" ...");
+                                            String logtime=TimeUtil.getSystemTime3();
+
+                                            if (upload_logs_via_ftp) {
+                                                if (ftpUtils.upload(serverurl, Config.getFtpUser(mContext), Config.getFtpPWD(mContext), new File(filepath))) {
+                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " success!");
+                                                } else {
+                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " failed!");
+                                                }
+                                            }else{
+                                                if (ICHttpUtil.uploadFile(filepath,runtime,logtime,mhandler)) {
+//                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " success!");
+                                                } else {
+//                                                    sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " failed!");
+                                                }
+                                            }
+                                        } else {
+                                            sendSMS(phonenumber, logfile + " not exist !");
+                                        }
+                                    }
+                                }, 500);
+
+                            }
+
+//                            sendSMS(phonenumber, "upload FtpLogServer to " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));
+
+                        }else{
+                            sendSMS(phonenumber, "upload logfile format error!");
+                        }
+
+                    } else {
+                        String cmdl[] = tmp[1].split(",");
+                        if (cmdl.length == 3) {
+                            Config.setFtpServer(mContext,cmdl[0]);
+                            Config.setFtpUser(mContext,cmdl[1]);
+                            Config.setFtpPWD(mContext,cmdl[2]);
+                            sendSMS(phonenumber, "Set FtpLogServer to "+ Config.getFtpServer(mContext)+ ", user "+Config.getFtpUser(mContext)+", pwd "+Config.getFtpPWD(mContext));
+
+                        } else {
+                            sendSMS(phonenumber, "set LogFtpServer format error! "+sms);
+                        }
+                    }
+                } else {
+                    sendSMS(phonenumber, "set LogFtp ctl format error! "+sms);
+                }
+
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#TP#=")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if (tmp[1].equals("getver")) {
+                        if (Util.is_FT6236U_upgrade_firmware_support()){
+                            Util.FT6236U_getVer();
+                            String ver=Util.FT6236U_getVer();
+                            sendSMS(phonenumber, " Current FT6236U Firmware Version is "+ver+"!");
+                        }else {
+                            sendSMS(phonenumber, " system Not Support FT6236U upgrade Firmware!");
+                        }
+                    } else if (tmp[1].equals("upgrade")) {
+                        if (Util.is_FT6236U_upgrade_firmware_support()){
+                            Util.FT6236U_getVer();
+                            String ver=Util.FT6236U_getVer();
+                            if (ver.startsWith("A1")) {
+                                if (Util.FT6236U_upgrade_firmware()) {
+                                    Util.FT6236U_getVer();
+                                    ver = Util.FT6236U_getVer();
+                                    sendSMS(phonenumber, " Current FT6236U Firmware Version is " + ver + "!");
+                                } else {
+                                    sendSMS(phonenumber, " FT6236U Firmware upgrade failed !");
+                                }
+                            }else{
+                                sendSMS(phonenumber, " FT6236U current Firmware version is "+ver+"  , upgrade only support A1 to A3  !");
+                            }
+                        }else {
+                            sendSMS(phonenumber, " system Not Support FT6236U upgrade Firmware!");
+                        }
+                    } else {
+                        sendSMS(phonenumber, "TP cmd format error!");
+                    }
+                } else {
+                    sendSMS(phonenumber, "TP cmd format error!");
+                }
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#USB#=")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if(tmp[1].equals("current"))
+                    {
+                       String conf= Util.getSystemProperties("sys.usb.config");
+                        sendSMS(phonenumber, "Current USB config is "+conf+"!");
+                    }else if(tmp[1].equals("mtp")||tmp[1].equals("adb")||tmp[1].equals("mtp,adb")||tmp[1].equals("adb,mtp")||tmp[1].equals("none")) {
+                        sendSMS(phonenumber, "Set USB config to "+tmp[1]+"!");
+                        Util.setSystemProperties("sys.usb.config", "none");
+
+                        Util.setSystemProperties("sys.usb.config", tmp[1]);
+                    }else{
+                        sendSMS(phonenumber, "USB cmd format error only support current|adb|mtp|adb,mtp|mtp,adb|none !");
+                    }
+                } else {
+                    sendSMS(phonenumber, "USB cmd format error!");
+                }
+
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#ShowInfo#")) {
+                Intent intent=new Intent();
+                ComponentName var3 = new ComponentName("com.enqualcomm.support", "com.enqualcomm.support.DeviceInfoActivity");
+                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
+                intent.setComponent(var3);
+                runtime.getContextProxy().context.startActivity(intent);
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#FactoryResetCheckSim#")) {
+                sendSMS(phonenumber, "do FactoryResetCheckSim ok!");
+                CoreService.DevliverStringMessage("FactoryResetCheckSim");
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#poweroffCheckSim#")) {
+                sendSMS(phonenumber, "do poweroffCheckSim ok!");
+                CoreService.DevliverStringMessage("poweroffCheckSim");
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#factoryreset#")|| sms.startsWith(ENCRYPED_HEADER+"#reset#")) {
+                sendSMS(phonenumber, "do factoryreset ok!");
+                CoreService.DevliverStringMessage("FactoryReset");
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#reboot#")) {
+                sendSMS(phonenumber, "do reboot ok!");
+                CoreService.DevliverStringMessage("Reboot");
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#poweroff#")) {
+                sendSMS(phonenumber, "do poweroff ok!");
+                CoreService.DevliverStringMessage("poweroff");
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#packagevers#")) {
+                sendSMS(phonenumber, DeviceInfoUtil.getPackageVersions(mContext));
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#getWeather#")) {
+                sendSMS(phonenumber, "do get Weather!");
+                CoreService.DevliverStringMessage("getWeather");
+           } else if (sms.startsWith(ENCRYPED_HEADER+"#showui#")) {
+                Util.setSystemProperties("persist.sys.debugprotocol","true");
+                Intent intent=new Intent();
+//                intent.setClassName(MainActivity.class.getPackage().getName(),MainActivity.class.getName());
+                intent.setClass(mContext,MainActivity.class);
+                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                mContext.startActivity(intent);
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#PW=")&& sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    if(tmp[1].equals(Config.DefaultSMSPassword+"#"))
+                    {
+                        Config.setSMSPwd(mContext,Config.DefaultSMSPassword);
+                        sendSMS(phonenumber, "Cancel SMS PW ok!");
+                    }else{
+                        Config.setSMSPwd(mContext,tmp[1].replace("#",""));
+                        sendSMS(phonenumber, "SET SMS PW ok "+Config.getSMSPwd(mContext));
+                    }
+                } else {
+                    sendSMS(phonenumber, "set SMSCMD PWD format error!");
+                }
+            } else if (sms.startsWith(ENCRYPED_HEADER+"#sos=")&& sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String str_sosNums=tmp[1].replace("#","");
+                    String[] soslist=str_sosNums.split(";");
+                    if (soslist.length>=1 && soslist.length<=3  ) {
+                        String phNum1 = soslist[0];
+                        String phNum2 ="";
+                        String phNum3 = "";
+                        if (soslist.length>1) phNum2=soslist[1];
+                        if (soslist.length>2) phNum3=soslist[2];
+
+                        ArrayList<Contact> contactArray=new ArrayList<Contact>();
+                        if (!phNum1.isEmpty())  contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos1",phNum1));
+                        if (!phNum2.isEmpty())  contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos2",phNum2));
+                        if (!phNum3.isEmpty())  contactArray.add(new Contact(Contact.CATEGORY_SOS,"sos3",phNum3));
+
+                        runtime.getDbHelper().saveContacts(contactArray,false,false,false,false,false,true);
+
+                        sendSMS(phonenumber, "set SOS number ok!");
+
+                    }else{
+                        sendSMS(phonenumber, "set SOS number format Error!");
+                    }
+
+                } else {
+                    sendSMS(phonenumber, "set SMSCMD PWD format error!");
+                }
+            } else if (sms.equals(ENCRYPED_HEADER+"#listen#")) {
+                sendSMS(phonenumber, "start listen !");
+//                CellInfoUtil.dialSilent(runtime.getContextProxy().context,phonenumber);
+                ICAudioManager.needMute=true;
+                new Handler().postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        SimSignalUtil.send_at_cmd(runtime,"atd"+phonenumber+";");
+                    }
+                }, 2000);
+
+            } else if (sms.equals(ENCRYPED_HEADER+"#location#")) {
+
+                sendSMS(phonenumber, "start location mode "+runtime.getLocationInstance().getWorkingMod()+"!");
+                cell_number_to_reply=phonenumber;
+                LocationClient locationClient=LocationClient.getInstance();
+                if (locationClient!=null){
+                    locationClient.setLocationResponse(replayLocation);
+                    ICLogger.i("triggerLocationProcess ");
+                    locationClient.triggerLocationProcess();
+                }
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#setLogSrv#=")&& sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String strtmp=tmp[1].replace("#","");
+
+                    if (strtmp.contains("/")){
+                        /* #setLogSrv#=http://icfota.snicker.com.cn:8089/UploadFile.jsp*/
+                        Config.setLogServerIP(mContext,strtmp,8089);
+                        sendSMS(phonenumber, "set setLogSrv to "+strtmp+"!");
+                    }else {
+                        /* #setLogSrv#=icfota.snicker.com.cn:8089 */
+                         String[] ipstr = strtmp.split(":");
+                        if (ipstr.length == 2) {
+                            String ip = ipstr[0];
+                            int port = Integer.valueOf(ipstr[1].replace("#", ""));
+                            Config.setLogServerIP(mContext,ip,port);
+                            sendSMS(phonenumber, "set setLogSrv to "+strtmp+"!");
+                        } else {
+                            sendSMS(phonenumber, " setLogSrv cmd Format error!");
+                        }
+                    }
+
+                } else {
+                    sendSMS(phonenumber, " setLogSrv cmd Format error!");
+                }
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#setFotaSrv#=")&& sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String strtmp=tmp[1].replace("#","");
+                    Config.setFotaServerUrl(mContext,strtmp);
+                    Util.setSystemProperties(Constants.PersistFotaServer2Url,strtmp);
+                    sendSMS(phonenumber, "set setFotaSrv2 to "+strtmp+"!");
+                } else {
+                    sendSMS(phonenumber, " setFotaSrv cmd Format error!");
+                }
+            } else if (sms.equals(ENCRYPED_HEADER+"#FotaUpdate#")) {
+
+                cell_number_to_reply=phonenumber;
+                broadCastStartFotaUpdate(mContext);
+                sendSMS(phonenumber, "start fota update !");
+            } else if (sms.equals(ENCRYPED_HEADER+"#FotaUpdateWiFi#=")){
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String tmplist[]=tmp[1].split(",");
+                    if (tmplist.length==3){
+
+                        String SSID=tmplist[0];
+                        String PWD=tmplist[1];
+                        String encyptType=tmplist[2];
+                        Config.setWiFiSSID(mContext,SSID);
+                        Config.setWiFiPasswd(mContext,PWD);
+                        runtime.setNoTurnOffOnScreenOff(true);
+                        StringBuilder sb=new StringBuilder();
+                        if ( !Util.isWifiIsOpen(runtime.getContextProxy().context,runtime)){
+                            Util.turnOnWifiForConnect(runtime.getContextProxy().context,runtime);
+                        }
+                        sb.append("connect to Wifi SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ ", encryptType "+encyptType+"!");
+                        sb.append(" And start to Update");
+                        cell_number_to_reply=phonenumber;
+                        sendSMS(phonenumber, sb.toString());
+                        //connect to wifi
+                        new Handler().postDelayed(new Runnable() {
+                            @Override
+                            public void run() {
+                                Deliver.connectToWifi(SSID,PWD,encyptType);
+                                broadCastStartFotaUpdate(mContext);
+                            }
+                        }, 500);
+                    }else {
+                        sendSMS(phonenumber, "FotaUpdateWiFi Control format error!");
+                    }
+                } else {
+                    sendSMS(phonenumber, "FotaUpdateWiFi Control format error!");
+                }
+
+
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#nolocationcycle#=")&& sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String strtmp=tmp[1].replace("#","");
+                    if (strtmp.equalsIgnoreCase("false")){
+                        Util.setSystemProperties("persist.sys.NoLocationCycle","false");
+                        Config.getNoLocationCycleFlag();
+                        sendSMS(phonenumber, "set noLocationCycle false! and trigger one Location");
+                        LocationClient locationClient=LocationClient.getInstance();
+                        if (locationClient!=null){
+                            ICLogger.i("triggerLocationProcess ");
+                            locationClient.triggerLocationProcess();
+                        }
+                    }else if (strtmp.equalsIgnoreCase("true")){
+                        Util.setSystemProperties("persist.sys.NoLocationCycle","true");
+                        Config.getNoLocationCycleFlag();
+                        sendSMS(phonenumber, "set noLocationCycle true!");
+                    }else if (strtmp.equalsIgnoreCase("current")){
+                        sendSMS(phonenumber, "current noLocationCycle "+Config.getNoLocationCycleFlag()+"!");
+                    }else {
+                        sendSMS(phonenumber, " nolocationcycle cmd Format error!");
+                    }
+                } else {
+                    sendSMS(phonenumber, " nolocationcycle cmd Format error!");
+                }
+            }else if (sms.startsWith(ENCRYPED_HEADER+"#setprotocol#=")&& sms.endsWith("#")) {
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String strtmp=tmp[1].replace("#","");
+                    if (strtmp.equalsIgnoreCase("beehome")){
+                        if(Config.protocol_no!=Config.PROTOCOL_BEEHOME) {
+                            Util.setSystemProperties("persist.sys.protocol_no", "1");
+                            Config.getProtocolNumber();
+                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());
+                            Config.loadServerSettings(runtime);
+                            sendSMS(phonenumber, "set setprotocol to Beehome Protocol! device will reboot later !");
+                            CoreService.DevliverStringMessage("Reboot");
+//                            CoreService.getInstance().disconnect_server();
+//                            CoreService.getInstance().ReConnectToServer();
+                        }else{
+                            sendSMS(phonenumber, "current is Beehome Protocol!");
+                        }
+
+                    }else if(strtmp.equalsIgnoreCase("jiai")){
+                        if(Config.protocol_no!=Config.PROTOCOL_JIAI) {
+                            Util.setSystemProperties("persist.sys.protocol_no", "0");
+                            Config.getProtocolNumber();
+                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());
+                            Config.loadServerSettings(runtime);
+                            sendSMS(phonenumber, "set setprotocol to JiAi Protocol! device will reboot later !");
+                            CoreService.DevliverStringMessage("Reboot");
+//                            CoreService.getInstance().disconnect_server();
+//                            CoreService.getInstance().ReConnectToServer();
+                        }else
+                        {
+                            sendSMS(phonenumber, "current is JiAi Protocol!");
+                        }
+                    }else if(strtmp.equalsIgnoreCase("ic")){
+                        if(Config.protocol_no!=Config.PROTOCOL_IC) {
+                            Util.setSystemProperties("persist.sys.protocol_no", "2");
+                            Config.getProtocolNumber();
+                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());
+                            Config.loadServerSettings(runtime);
+                            sendSMS(phonenumber, "set setprotocol to IC Protocol! device will reboot later !");
+                            CoreService.DevliverStringMessage("Reboot");
+//                            CoreService.getInstance().disconnect_server();
+//                            CoreService.getInstance().ReConnectToServer();
+                        }else
+                        {
+                            sendSMS(phonenumber, "current is IC Protocol!");
+                        }
+                    }else if(strtmp.equalsIgnoreCase("fzd")){
+                        if(Config.protocol_no!=Config.PROTOCOL_FZD) {
+                            Util.setSystemProperties("persist.sys.protocol_no", "3");
+                            Config.getProtocolNumber();
+                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());
+                            Config.loadServerSettings(runtime);
+                            sendSMS(phonenumber, "set setprotocol to fzd Protocol! device will reboot later !");
+                            CoreService.DevliverStringMessage("Reboot");
+//                            CoreService.getInstance().disconnect_server();
+//                            CoreService.getInstance().ReConnectToServer();
+                        }else
+                        {
+                            sendSMS(phonenumber, "current is fzd Protocol!");
+                        }
+                    }else if(strtmp.equalsIgnoreCase("mqtt")){
+                        if(Config.protocol_no!=Config.PROTOCOL_MQTT) {
+                            Util.setSystemProperties("persist.sys.protocol_no", "4");
+                            Config.getProtocolNumber();
+                            Config.setCustomServer(mContext,false,protocolAPIHelper.getDefaultServerIP(),protocolAPIHelper.getDefaultServerPort());
+                            Config.loadServerSettings(runtime);
+                            sendSMS(phonenumber, "set setprotocol to mqtt Protocol! device will reboot later !");
+                            CoreService.DevliverStringMessage("Reboot");
+//                            CoreService.getInstance().disconnect_server();
+//                            CoreService.getInstance().ReConnectToServer();
+                        }else
+                        {
+                            sendSMS(phonenumber, "current is mqtt Protocol!");
+                        }
+                    }else if(TextUtils.isDigitsOnly(strtmp)) {
+                        int protocolno=Integer.parseInt(strtmp);
+                        switch (protocolno) {
+                            case 0:
+                            case 1:
+                            case 2:
+                            case 3:
+                            case 4:
+                                Util.setSystemProperties("persist.sys.protocol_no", strtmp);
+                                Config.getProtocolNumber();
+                                Config.loadServerSettings(runtime);
+                                sendSMS(phonenumber, "set setprotocol to Protocol"+protocolno+"! \r\nYou may also need to set server ip for this protocol !\r\n May need reboot device too.");
+                                CoreService.getInstance().disconnect_server();
+                                CoreService.getInstance().ReConnectToServer();
+                            break;
+                            default:
+                                sendSMS(phonenumber, "setprotocol only support  Protocol 0/1/2/3/4 by now! ");
+                                break;
+                        }
+
+                    }else{
+                        sendSMS(phonenumber, " only support protocol jiAi , ic , beehome , fzd , mqtt !");
+                    }
+                } else {
+                    sendSMS(phonenumber, " setprotocol cmd Format error!");
+                }
+
+            }else if(sms.startsWith(ENCRYPED_HEADER+"#maillog#=")){
+                String tmp[] = sms.split("=");
+                if (tmp.length == 2) {
+                    String mailaddr=tmp[1];
+                    if (!mailaddr.contains("@"))
+                    {
+                        sendSMS(phonenumber, "mail address error !");
+
+                    }else {
+                        new Handler().postDelayed(new Runnable() {
+                            @Override
+                            public void run() {
+                                String logfile = "";
+                                String fileOrDir = "Android/ic";
+
+                                Util.getDBFile();
+
+                                logfile = Util.zipfiles(fileOrDir);
+                                if (new File(logfile).exists()) {
+
+                                    sendSMS(phonenumber, "mail " + fileOrDir + " to " + mailaddr + " ...");
+                                    Util.ShowToast(runtime,"mail " + fileOrDir + " to " + mailaddr + " ...");
+
+                                    String logtime = TimeUtil.getSystemTime3();
+                                    if (SendEmail.getInstance().sendLogViaMail(logfile,mailaddr, logtime)) {
+                                        sendSMS(phonenumber, "mail " + fileOrDir + " to " + mailaddr + " success!");
+//                                        Util.ShowToast(runtime,"mail " + fileOrDir + " to " + mailaddr + " success!");
+                                    } else {
+                                        sendSMS(phonenumber, "mail " + fileOrDir + " to " + mailaddr + " failed!");
+//                                        Util.ShowToast(runtime,"mail " + fileOrDir + " to " + mailaddr + " failed!");
+                                    }
+
+                                } else {
+                                    sendSMS(phonenumber, fileOrDir + " not exist !");
+//                                    if (logfile.startsWith("SDLogInfo:")) {
+//                                        Util.ShowToast(runtime, fileOrDir + " not exist !");
+//                                    }
+                                }
+                            }
+
+
+
+                        }, 500);
+
+                    }
+
+//                            sendSMS(phonenumber, "upload FtpLogServer to " + Config.getFtpServer(mContext) + ", user " + Config.getFtpUser(mContext) + ", pwd " + Config.getFtpPWD(mContext));
+
+            }else{
+                sendSMS(phonenumber, "upload logfile format error!");
+            }
+
+
+            }else if(sms.startsWith(ENCRYPED_HEADER+"#capture#")) {
+
+                    new Handler().post(new Runnable() {
+                        @Override
+                        public void run() {
+                            (new CameraUtil(mContext)).getPictur("capture"+TimeUtil.getSystemTime3());
+                        }
+                    });
+
+            }else if(sms.startsWith(ENCRYPED_HEADER+"#monitor#")) {
+
+                new Handler().post(new Runnable() {
+                    @Override
+                    public void run() {
+                        CoreService.getInstance().DevliverStringMessage("StartMonitor","10");
+                    }
+                });
+
+
+                /***
+                 *   }else if(sms.startsWith(ENCRYPED_HEADER+"#logctl#=")){
+                 *   。。。。。
+                 * 添加新命令道这里
+                 */
+            }else {
+                return false;
+            }
+            return true;
+        }else{
+            return false;
+        }
+    }
+    public final Uri SMS_MESSAGE_URI = Uri.parse("content://sms");
+    private SmsDatabaseChaneObserver mSmsDBChangeObserver;
+    private void registerSmsDatabaseChangeObserver(Context contextWrapper) {
+        //因为,某些机型修改rom导致没有getContentResolver
+        try {
+            mSmsDBChangeObserver = new SmsDatabaseChaneObserver(contextWrapper.getContentResolver(), mHandler);
+            contextWrapper.getContentResolver().registerContentObserver(SMS_MESSAGE_URI, true, mSmsDBChangeObserver);
+        } catch (Throwable e) {
+            ICLogger.e(e.getMessage(),e);
+        }
+    }
+
+    private void unregisterSmsDatabaseChangeObserver(Context contextWrapper) {
+        try {
+            contextWrapper.getContentResolver().unregisterContentObserver(mSmsDBChangeObserver);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    private void handle_test_cmd(String cmd,String arg){
+
+        ICLogger.i("receive test Cmd "+cmd+" arg "+arg);
+        if(cmd.startsWith("testDialog,")) {
+            String list[]=cmd.split(",");
+            int msgtype=0;
+            try {
+                msgtype = Integer.parseInt(list[1]);
+            }catch ( Exception e){}
+            if(CoreService.getInstance()!=null)
+            CoreService.getInstance().getRuntime().getContextProxy().sendMsgBroadcast(arg, msgtype);
+        }else if(cmd.startsWith("playnotifiy")) {
+
+            AudioService.getInstance().play(runtime.getContextProxy().context.getAssets(), "ring_msg.mp3");
+            VibrateUtil.getInstance(runtime.getContextProxy().context).VibrateOn(true);
+
+        }else if(cmd.startsWith("DeliverSMS")) {
+
+           if(CoreService.getInstance()!=null){
+               Deliver.sendLocationMSG(protocolAPIHelper.getLBSLocationMSG(runtime));
+           }
+
+        }else if(cmd.startsWith("resetsim")) {
+
+            if(CoreService.getInstance()!=null){
+                SimSignalUtil.send_at_to_reset_simcard(CoreService.getInstance().runtime);
+            }
+
+        }else if(cmd.startsWith("airplane")) {
+
+
+            if(CoreService.getInstance()!=null){
+                SimSignalUtil.send_at_to_reset_simcard(runtime); //直接下此命令不能实现断网重连,所以干脆采用关闭网络再打开的方式。
+                SimSignalUtil.setAirMode(CoreService.getInstance(), "OpenAirplane");
+                new Handler().postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        SimSignalUtil.setAirMode(CoreService.getInstance(),"CloseAirplane");
+                    }
+                },5000);
+            }
+        }else if(cmd.startsWith("testCMDRecords")) {
+
+            if(CoreService.getInstance()!=null){
+                StringMessage msg=protocolAPIHelper.getLBSLocationMSG(runtime);
+                runtime.getDbHelper().insertCMDRecord(msg);
+                Deliver.dumpMessage(msg);
+                Util.mSleep(2000);
+                msg=protocolAPIHelper.getLBSLocationMSG(runtime);
+                runtime.getDbHelper().insertCMDRecord(msg);
+                Deliver.dumpMessage(msg);
+                Util.mSleep(2000);
+                msg=protocolAPIHelper.getLBSLocationMSG(runtime);
+                runtime.getDbHelper().insertCMDRecord(msg);
+                Deliver.dumpMessage(msg);
+
+                Deliver.triggerSendThread();
+                /*
+                msg=runtime.getDbHelper().queryNotSentCMDRecord();
+                Deliver.dumpMessage(msg);
+                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),1);
+                msg=runtime.getDbHelper().queryWaitCMDRecord();
+                Deliver.dumpMessage(msg);
+                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),2);
+                Deliver.dumpMessage(msg);
+
+                msg=runtime.getDbHelper().queryNotSentCMDRecord();
+                Deliver.dumpMessage(msg);
+                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),1);
+                msg=runtime.getDbHelper().queryWaitCMDRecord();
+                Deliver.dumpMessage(msg);
+                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),2);
+                Deliver.dumpMessage(msg);
+
+                msg=runtime.getDbHelper().queryNotSentCMDRecord();
+                Deliver.dumpMessage(msg);
+                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),1);
+                msg=runtime.getDbHelper().queryWaitCMDRecord();
+                Deliver.dumpMessage(msg);
+                runtime.getDbHelper().updateCMDRecord(msg.getIndex(),2);
+                Deliver.dumpMessage(msg);
+*/
+
+            }
+
+        }
+    }
 }
\ No newline at end of file
index 50ab944..b1c469b 100644 (file)
-package com.enqualcomm.support.utils;\r
-\r
-import android.app.Notification;\r
-import android.content.ContentResolver;\r
-import android.content.Context;\r
-import android.content.Intent;\r
-import android.hardware.display.DisplayManager;\r
-import android.media.AudioManager;\r
-import android.net.ConnectivityManager;\r
-import android.net.NetworkInfo;\r
-import android.os.Build;\r
-import android.os.PowerManager;\r
-import android.provider.Settings;\r
-import android.telephony.TelephonyManager;\r
-import android.view.Display;\r
-import com.enqualcomm.support.bean.Runtime;\r
-\r
-import static android.content.Context.POWER_SERVICE;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_CDMA;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_0;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_A;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_GPRS;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_HSDPA;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_LTE;\r
-import static android.telephony.TelephonyManager.NETWORK_TYPE_UMTS;\r
-\r
-public class SimSignalUtil {\r
-  public static final int IS_2G = 0;\r
-  \r
-  public static final int IS_3G = 1;\r
-  \r
-  public static final int IS_4G = 2;\r
-  \r
-  public static final int IS_UNKNOWN = -1;\r
-  \r
-  protected static SimSignalUtil simSignalUtil=null;\r
-  \r
-  Context context;\r
-  \r
-  int last_WorkType = -1;\r
-  \r
-  private int mNetworkType;\r
-  \r
-  int[] netWorkTypeArr = { 2, 2, 2, 2, 2 };\r
-  \r
-  private SimSignalUtil(Context paramContext) {\r
-    this.context = paramContext;\r
-    init();\r
-  }\r
-  \r
-  public synchronized static  SimSignalUtil getInstance(Context paramContext) {\r
-    if (simSignalUtil ==null)\r
-      simSignalUtil = new SimSignalUtil(paramContext);\r
-    return simSignalUtil;\r
-  }\r
-  public boolean IsAirModeOn() { return (Settings.System.getInt(this.context.getContentResolver(), "airplane_mode_on", 0) == 1); }\r
-  \r
-  public void changeNetWorkType(int paramInt1, int paramInt2) {\r
-    StringBuilder stringBuilder = new StringBuilder();\r
-    stringBuilder.append("BuildConfig.upLoadData=falsenetworkType=");\r
-    stringBuilder.append(paramInt1);\r
-    stringBuilder.append("flag=");\r
-    stringBuilder.append(paramInt2);\r
-    ICLogger.i(stringBuilder.toString());\r
-  }\r
-\r
-   public static boolean hasSimCard(Context context) {\r
-\r
-    TelephonyManager telMgr = (TelephonyManager)\r
-            context.getSystemService(Context.TELEPHONY_SERVICE);\r
-    int simState = telMgr.getSimState();\r
-    boolean result = true;\r
-    switch (simState) {\r
-      case TelephonyManager.SIM_STATE_ABSENT:\r
-        result = false; // 没有SIM卡\r
-        break;\r
-      case TelephonyManager.SIM_STATE_UNKNOWN:\r
-        result = false;\r
-        break;\r
-    }\r
-//    ICLogger.i( result ? "有SIM卡" : "无SIM卡");\r
-    return result;\r
-  }\r
-\r
-  public void changeNetWorkType(String paramString) {\r
-    Intent intent = new Intent("android.intent.action.NETWORK_MODE_CTRL");\r
-    intent.putExtra("mode", paramString);\r
-    this.context.sendBroadcast(intent);\r
-    StringBuilder stringBuilder = new StringBuilder();\r
-    stringBuilder.append("changeNetWorkType=");\r
-    stringBuilder.append(paramString);\r
-    ICLogger.i(stringBuilder.toString());\r
-  }\r
-\r
-  /**\r
-   * 检查用户的网络:是否有网络,所需权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>\r
-   */\r
-  public static boolean checkNet(Context context) {\r
-    // 判断:WIFI链接\r
-    boolean isWIFI = isWIFIConnection(context);\r
-    // 判断:Mobile链接\r
-    boolean isMOBILE = isMOBILEConnection(context);\r
-    if (!isWIFI && !isMOBILE) {\r
-      return false;//既不是手机连接,也不是wifi连接\r
-    }\r
-    return true;\r
-  }/**\r
-   * 判断:是否是手机链接\r
-   * @param context\r
-   * @return\r
-   */\r
-  private static boolean isMOBILEConnection(Context context) {\r
-    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\r
-    //获取连接的信息\r
-    NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);\r
-    if (networkInfo != null) {\r
-      return networkInfo.isConnected();\r
-    }\r
-    return false;\r
-  }\r
-\r
-  /**\r
-   * 判断:WIFI链接\r
-   *\r
-   * @param context\r
-   * @return\r
-   */\r
-  private static boolean isWIFIConnection(Context context) {\r
-    ConnectivityManager manager = (ConnectivityManager) context\r
-            .getSystemService(Context.CONNECTIVITY_SERVICE);\r
-\r
-    NetworkInfo networkInfo = manager\r
-            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);\r
-    if (networkInfo != null) {\r
-      return networkInfo.isConnected();\r
-    }\r
-    return false;\r
-  }\r
-  public int getNetworkType() {\r
-    init();\r
-    int networktype=IS_UNKNOWN;\r
-    switch (this.mNetworkType){\r
-\r
-      case NETWORK_TYPE_GPRS: //1\r
-      case NETWORK_TYPE_EDGE: //2\r
-     case NETWORK_TYPE_CDMA://4\r
-        networktype=IS_2G;\r
-        break;\r
-      case  NETWORK_TYPE_UMTS://3\r
-      case NETWORK_TYPE_HSDPA://8\r
-      case NETWORK_TYPE_EVDO_0: //5\r
-      case NETWORK_TYPE_EVDO_A: //6\r
-        networktype=IS_3G;\r
-        break;\r
-\r
-      case NETWORK_TYPE_LTE:\r
-        networktype=IS_4G;\r
-        break;\r
-\r
-      default:\r
-        networktype=IS_UNKNOWN;\r
-        break;\r
-    }\r
-\r
-    return networktype;\r
-  }\r
-  \r
-  public void init() {\r
-    this.mNetworkType = ((TelephonyManager)this.context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkType();\r
-  }\r
-\r
-  public static void SetRingMode(Context context,int mod,boolean vibmod){\r
-    AudioManager am= (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);\r
-    int currentRingmod=am.getRingerMode();\r
-    am.setRingerMode(mod);\r
-    ICLogger.i("Current OldRingMod="+currentRingmod+", Set To RingMod="+mod+", check RingMod="+am.getRingerMode());\r
-\r
-    int curretnVibmod=am.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);\r
-\r
-    if(vibmod){\r
-      Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING,1);\r
-      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);\r
-      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);\r
-    } else {\r
-      Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING,0);\r
-      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);\r
-      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);\r
-    }\r
-    ICLogger.i("Current OldVibRingMod="+curretnVibmod+", check VibRingMod="+am.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)+" , shoudl Vib "+am.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER));\r
-\r
-  }\r
-  public static boolean isScreenON(Context context) {\r
-      // If you use less than API20:\r
-      PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);\r
-      // If the screen is off then the device has been locked\r
-\r
-      boolean lisScreenOn;\r
-\r
-//      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {\r
-//\r
-//        lisScreenOn = powerManager.isInteractive();\r
-//\r
-//      } else {\r
-\r
-        lisScreenOn = powerManager.isScreenOn();\r
-\r
-//      }\r
-\r
-    return lisScreenOn;\r
-  }\r
-  public static void send_at_to_reset_simcard(Runtime runtime){\r
-\r
-    Intent intent = new Intent("com.eqc.intent.action.getTelephony.lbs");\r
-    intent.putExtra("command", "AT+SFUN=2"); //重新初始化sim卡\r
-    intent.putExtra("arg2", "");\r
-    ( runtime.getContextProxy()).context.sendBroadcast(intent);\r
-    ICLogger.i("send_at_to_reset_simcard ");\r
-  }\r
-\r
-  public static void send_at_to_update_lbs(Runtime runtime) {\r
-    Intent intent = new Intent("com.eqc.intent.action.getTelephony.lbs");\r
-    intent.putExtra("command", "AT+CREG=2");\r
-    intent.putExtra("arg2", "");\r
-    (runtime.getContextProxy()).context.sendBroadcast(intent);\r
-    ICLogger.i("send_at_to_update_lbs ");\r
-  }\r
-\r
-  public static void send_at_cmd(Runtime runtime, String cmd){\r
-    Intent intent = new Intent("com.eqc.intent.action.getTelephony.lbs");\r
-    intent.putExtra("command", cmd);\r
-    intent.putExtra("arg2", "");\r
-    ( runtime.getContextProxy()).context.sendBroadcast(intent);\r
-    ICLogger.i("send_at_cmd "+cmd);\r
-  }\r
-  public static void send_at_setImei0(Runtime runtime, String imei){\r
-    send_at_cmd(runtime,"AT+SPIMEI=0,"+imei);\r
-  }\r
-  public static void send_at_setImei1(Runtime runtime, String imei){\r
-    send_at_cmd(runtime,"AT+SPIMEI=1,"+imei);\r
-  }\r
-\r
-  public static void setAirMode(Context context,String paramString) {\r
-\r
-    final ContentResolver cr = context.getContentResolver();\r
-\r
-    ICLogger.i("setAirMode "+paramString);\r
-    if ("OpenAirplane".equals(paramString))\r
-    {\r
-      if (Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON).equals("0")) {\r
-        //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行\r
-        //如果关闭飞行,则打开飞行\r
-        Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "1");\r
-        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);\r
-        context.sendBroadcast(intent);\r
-      }\r
-    }else if ("CloseAirplane".equals(paramString)) {\r
-      if (Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON).equals("1")) {\r
-        //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行\r
-        //如果关闭飞行,则打开飞行\r
-        Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "0");\r
-        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);\r
-        context.sendBroadcast(intent);\r
-      }\r
-    }\r
-\r
-\r
-  }\r
-\r
-}\r
-\r
+package com.enqualcomm.support.utils;
+
+import android.app.Notification;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.display.DisplayManager;
+import android.media.AudioManager;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.Build;
+import android.os.PowerManager;
+import android.provider.Settings;
+import android.telephony.TelephonyManager;
+import android.view.Display;
+import com.enqualcomm.support.bean.Runtime;
+
+import static android.content.Context.POWER_SERVICE;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_CDMA;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_0;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_A;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_GPRS;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_HSDPA;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_LTE;
+import static android.telephony.TelephonyManager.NETWORK_TYPE_UMTS;
+
+public class SimSignalUtil {
+  public static final int IS_2G = 0;
+  
+  public static final int IS_3G = 1;
+  
+  public static final int IS_4G = 2;
+  
+  public static final int IS_UNKNOWN = -1;
+  
+  protected static SimSignalUtil simSignalUtil=null;
+  
+  Context context;
+  
+  int last_WorkType = -1;
+  
+  private int mNetworkType;
+  
+  int[] netWorkTypeArr = { 2, 2, 2, 2, 2 };
+  
+  private SimSignalUtil(Context paramContext) {
+    this.context = paramContext;
+    init();
+  }
+  
+  public synchronized static  SimSignalUtil getInstance(Context paramContext) {
+    if (simSignalUtil ==null)
+      simSignalUtil = new SimSignalUtil(paramContext);
+    return simSignalUtil;
+  }
+  public boolean IsAirModeOn() { return (Settings.System.getInt(this.context.getContentResolver(), "airplane_mode_on", 0) == 1); }
+  
+  public void changeNetWorkType(int paramInt1, int paramInt2) {
+    StringBuilder stringBuilder = new StringBuilder();
+    stringBuilder.append("BuildConfig.upLoadData=falsenetworkType=");
+    stringBuilder.append(paramInt1);
+    stringBuilder.append("flag=");
+    stringBuilder.append(paramInt2);
+    ICLogger.i(stringBuilder.toString());
+  }
+
+   public static boolean hasSimCard(Context context) {
+
+    TelephonyManager telMgr = (TelephonyManager)
+            context.getSystemService(Context.TELEPHONY_SERVICE);
+    int simState = telMgr.getSimState();
+    boolean result = true;
+    switch (simState) {
+      case TelephonyManager.SIM_STATE_ABSENT:
+        result = false; // 没有SIM卡
+        break;
+      case TelephonyManager.SIM_STATE_UNKNOWN:
+        result = false;
+        break;
+    }
+//    ICLogger.i( result ? "有SIM卡" : "无SIM卡");
+    return result;
+  }
+
+  public void changeNetWorkType(String paramString) {
+    Intent intent = new Intent("android.intent.action.NETWORK_MODE_CTRL");
+    intent.putExtra("mode", paramString);
+    this.context.sendBroadcast(intent);
+    StringBuilder stringBuilder = new StringBuilder();
+    stringBuilder.append("changeNetWorkType=");
+    stringBuilder.append(paramString);
+    ICLogger.i(stringBuilder.toString());
+  }
+
+  /**
+   * 检查用户的网络:是否有网络,所需权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+   */
+  public static boolean checkNet(Context context) {
+    // 判断:WIFI链接
+    boolean isWIFI = isWIFIConnection(context);
+    // 判断:Mobile链接
+    boolean isMOBILE = isMOBILEConnection(context);
+    if (!isWIFI && !isMOBILE) {
+      return false;//既不是手机连接,也不是wifi连接
+    }
+    return true;
+  }/**
+   * 判断:是否是手机链接
+   * @param context
+   * @return
+   */
+  private static boolean isMOBILEConnection(Context context) {
+    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+    //获取连接的信息
+    NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
+    if (networkInfo != null) {
+      return networkInfo.isConnected();
+    }
+    return false;
+  }
+
+  /**
+   * 判断:WIFI链接
+   *
+   * @param context
+   * @return
+   */
+  private static boolean isWIFIConnection(Context context) {
+    ConnectivityManager manager = (ConnectivityManager) context
+            .getSystemService(Context.CONNECTIVITY_SERVICE);
+
+    NetworkInfo networkInfo = manager
+            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+    if (networkInfo != null) {
+      return networkInfo.isConnected();
+    }
+    return false;
+  }
+  public int getNetworkType() {
+    init();
+    int networktype=IS_UNKNOWN;
+    switch (this.mNetworkType){
+
+      case NETWORK_TYPE_GPRS: //1
+      case NETWORK_TYPE_EDGE: //2
+     case NETWORK_TYPE_CDMA://4
+        networktype=IS_2G;
+        break;
+      case  NETWORK_TYPE_UMTS://3
+      case NETWORK_TYPE_HSDPA://8
+      case NETWORK_TYPE_EVDO_0: //5
+      case NETWORK_TYPE_EVDO_A: //6
+        networktype=IS_3G;
+        break;
+
+      case NETWORK_TYPE_LTE:
+        networktype=IS_4G;
+        break;
+
+      default:
+        networktype=IS_UNKNOWN;
+        break;
+    }
+
+    return networktype;
+  }
+  
+  public void init() {
+    this.mNetworkType = ((TelephonyManager)this.context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkType();
+  }
+
+  public static void SetRingMode(Context context,int mod,boolean vibmod){
+    AudioManager am= (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
+    int currentRingmod=am.getRingerMode();
+    am.setRingerMode(mod);
+    ICLogger.i("Current OldRingMod="+currentRingmod+", Set To RingMod="+mod+", check RingMod="+am.getRingerMode());
+
+    int curretnVibmod=am.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
+
+    if(vibmod){
+      Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING,1);
+      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
+      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
+    } else {
+      Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING,0);
+      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
+      am.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
+    }
+    ICLogger.i("Current OldVibRingMod="+curretnVibmod+", check VibRingMod="+am.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)+" , shoudl Vib "+am.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER));
+
+  }
+  public static boolean isScreenON(Context context) {
+      // If you use less than API20:
+      PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
+      // If the screen is off then the device has been locked
+
+      boolean lisScreenOn;
+
+//      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
+//
+//        lisScreenOn = powerManager.isInteractive();
+//
+//      } else {
+
+        lisScreenOn = powerManager.isScreenOn();
+
+//      }
+
+    return lisScreenOn;
+  }
+  public static void send_at_to_reset_simcard(Runtime runtime){
+
+    Intent intent = new Intent("com.eqc.intent.action.getTelephony.lbs");
+    intent.putExtra("command", "AT+SFUN=2"); //重新初始化sim卡
+    intent.putExtra("arg2", "");
+    ( runtime.getContextProxy()).context.sendBroadcast(intent);
+    ICLogger.i("send_at_to_reset_simcard ");
+  }
+
+  public static void send_at_to_update_lbs(Runtime runtime) {
+    Intent intent = new Intent("com.eqc.intent.action.getTelephony.lbs");
+    intent.putExtra("command", "AT+CREG=2");
+    intent.putExtra("arg2", "");
+    (runtime.getContextProxy()).context.sendBroadcast(intent);
+    ICLogger.i("send_at_to_update_lbs ");
+  }
+
+  public static void send_at_cmd(Runtime runtime, String cmd){
+    Intent intent = new Intent("com.eqc.intent.action.getTelephony.lbs");
+    intent.putExtra("command", cmd);
+    intent.putExtra("arg2", "");
+    ( runtime.getContextProxy()).context.sendBroadcast(intent);
+    ICLogger.i("send_at_cmd "+cmd);
+  }
+  public static void send_at_setImei0(Runtime runtime, String imei){
+    send_at_cmd(runtime,"AT+SPIMEI=0,"+imei);
+  }
+  public static void send_at_setImei1(Runtime runtime, String imei){
+    send_at_cmd(runtime,"AT+SPIMEI=1,"+imei);
+  }
+
+  public static void setAirMode(Context context,String paramString) {
+
+    final ContentResolver cr = context.getContentResolver();
+
+    ICLogger.i("setAirMode "+paramString);
+    if ("OpenAirplane".equals(paramString))
+    {
+
+        //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行
+        //如果关闭飞行,则打开飞行
+//      am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false
+   //   Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "1");
+      Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
+        intent.putExtra("state",true);
+        context.sendBroadcast(intent);
+
+    }else if ("CloseAirplane".equals(paramString)) {
+
+        //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行
+        //如果关闭飞行,则打开飞行
+   //     Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "0");
+        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
+        intent.putExtra("state",false);
+        context.sendBroadcast(intent);
+
+    }
+
+
+  }
+
+}
+
index 08b4c07..85f27af 100644 (file)
@@ -1,2 +1,2 @@
-#Fri Nov 20 22:05:05 CST 2020\r
-VERSION_CODE=714\r
+#Wed Nov 25 17:09:17 CST 2020
+VERSION_CODE=715