From: snickersun Date: Wed, 25 Nov 2020 09:11:49 +0000 (+0800) Subject: release 715 X-Git-Url: http://git.snicker.com.cn/Users/apple/Desktop/static/gitweb.css?a=commitdiff_plain;h=2c58566bf75daad55aa188d693458b1576ee813f;p=protocol_srv.git release 715 当网络长时间断开,或者服务器长时间无反应(12次没有响应),同时重置sim卡,重置4G网络。(原理只重置sim) --- diff --git a/app/release/ICSer_V714_2011202205_release.apk b/app/release/ICSer_V715_2011251709_release.apk similarity index 78% rename from app/release/ICSer_V714_2011202205_release.apk rename to app/release/ICSer_V715_2011251709_release.apk index 81209ef0..2a40b345 100644 Binary files a/app/release/ICSer_V714_2011202205_release.apk and b/app/release/ICSer_V715_2011251709_release.apk differ diff --git a/app/release/output.json b/app/release/output.json index 9f3d0601..d1040a24 100644 --- a/app/release/output.json +++ b/app/release/output.json @@ -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 diff --git a/app/src/main/java/com/enqualcomm/support/CoreService.java b/app/src/main/java/com/enqualcomm/support/CoreService.java index 8d552b62..4c747486 100644 --- a/app/src/main/java/com/enqualcomm/support/CoreService.java +++ b/app/src/main/java/com/enqualcomm/support/CoreService.java @@ -1,1660 +1,1661 @@ -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 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("check 发送心跳包时,如果发现服务器没有响应,或者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 contactArray=new ArrayList(); -// 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 contactArray=new ArrayList(); - 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 contactArray=new ArrayList(); -// 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() { -// 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 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.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(); - } - - -} +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 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 contactArray=new ArrayList(); +// 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 contactArray=new ArrayList(); + 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 contactArray=new ArrayList(); +// 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() { +// 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 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(); + } + + +} diff --git a/app/src/main/java/com/enqualcomm/support/ICSmsManager.java b/app/src/main/java/com/enqualcomm/support/ICSmsManager.java index f00f18ed..9faafc47 100644 --- a/app/src/main/java/com/enqualcomm/support/ICSmsManager.java +++ b/app/src/main/java/com/enqualcomm/support/ICSmsManager.java @@ -1,1279 +1,1281 @@ -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 contactArray=new ArrayList(); - 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.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); -*/ - - } - - } - } +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 contactArray=new ArrayList(); + 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 diff --git a/app/src/main/java/com/enqualcomm/support/utils/SimSignalUtil.java b/app/src/main/java/com/enqualcomm/support/utils/SimSignalUtil.java index 50ab9445..b1c469ba 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/SimSignalUtil.java +++ b/app/src/main/java/com/enqualcomm/support/utils/SimSignalUtil.java @@ -1,271 +1,274 @@ -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()); - } - - /** - * 检查用户的网络:是否有网络,所需权限: - */ - 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)) - { - if (Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON).equals("0")) { - //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行 - //如果关闭飞行,则打开飞行 - Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "1"); - Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); - context.sendBroadcast(intent); - } - }else if ("CloseAirplane".equals(paramString)) { - if (Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON).equals("1")) { - //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行 - //如果关闭飞行,则打开飞行 - Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "0"); - Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); - context.sendBroadcast(intent); - } - } - - - } - -} - +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()); + } + + /** + * 检查用户的网络:是否有网络,所需权限: + */ + 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); + + } + + + } + +} + diff --git a/app/version_code.properties b/app/version_code.properties index 08b4c07f..85f27af7 100644 --- a/app/version_code.properties +++ b/app/version_code.properties @@ -1,2 +1,2 @@ -#Fri Nov 20 22:05:05 CST 2020 -VERSION_CODE=714 +#Wed Nov 25 17:09:17 CST 2020 +VERSION_CODE=715