From: snickersun Date: Mon, 3 Feb 2020 00:25:26 +0000 (+0800) Subject: 1、为了尝试使用EqcIMessage,修改com.ic.protocol 为 com.enqualcomm.support,暂时还是只能用通讯录功能,微聊还不能用。 X-Git-Url: http://git.snicker.com.cn/sitemap.xml?a=commitdiff_plain;h=33fafa46e7a38ad4506006ec004530ef2ea1f456;p=icsupport.git 1、为了尝试使用EqcIMessage,修改com.ic.protocol 为 com.enqualcomm.support,暂时还是只能用通讯录功能,微聊还不能用。 2、添加协议AP07/BP07,BP28,协议收发的buffer已经完成,发还没有与实际文件关联,收还没有通知到ui 3、把Location发送改到Deliver中,采用Queue,但是目前偶尔会出现lock异常,占资源过多的情况。 4、修复心率测试后releasewakelock失败 5、修复MainActivity退出Launcher会crash的问题。 6、ICSer_V340_202002030355_debug.apk 发出作为调试 --- diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 65ffeaae..e11fe1ee 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -5,7 +5,7 @@ android:screenOrientation="portrait" android:supportsRtl="true" android:allowBackup="true" - package="com.ic.protocol"> + package="com.enqualcomm.support"> @@ -120,7 +120,7 @@ android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> - + @@ -128,17 +128,14 @@ - + - - - - + - + diff --git a/app/src/main/java/com/ic/protocol/service/protocolMainServer.java b/app/src/main/java/com/enqualcomm/support/CoreService.java similarity index 88% rename from app/src/main/java/com/ic/protocol/service/protocolMainServer.java rename to app/src/main/java/com/enqualcomm/support/CoreService.java index 8686e7ed..3e9b7aa8 100644 --- a/app/src/main/java/com/ic/protocol/service/protocolMainServer.java +++ b/app/src/main/java/com/enqualcomm/support/CoreService.java @@ -1,4 +1,4 @@ -package com.ic.protocol.service; +package com.enqualcomm.support; import android.annotation.SuppressLint; import android.app.AlarmManager; @@ -27,6 +27,14 @@ import com.ic.protocol.adapter.protocolAPIHelper; import com.ic.protocol.bean.Runtime; import com.ic.protocol.bean.StringMessage; import com.ic.protocol.bean.heartRateStatus; +import com.ic.protocol.service.CheckSIM; +import com.ic.protocol.service.Deliver; +import com.ic.protocol.service.HeartRateManager; +import com.ic.protocol.service.Initialize; +import com.ic.protocol.service.KeepAlive; +import com.ic.protocol.service.SendChatMessage; +import com.ic.protocol.service.SilentManager; +import com.ic.protocol.service.UpLoadDataPoints; import com.ic.protocol.service.base.AbstractConnectionService; import com.ic.protocol.service.base.AbstractInvokeHandlerService; import com.ic.protocol.utils.AlarmHelper; @@ -64,18 +72,21 @@ import static com.ic.protocol.Constants.ACTION_EQC_ALARM; import static com.ic.protocol.Constants.ACTION_HEATR_RATE_START; import static com.ic.protocol.Constants.ACTION_LOCATION_ALARM; import static com.ic.protocol.Constants.HEART_ALARM; +import static com.ic.protocol.Constants.KEY_SAVE_STEP_COUNT; +import static com.ic.protocol.Constants.KEY_STEP_COUNT; import static com.ic.protocol.Constants.SLEEP_ALARM; +import static com.ic.protocol.Constants.STEP_COUNT_ALARM_ACTION; import static com.ic.protocol.Constants.WAKE_ALARM; import static com.ic.protocol.Constants.WEATHER_ALARM; import static com.ic.protocol.bean.ICLocation.*; -public class protocolMainServer extends Service { +public class CoreService extends Service { private Toastc toast = null; - private static protocolMainServer mProtocolServer=null; + private static CoreService mProtocolServer=null; private static LBSHelper lbshelper=null; public static final String ACTION_ALARM = "com.enqualcomm.support.ACTION_ALARM"; @@ -118,7 +129,7 @@ public class protocolMainServer extends Service { if (arrayOfString.length > 4) { str = arrayOfString[1]; String str1 = arrayOfString[3]; - Context context = (protocolMainServer.this.runtime.getContextProxy()).context; + Context context = (CoreService.this.runtime.getContextProxy()).context; StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.append("AT lbsInfo LAC== "); stringBuilder1.append(Integer.valueOf(str, 16)); @@ -141,28 +152,27 @@ public class protocolMainServer extends Service { stringBuilder1.append("时间变化"); stringBuilder1.append(param1Intent.getAction()); Logger.i(stringBuilder1.toString()); - protocolMainServer.this.setSleepAlarm(); - protocolMainServer.this.setWakeAlarm(); - protocolMainServer.this.setHeartAlarm(); - protocolMainServer.this.setHeartRateDetectAlarm(3); - protocolMainServer.this.setWeatherAlarm(); - protocolMainServer.this.setLocationAlarm(runtime.getLocationInstance().getWorkingMod()); - if (protocolMainServer.this.cmcm_call_eiot_into_powersave_mode() == 0) - AlarmWakeUp.isNeedWakeUpAlarm(protocolMainServer.this.runtime); + CoreService.this.setSleepAlarm(); + CoreService.this.setWakeAlarm(); + CoreService.this.setHeartAlarm(); + CoreService.this.setHeartRateDetectAlarm(3); + CoreService.this.setWeatherAlarm(); + CoreService.this.setLocationAlarm(runtime.getLocationInstance().getWorkingMod()); + if (CoreService.this.cmcm_call_eiot_into_powersave_mode() == 0) + AlarmWakeUp.isNeedWakeUpAlarm(CoreService.this.runtime); } }; private static class ServerHandler implements ConnectionListener { - private final WeakReference mReference; + private final WeakReference mReference; - ServerHandler(protocolMainServer param1CoreService) { this.mReference = new WeakReference(param1CoreService); } + ServerHandler(CoreService param1CoreService) { this.mReference = new WeakReference(param1CoreService); } public void onConnectionClose() { - protocolMainServer coreService = (protocolMainServer)this.mReference.get(); + CoreService coreService = (CoreService)this.mReference.get(); if (coreService == null) return; Logger.i("onConnectionClose++ retry to connect again!"); - // startConnectionRetryTimer(); String ip=Util.parseHostGetIPAddress(coreService.runtime.getHost()); if ( ip !=null && ! ip.equals(coreService.runtime.getSrvIP())){ @@ -173,7 +183,7 @@ public class protocolMainServer extends Service { } public void onConnectionOpen() { - protocolMainServer coreService = (protocolMainServer)this.mReference.get(); + CoreService coreService = (CoreService)this.mReference.get(); if (coreService == null) return; coreService.connectionServiceChain.processConnectionOpen(coreService.connection, coreService.runtime); @@ -182,7 +192,7 @@ public class protocolMainServer extends Service { public void onReceive(StringMessage param1StringMessage) { - protocolMainServer coreService = (protocolMainServer)this.mReference.get(); + CoreService coreService = (CoreService)this.mReference.get(); Logger.i("onReceive " +param1StringMessage.cmd() +" coreService " + coreService ); if (coreService == null) return; @@ -226,22 +236,22 @@ public class protocolMainServer extends Service { if (is_in_sleep_mode) { /*屏幕亮起时,如果在sleep模式,则唤醒各个进程*/ - protocolMainServer.is_in_sleep_mode=false; - protocolMainServer.is_allowed_in_sleep_mode=0; - if (protocolMainServer.this.mKeepAlive != null) - protocolMainServer.this.mKeepAlive.setSleepMode(false); - protocolMainServer.this.wakeUpFromSleep(); + 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(); } if (is_wifi_network_ok) { /*屏幕亮起时,如果wifi开启,则开启wifi*/ - protocolMainServer.is_in_sleep_mode=false; - Util.turnOnWifiForConnect((protocolMainServer.this.runtime.getContextProxy()).context, protocolMainServer.this.runtime); + CoreService.is_in_sleep_mode=false; + Util.turnOnWifiForConnect((CoreService.this.runtime.getContextProxy()).context, CoreService.this.runtime); } - } else if ("android.intent.action.SCREEN_OFF".equals(param1Intent.getAction()) && Util.isWifiIsOpen((protocolMainServer.this.runtime.getContextProxy()).context, protocolMainServer.this.runtime)) { + } else if ("android.intent.action.SCREEN_OFF".equals(param1Intent.getAction()) && Util.isWifiIsOpen((CoreService.this.runtime.getContextProxy()).context, CoreService.this.runtime)) { - protocolMainServer.is_in_sleep_mode=true; - Util.turnOffWifiForSleep((protocolMainServer.this.runtime.getContextProxy()).context, protocolMainServer.this.runtime); + CoreService.is_in_sleep_mode=true; + Util.turnOffWifiForSleep((CoreService.this.runtime.getContextProxy()).context, CoreService.this.runtime); } } }; @@ -255,7 +265,7 @@ public class protocolMainServer extends Service { Initialize initialize = new Initialize(); CheckSIM checkSIM = new CheckSIM(); this.mKeepAlive = new KeepAlive(); - this.mDeliver = new Deliver(); + this.mDeliver = new Deliver(this.connection,this.runtime); initialize.setNext(checkSIM); checkSIM.setNext(this.mKeepAlive); this.mKeepAlive.setNext(this.mDeliver); @@ -282,15 +292,15 @@ public class protocolMainServer extends Service { private void loadStepCount() { - int i = SharPreferenceUtil.getPrefInt(this, "KEY_STEP_COUNT", 0); - int j = SharPreferenceUtil.getPrefInt(this, "key_save_step_count", 0); + int i = SharPreferenceUtil.getPrefInt(this, KEY_STEP_COUNT, 0); + int j = SharPreferenceUtil.getPrefInt(this, KEY_SAVE_STEP_COUNT, 0); this.runtime.setSaveStepCount(j); this.runtime.setTotalStepCount(i); } private void setCleanStepCountAlarm() { /*一天清零一次 计步*/ - AlarmHelper.setCleanStepCountAlarm(this, 23, 59, "com.enqualcomm.support.ACTION_STEP_COUNT_ALARM"); + AlarmHelper.setCleanStepCountAlarm(this, 23, 59, STEP_COUNT_ALARM_ACTION); } private void setSleepAlarm() { @@ -303,7 +313,7 @@ public class protocolMainServer extends Service { // /*每1 左右 唤醒自己*/ // Context context=runtime.getContextProxy().context; // AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); -// Intent intent = new Intent(context, com.ic.protocol.service.protocolMainServer.class); +// 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); @@ -333,7 +343,7 @@ public class protocolMainServer extends Service { } private void wakeUpFromSleep() { this.startAlarmCount = 0; -// alarmCycle = 1; + alarmCycle = 1; setAlarm(alarmCycle); this.runtime.getContextProxy().sendBroadcast(ACTION_EQC_ALARM, this.runtime); this.connection.open(); @@ -352,7 +362,7 @@ public class protocolMainServer extends Service { public PowerManager.WakeLock getWakeLock(int paramInt) { - PowerManager.WakeLock wakeLock = ((PowerManager)(this.runtime.getContextProxy()).context.getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag"); + 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; @@ -370,8 +380,8 @@ public class protocolMainServer extends Service { @Override public void onCreate() { - Logger.i("CoreService--onCreate002"); - log("开始监听网络协议状态"); +// Logger.i("CoreService--onCreate002"); + log("初始化网络协议服务"); mProtocolServer=this; this.runtime = new Runtime(); @@ -382,6 +392,7 @@ public class protocolMainServer extends Service { this.runtime.setLbsHelper(new LBSHelper(this,this.runtime.getContextProxy().getWifiManager(), this.runtime)); this.runtime.setImeiAndCid(PhoneUtils.getIMEI(this),""); this.runtime.setHRS(new heartRateStatus()); + this.runtime.setUseQueue(true); this.connectionServiceChain = getConnectionServiceChain(); this.invokeHandlerServiceChain = getInvokeHandlerServiceChain(); if (cmcm_call_eiot_into_powersave_mode() == 1) { @@ -636,6 +647,9 @@ public class protocolMainServer extends Service { case LOWPOWER_MOD: cycle=60; break; + case CUSTOM_MOD: + cycle=runtime.getLocationInstance().getLocation_cycle(); + break; } AlarmHelper.setRealTimeAlarm(runtime.getContextProxy().context,cycle, ACTION_LOCATION_ALARM); @@ -674,7 +688,7 @@ public class protocolMainServer extends Service { public void setUpLocationDataAlarm(long paramLong) { AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); - Intent intent = new Intent(this, protocolMainServer.class); + 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); @@ -699,14 +713,14 @@ public class protocolMainServer extends Service { } private static class RequestHandler extends Handler { - private final WeakReference mReference; + private final WeakReference mReference; - RequestHandler(protocolMainServer param1CoreService) { + RequestHandler(CoreService param1CoreService) { this.mReference = new WeakReference(param1CoreService); } public void handleMessage(Message param1Message) { - protocolMainServer coreService = (protocolMainServer)this.mReference.get(); + CoreService coreService = (CoreService)this.mReference.get(); if (coreService == null) return; coreService.invokeHandlerServiceChain.processUserRequest(param1Message, coreService.connection, coreService.runtime); @@ -719,7 +733,7 @@ public class protocolMainServer extends Service { } - private static final String TAG = "ICSrv." + protocolMainServer.class.getSimpleName(); + private static final String TAG = "ICSrv." + CoreService.class.getSimpleName(); private static boolean mLowPowerMode = false; private static boolean mCallStateIsIdle = true; // 非通话活动 @@ -739,7 +753,7 @@ public class protocolMainServer extends Service { Logger.log(TAG,funcName,msg); } - public static protocolMainServer getInstance(){ + public static CoreService getInstance(){ return mProtocolServer; } @@ -789,8 +803,8 @@ public class protocolMainServer extends Service { 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); + SharPreferenceUtil.setPrefInt(this, KEY_STEP_COUNT, i); + SharPreferenceUtil.setPrefInt(this, KEY_SAVE_STEP_COUNT, j); } @Override public void onDestroy() { diff --git a/app/src/main/java/com/ic/protocol/BootCompleteReceiver.java b/app/src/main/java/com/ic/protocol/BootCompleteReceiver.java index 3a3b621f..2d62be3d 100644 --- a/app/src/main/java/com/ic/protocol/BootCompleteReceiver.java +++ b/app/src/main/java/com/ic/protocol/BootCompleteReceiver.java @@ -9,7 +9,7 @@ import com.ic.protocol.utils.Logger; public class BootCompleteReceiver extends BroadcastReceiver { public void onReceive(Context paramContext, Intent paramIntent) { Logger.i("监听到开机广播"); - paramContext.startService(new Intent(paramContext, com.ic.protocol.service.protocolMainServer.class)); + paramContext.startService(new Intent(paramContext, com.enqualcomm.support.CoreService.class)); } } diff --git a/app/src/main/java/com/ic/protocol/Config.java b/app/src/main/java/com/ic/protocol/Config.java index 5c534a69..6b9a326c 100644 --- a/app/src/main/java/com/ic/protocol/Config.java +++ b/app/src/main/java/com/ic/protocol/Config.java @@ -177,7 +177,81 @@ public class Config { private static String make() { try { - return (new JSONStringer()).object().key("cmd").value("Init").key("sw_version").value("eiot_V1.0.0").key("protocol_version").value("2.0").key("product").value(2L).key("sim").value(1L).key("connect").value(1L).key("work_mode").value(work_mode).key("phonebook").value(1L).key("wifi").value(2L).key("pedometer").value(1L).key("wechat").value(1L).key("shake").value(1L).key("antioff").value(antioff).key("key_num").value(1L).key("kindness_num").value(0L).key("sos_num").value(0L).key("monitor_num").value(0L).key("other_contact_num").value(30L).key("volume").value(0L).key("ring_vol").value(2L).key("call_vol").value(2L).key("Schedule_powonoff").value(0L).key("temperature").value(0L).key("air_pressure").value(0L).key("dampness").value(0L).key("BT").value("1@4.0").key("TP").value(1L).key("camera").value("1@200").key("T_Card").value(0L).key("NFC").value(0L).key("wireless_charge").value(0L).key("geomagnetic").value(0L).key("gyroscope").value(0L).key("behavior_mode").value(0L).key("LBS").value(1L).key("monitor").value(1L).key("check_bill").value(1L).key("sndrec").value(0L).key("voice_control").value(0L).key("market").value("domestic").key("platform").value("SC9820E").key("LCD").value("OLED@240X206").key("communication_standard").value(1L).key("time_set").value(0L).key("language").value("0@0").key("mcc_mnc").value("46000").key("end_call").value(0L).key("multi_point").value(0L).key("make_call").value(1L).key("search_terminal").value(1L).key("alarm").value(1L).key("silent").value(1L).key("weather").value(1L).key("url_download").value(1L).key("shutdown_hand").value(1L).key("relation").value(0L).key("voice_notice").value(1L).key("q_a").value(1L).key("gps").value(1L).key("gsensor").value(1L).key("reboot").value(1L).key("relatives").value(1L).key("heart_rate").value(heart_rate).key("sedentary_reminder").value(0L).key("fight_mode").value(0L).key("sleep_monitor").value(0L).key("sms_forward").value(0L).key("video_jf").value(1L).key("nickname").value(0L).key("wifi_setting").value(1L).key("yunosuuid").value(0L).key("oss_file").value(0L).key("swReleaseNo").value(sw_release_no).endObject().toString(); + return (new JSONStringer()).object() + .key("cmd").value("Init") + .key("sw_version").value("eiot_V1.0.0") + .key("protocol_version").value("2.0") + .key("product").value(2L) + .key("sim").value(1L) + .key("connect").value(1L) + .key("work_mode").value(work_mode) + .key("phonebook").value(1L) + .key("wifi").value(2L) + .key("pedometer").value(1L) + .key("wechat").value(1L) + .key("shake").value(1L) + .key("antioff").value(antioff) + .key("key_num").value(1L) + .key("kindness_num").value(0L) + .key("sos_num").value(0L) + .key("monitor_num").value(0L) + .key("other_contact_num").value(30L) + .key("volume").value(0L) + .key("ring_vol").value(2L) + .key("call_vol").value(2L) + .key("Schedule_powonoff").value(0L) + .key("temperature").value(0L) + .key("air_pressure").value(0L) + .key("dampness").value(0L) + .key("BT").value("1@4.0") + .key("TP").value(1L) + .key("camera").value("1@200") + .key("T_Card").value(0L) + .key("NFC").value(0L) + .key("wireless_charge").value(0L) + .key("geomagnetic").value(0L) + .key("gyroscope").value(0L) + .key("behavior_mode").value(0L) + .key("LBS").value(1L) + .key("monitor").value(1L) + .key("check_bill").value(1L) + .key("sndrec").value(0L) + .key("voice_control").value(0L) + .key("market").value("domestic") + .key("platform").value("SC9820E") + .key("LCD").value("OLED@240X206") + .key("communication_standard").value(1L) + .key("time_set").value(0L) + .key("language").value("0@0") + .key("mcc_mnc").value("46000") + .key("end_call").value(0L) + .key("multi_point").value(0L) + .key("make_call").value(1L) + .key("search_terminal").value(1L) + .key("alarm").value(1L) + .key("silent").value(1L) + .key("weather").value(1L) + .key("url_download").value(1L) + .key("shutdown_hand").value(1L) + .key("relation").value(0L) + .key("voice_notice").value(1L) + .key("q_a").value(1L) + .key("gps").value(1L) + .key("gsensor").value(1L) + .key("reboot").value(1L) + .key("relatives").value(1L) + .key("heart_rate").value(heart_rate) + .key("sedentary_reminder").value(0L) + .key("fight_mode").value(0L) + .key("sleep_monitor").value(0L) + .key("sms_forward").value(0L) + .key("video_jf").value(1L) + .key("nickname").value(0L) + .key("wifi_setting").value(1L) + .key("yunosuuid").value(0L) + .key("oss_file").value(0L) + .key("swReleaseNo").value(sw_release_no) + .endObject().toString(); } catch (JSONException jSONException) { jSONException.printStackTrace(); return ""; diff --git a/app/src/main/java/com/ic/protocol/CrashHandler.java b/app/src/main/java/com/ic/protocol/CrashHandler.java index 050bd28f..e60e5b77 100644 --- a/app/src/main/java/com/ic/protocol/CrashHandler.java +++ b/app/src/main/java/com/ic/protocol/CrashHandler.java @@ -9,6 +9,8 @@ import android.os.Looper; import android.util.Log; import android.widget.Toast; +import com.enqualcomm.support.R; + import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; @@ -190,9 +192,9 @@ public class CrashHandler implements Thread.UncaughtExceptionHandler { sb.append("\n\n"); try { - String fileName = "EqcLauncher-" + dateFormatDate.format(new Date()) + ".log"; - if (Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED)) { + String fileName = "ICProtocol-" + dateFormatDate.format(new Date()) + ".log"; +// if (Environment.getExternalStorageState().equals( +// Environment.MEDIA_MOUNTED)) { File dir = new File(Environment.getExternalStorageDirectory().getPath(), "crash"); String path = dir.getPath(); if (!dir.exists()) { @@ -201,7 +203,7 @@ public class CrashHandler implements Thread.UncaughtExceptionHandler { FileOutputStream fos = new FileOutputStream(new File(path, fileName), true); fos.write(sb.toString().getBytes()); fos.close(); - } +// } return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...," + e); diff --git a/app/src/main/java/com/ic/protocol/GSensorListener.java b/app/src/main/java/com/ic/protocol/GSensorListener.java index 17c1c1d6..3d66a101 100644 --- a/app/src/main/java/com/ic/protocol/GSensorListener.java +++ b/app/src/main/java/com/ic/protocol/GSensorListener.java @@ -1,196 +1,55 @@ package com.ic.protocol; -import android.content.Context; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; + import android.os.Handler; import android.os.Message; -import android.os.PowerManager; import com.ic.jni.ICJniUtils; import com.ic.protocol.bean.Runtime; -import com.ic.protocol.service.protocolMainServer; -import com.ic.protocol.utils.CellInfoUtil; + import com.ic.protocol.utils.FileOutputUtil; import com.ic.protocol.utils.Logger; -import java.util.Timer; -import java.util.TimerTask; +/** + * 由于Gsensor用的硬件计步,只需要保证打开计步器即可 + */ +public class GSensorListener { -public class GSensorListener implements SensorEventListener { - private static final String MY_WAKE_LOCKTAG = "MyWakelockTag_GSensorListener"; public static boolean getStepCountOver = false; private int CURRENT_STEP; - private int anti_off; - - private int haveAddAntiOffCount = -1; - - private boolean isFirstSendAntiOff = true; - - boolean isReceivedFirstValue; - - private Context mContext; - Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what != 100) - return; - GSensorListener.this.sensorManager.unregisterListener(GSensorListener.this); - int i = ICJniUtils.getStepCount();//EqcAlgorithmNative.native_EqcAlgorithm_Gsensor_get_step(); -// GSensorListener (GSensorListener.this, i); - GSensorListener.this.CURRENT_STEP = i; - + return; + GSensorListener.this.CURRENT_STEP = ICJniUtils.getStepCount(); StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.append("CURRENT_STEP ="); stringBuilder1.append(GSensorListener.this.CURRENT_STEP); Logger.i(stringBuilder1.toString()); - GSensorListener.this.sendAntiOff(GSensorListener.this.CURRENT_STEP); -// GSensorListener.access$302(GSensorListener.this, 0); -// GSensorListener.getStepCountOver=false; -// EqcAlgorithmNative.native_EqcAlgorithmMethod6(0.0F, 0.0F, 0.0F, GSensorListener.this.CURRENT_STEP); - Context context = GSensorListener.this.mContext; - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(), "CURRENT_STEP", stringBuilder1.toString()); -// GSensorListener.access$502(GSensorListener.this, null); - GSensorListener.this.releaseWakeLock(GSensorListener.this.mWakeLock); + runtime.setTotalStepCount(CURRENT_STEP); + GSensorListener.getStepCountOver=false; + FileOutputUtil.fileOutput(runtime.getCacheDir(), "CURRENT_STEP", stringBuilder1.toString()); } }; + + private Runtime runtime; - private TimerTask mMyTimerTask; - - private Timer mTimer; - - private PowerManager.WakeLock mWakeLock; - - private SensorManager sensorManager; - - static { - - } - - public GSensorListener(SensorManager paramSensorManager, Context context, Runtime dev) { - this.sensorManager = paramSensorManager; - this.mContext = context; + public GSensorListener( Runtime dev) { + this.runtime = dev; ICJniUtils.enablePedometer(); } - - private void releaseWakeLock(PowerManager.WakeLock paramWakeLock) { - if (paramWakeLock == null) { - Logger.i("Gsensor 没有加锁"); - return; - } - - if (CellInfoUtil.getCellInfoOver) { - if (paramWakeLock.isHeld()) { - CellInfoUtil.getCellInfoOver = false; - getStepCountOver = false; - paramWakeLock.release(); - return; - } - } else { - getStepCountOver = true; - } + public void updateStepCount(){ + getStepCountOver=true; + mHandler.sendEmptyMessage(100); } - - private void sendAntiOff(int paramInt) {} - public int getStepCount() { - this.CURRENT_STEP=ICJniUtils.getStepCount(); return this.CURRENT_STEP; - } - - public PowerManager.WakeLock getWakeLock() { - PowerManager.WakeLock wakeLock = ((PowerManager)this.mContext.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag_GSensorListener"); - wakeLock.acquire(60000L); - return wakeLock; - } - - public void onAccuracyChanged(Sensor paramSensor, int paramInt) {} - - public void onSensorChanged(SensorEvent paramSensorEvent) { - int currentStepCount; - try { - float f = paramSensorEvent.values[0]; - currentStepCount = (int)f; - } catch (Exception e) { - e.printStackTrace(); - Logger.i("Exception"); - currentStepCount = 0; - } - StringBuilder stringBuilder1 = new StringBuilder(); - stringBuilder1.append("count ="); - stringBuilder1.append(currentStepCount); - Logger.i(stringBuilder1.toString()); - int step = ICJniUtils.getStepCount();//EqcAlgorithmNative.native_EqcAlgorithm_Gsensor_get_step(); - if (step == this.CURRENT_STEP && !this.isReceivedFirstValue) { - this.isReceivedFirstValue = true; - return; - } - if (this.mTimer != null) { - this.mTimer.cancel(); - this.mTimer.purge(); - this.mTimer = null; - } -// sendAntiOff(i); - this.haveAddAntiOffCount = 0; - this.CURRENT_STEP = step; -// EqcAlgorithmNative.native_EqcAlgorithmMethod6(0.0F, 0.0F, 0.0F, this.CURRENT_STEP); - - Context context = this.mContext; - StringBuilder stringBuilder2 = new StringBuilder(); - stringBuilder2.append("CURRENT_STEP="); - stringBuilder2.append(this.CURRENT_STEP); - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(), "CURRENT_STEP", stringBuilder2.toString()); - this.sensorManager.unregisterListener(this); - releaseWakeLock(this.mWakeLock); - } - - public void startListen(PowerManager.WakeLock paramWakeLock) { - this.mWakeLock = paramWakeLock; - if (this.haveAddAntiOffCount == 1) - sendAntiOff(this.CURRENT_STEP); - this.haveAddAntiOffCount = 1; - this.isReceivedFirstValue = false; - (new Thread(new Runnable() { - public void run() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("registerListener sensorManager="); - stringBuilder.append(GSensorListener.this.sensorManager); - Logger.i(stringBuilder.toString()); - GSensorListener.this.sensorManager.registerListener(GSensorListener.this, GSensorListener.this.sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), 0); - } - })).start(); - if (this.mTimer == null) - this.mTimer = new Timer(); - if (this.mMyTimerTask != null) - this.mMyTimerTask.cancel(); - class MyTimerTask extends TimerTask { - public void run() { - //发送读取计步消息 - GSensorListener.this.mHandler.sendEmptyMessage(100); - } - }; - this.mMyTimerTask = new MyTimerTask(); - //延时2秒执行发送“读取计步”消息 - this.mTimer.schedule(this.mMyTimerTask, 2000L); - } - - public void stopListen() { - this.sensorManager.unregisterListener(this); - if (this.mTimer != null) { - this.mTimer.cancel(); - this.mTimer.purge(); - this.mTimer = null; - } - releaseWakeLock(this.mWakeLock); - } } diff --git a/app/src/main/java/com/ic/protocol/ICApplication.java b/app/src/main/java/com/ic/protocol/ICApplication.java index 3c4e37b8..e4101eb7 100644 --- a/app/src/main/java/com/ic/protocol/ICApplication.java +++ b/app/src/main/java/com/ic/protocol/ICApplication.java @@ -9,6 +9,8 @@ import android.util.Log; import android.util.SparseArray; +import com.enqualcomm.support.BuildConfig; + import java.util.HashMap; diff --git a/app/src/main/java/com/ic/protocol/LocationClient.java b/app/src/main/java/com/ic/protocol/LocationClient.java index b1f506fa..6c42132c 100644 --- a/app/src/main/java/com/ic/protocol/LocationClient.java +++ b/app/src/main/java/com/ic/protocol/LocationClient.java @@ -17,13 +17,14 @@ import com.ic.protocol.bean.ICLocation; import com.ic.protocol.bean.StringMessage; import com.ic.protocol.service.Deliver; import com.ic.protocol.service.KeepAlive; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; import com.ic.protocol.utils.CellInfoUtil; import com.ic.protocol.utils.DeviceInfoUtil; import com.ic.protocol.utils.FileCache; import com.ic.protocol.utils.FileOutputUtil; import com.ic.protocol.utils.Logger; import com.ic.protocol.utils.NettyConnection; +import com.ic.protocol.utils.ServiceUtil; import com.ic.protocol.utils.SharPreferenceUtil; import com.ic.protocol.utils.SimSignalUtil; import com.ic.protocol.bean.Runtime; @@ -60,30 +61,29 @@ public class LocationClient { public static final String LOCATION_CYCLE = "location_cycle"; public static final String LOCATION_MODE = "location_mode"; - + private static final int MAX_SIZE = 50; private static final int OPEN_AIRMODE = 1; private static final int TIME_OUT = 30000; - + private static NettyConnection connection; - - private static FileCache fileCache; + + private static boolean isLocationCallBack = false; - + private static boolean linkOK = false; - private static ReentrantLock lock = new ReentrantLock(); + private static boolean mHasWifiResult = true; - public static LinkedBlockingDeque queue = new LinkedBlockingDeque(50); - + private static Runtime runtime; - private int H12StepCount; +// private int H12StepCount; private boolean batteryLowNotification; @@ -101,10 +101,7 @@ public class LocationClient { private String mCellInfo; - ReentrantLock mLock = new ReentrantLock(); - Condition mCondition = this.mLock.newCondition(); - private LBSHelper mLbsHelper; private Timer mTimer=null; @@ -112,9 +109,7 @@ public class LocationClient { private int mPedometer2; private SimSignalUtil mSignalUtil; - - private String mWifiInfo; - + private NMEAListener nmeaListener; private int preLbsCid; @@ -125,34 +120,21 @@ public class LocationClient { public void onReceive(Context param1Context, Intent param1Intent) { if ("android.intent.action.SCREEN_ON".equals(param1Intent.getAction())) { LocationClient.this.mSignalUtil.setAirMode("CloseAirplane"); -// EqcAlgorithmNative.native_EqcAlgorithmMethod8(0); - } + } } }; public LocationClient(NettyConnection paramNettyConnection, Runtime paramRuntime) { connection = paramNettyConnection; runtime = paramRuntime; - fileCache = new FileCache(paramRuntime.getFileDir()); + + //GPS 监听管理初始化 this.nmeaListener = new NMEAListener(paramRuntime.getContextProxy().getLocationManager(), paramRuntime); - this.gSensorListener = new GSensorListener(paramRuntime.getContextProxy().getSensorManager(), (paramRuntime.getContextProxy()).context, paramRuntime); + // 初始化同时开启计步(硬件计步器,比较省电,全程开启计步功能) + this.gSensorListener = new GSensorListener(paramRuntime); } - - private static int getMinSignalStrength(int paramInt) { - int b = -105; - switch (paramInt) { - case SimSignalUtil.IS_4G: - b = -100; - break; - case SimSignalUtil.IS_2G: - case SimSignalUtil.IS_3G: - default: - break; - } - return b; - } - + private void handler2GTo4G() { int networktype = this.mSignalUtil.getNetworkType(); int singal = runtime.getSignalStrength(); @@ -173,88 +155,38 @@ public class LocationClient { this.mSignalUtil.changeNetWorkType("2G"); this.haveChanegTo4GTime = currenttime; return; - } + } return; case SimSignalUtil.IS_2G: case SimSignalUtil.IS_3G: break; - } + } if (this.haveChanegTo4G || currenttime - this.haveChanegTo4GTime > 43200000L) { this.mSignalUtil.changeNetWorkType("4G"); this.haveChanegTo4G = false; this.haveChanegTo4GTime = currenttime; - } + } } //计算运动并发送数据 private void updateStepCount() { - int i = this.gSensorListener.getStepCount(); - runtime.setTotalStepCount(i); - this.H12StepCount = DeviceInfoUtil.getStepCount((runtime.getContextProxy()).context); - if (i != 0 && Math.abs(this.H12StepCount - this.mPedometer2) > 1000) { -// connection.send(API.H12(runtime, this.H12StepCount)); - Logger.i("StepCount 运动开始后 变化超过1000 ,则发送给服务器!"); - } - } + this.gSensorListener.updateStepCount(); +// this.H12StepCount = DeviceInfoUtil.getStepCount((runtime.getContextProxy()).context); +// if (i != 0 && Math.abs(this.H12StepCount - this.mPedometer2) > 1000) { +//// connection.send(API.H12(runtime, this.H12StepCount)); +// Logger.i("StepCount 运动开始后 变化超过1000 ,则发送给服务器!"); +// } - private static void loadMessage2Queue() { - byte b = 0; - while (b < 5) { - String str = fileCache.load(); - if (str != null) { - byte b1 = ++b; - try { - StringMessage stringMessage = new StringMessage(str); - if (!queue.offerLast(stringMessage)) { - fileCache.put(str); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } } - - private void notifiSetAirModeMethod() { (new Thread(new Runnable() { - public void run() { - SystemClock.sleep(3000L); - boolean bool = LocationClient.this.mSignalUtil.IsAirModeOn(); - byte b = 1; - if (bool != true) - b = 0; - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("AirMode=="); - stringBuilder.append(b); - Logger.i(stringBuilder.toString()); -// EqcAlgorithmNative.native_EqcAlgorithmMethod8(b); - } - })).start(); } - + + private void performAlarm(PowerManager.WakeLock paramWakeLock) { if (!runtime.isAirMode) { - CellInfoUtil.triggerUpdateCellinfo(); - sendBatteryNotification(); -// startLocationProcess(); + updateStepCount();//update StepCount + CellInfoUtil.triggerUpdateCellinfo(); + sendBatteryNotification(); } } - - private void sendBatteryNotification() { - if (runtime.getHaveBatteryChange() && !runtime.getBatterychanging() && !this.batteryNotification) { -// connection.send(API.H05(runtime, "2")); - Logger.i("sendBatteryNotification LevelChanged "); - this.batteryNotification = true; - } - if (runtime.getBatteryLow() && !runtime.getBatterychanging() && !this.batteryLowNotification) { -// connection.send(API.H05(runtime, "1")); - Logger.i("sendBatteryNotification Low Battery "); - this.batteryLowNotification = true; - } - if (runtime.getBatterychanging()) { - this.batteryNotification = false; - this.batteryLowNotification = false; - } - } - public void triggerLocationProcess(){ mhandler.sendEmptyMessage(0); } @@ -266,17 +198,14 @@ public class LocationClient { public void startWifiScan(){ Logger.i("开启wifi扫描"); -// runtime.currentWifiInfo = ""; runtime.setWifiinfo(""); mHasWifiResult = false; this.mLbsHelper.registerBroadReceiver(); this.mLbsHelper.getWifiInfo(); this.mLbsHelper.setOnWiFiInfoListener(new LBSHelper.OnWiFiInfoListener() { public void getWifiInfoCallBack(String param1String) { -// LocationClient.access$002(true); Logger.i("get wifi scan Callback " + param1String); LocationClient.mHasWifiResult=true; -// runtime.currentWifiInfo = param1String==null?"":param1String; runtime.setWifiinfo(param1String==null?"":param1String); } }); @@ -289,10 +218,6 @@ public class LocationClient { public void call(Object param1Object) { LocationClient.this.nmeaListener.startListen(); } }); -// Single.just(null).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1() { -// public void call(Object param1Object) { LocationClient.this.waitAndSendLocation(); } -// }); - } public void startCheckResult(){ @@ -313,7 +238,9 @@ public class LocationClient { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 100){ - waitAndSendLocation(); + Single.just(null).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1() { + public void call(Object param1Object) { LocationClient.this.waitAndSendLocation(); } + }); }else if (msg.what == 0){ startLocationProcess(WorkingMod); } @@ -322,16 +249,18 @@ public class LocationClient { } }; + + boolean wifi_ok=false,gps_ok=false,lbs_ok=false,gps_nosignal=false; public void waitAndSendLocation(){ - wifi_ok=false; + + wifi_ok=false; gps_ok=false; lbs_ok=false; gps_nosignal=false; - checktimes++; int mode=runtime.getLocationInstance().getWorkingMod(); if (runtime.getWifiInfo().length()>0 ) wifi_ok =true; @@ -355,16 +284,9 @@ public class LocationClient { if ((lbs_ok && timeout==true) ||(lbs_ok && gps_ok && wifi_ok )||(lbs_ok&&gps_nosignal&&wifi_ok)){ String AP01_CMD=protocolAPIHelper.AP01(runtime); - if (connection.isServerConnected() && KeepAlive.isConnected) - { - Logger.i("gps first send "+AP01_CMD); - connection.send(protocolAPIHelper.genStringMessage("AP01", AP01_CMD)); - }else{ - Logger.i("offline skip gps "+AP01_CMD); - FileOutputUtil.fileOutput(runtime.getCacheDir(),"APILog"," offlineskip "+AP01_CMD); - } -// triggerSendThread(); + Deliver.sendLocationMSG(AP01_CMD); + if (mTimer!=null){ mTimer.cancel(); mTimer=null; @@ -386,15 +308,8 @@ public class LocationClient { if ((lbs_ok && timeout==true) ||(lbs_ok && wifi_ok )){ String AP01_CMD=protocolAPIHelper.AP01(runtime); - if (connection.isServerConnected() && KeepAlive.isConnected) - { - Logger.i("wifi first send "+AP01_CMD); - connection.send(protocolAPIHelper.genStringMessage("AP01", AP01_CMD)); - }else{ - Logger.i("offline skip wifi "+AP01_CMD); - FileOutputUtil.fileOutput(runtime.getCacheDir(),"APILog"," offlineskip "+AP01_CMD); - } -// triggerSendThread(); + Deliver.sendLocationMSG(AP01_CMD); + if (mTimer!=null){ mTimer.cancel(); mTimer=null; @@ -425,53 +340,19 @@ public class LocationClient { }); } -// public void EqcAlgorithmInterfaceMethod4() { + public void updateCellInfo() { this.mLbsHelper.getAttchCellInfo(runtime.getContextProxy().getTelephonyManager()); // CellInfoUtil.triggerUpdateCellinfo(); CellInfoUtil.setCurrentAttachCellInfo(runtime, getLocationWakeLock()); } - -// public void EqcAlgorithmInterfaceMethod5(int paramInt) { + public void updateSimSignalInfo() { SimSignalUtil.getInstance((runtime.getContextProxy()).context); } - -// public void EqcAlgorithmInterfaceMethod6(int paramInt) { - // 飞行模式 1 开启 0 关闭 - public void setAirMode(int paramInt) { - boolean isAirModeOn = this.mSignalUtil.IsAirModeOn(); - boolean isScreenOn = this.mSignalUtil.isScreenON(); - switch (paramInt) { - - case 1: - if (!isAirModeOn && !isScreenOn) { - this.mSignalUtil.setAirMode("OpenAirplane"); - runtime.isAirMode = true; - notifiSetAirModeMethod(); - - } - if (isAirModeOn) { -// EqcAlgorithmNative.native_EqcAlgorithmMethod8(1); - - } - break; - case 0: - if (isAirModeOn) { - this.mSignalUtil.setAirMode("CloseAirplane"); - runtime.isAirMode = false; - notifiSetAirModeMethod(); - return; - } - break; - default: - break; - } - } - public PowerManager.WakeLock getLocationWakeLock() { PowerManager.WakeLock wakeLock = ((PowerManager)(runtime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "locationSend"); wakeLock.acquire(1000L); @@ -482,13 +363,11 @@ public void updateCellInfo() { //每分钟更新一次数据 runtime.preCellInfo = runtime.getCurrentCellInfo(); runtime.preCdmaInfo = runtime.getCdmaInfo(); - runtime.preTime = TimeUtil.getSystemTime(System.currentTimeMillis() - (protocolMainServer.alarmCycle * 60 * 1000)); + runtime.preTime = TimeUtil.getSystemTime(System.currentTimeMillis() - (CoreService.alarmCycle * 60 * 1000)); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("runtime.preCellInfo="); stringBuilder.append(runtime.preCellInfo); Logger.i(stringBuilder.toString()); - updateStepCount();//update StepCount - this.gSensorListener.startListen(paramWakeLock); performAlarm(paramWakeLock); } @@ -497,17 +376,15 @@ public void updateCellInfo() { public void startLocationProcess(int mod){ + updateStepCount();//update StepCount,保证每次定位前,计步数据是最新的。防止丢数据。 Logger.i("forceLocation="+forceLocation+", WorkingMod="+WorkingMod+", isLocating="+isLocating+", lastStep="+runtime.getLastStepCount()+", currentStep="+ runtime.getTotalStepCount()); if (isLocating ) { Logger.i("locating ,skip location!"); return; } - - // 不强制定位 且 WorkingMod 不是紧急模式,且 没有移动过 if ( !(( forceLocation == 1 ) || ( WorkingMod == 4 )) && ( runtime.getLastStepCount() == runtime.getTotalStepCount()) ){ - Logger.i("No Move ,skip location!"); return ; } @@ -533,25 +410,15 @@ public void updateCellInfo() { private static int WorkingMod=1; private static int forceLocation=0; public void onReceive(StringMessage paramStringMessage) { -// Logger.i("LocationClient onReceive " +paramStringMessage.cmd()+" linkOK "+linkOK ); -// if ("Sport:OK".equals(paramStringMessage.cmd())) -// this.mPedometer2 = this.H12StepCount; - Logger.i("LocationClient onReceive " +paramStringMessage.cmd() ); -// if (linkOK) -// return; -// if (paramStringMessage.cmd().startsWith("AP") || paramStringMessage.cmd().startsWith("BP")) { -// //如果Link:OK 则触发(激活)等待信号的发送线程 -//// triggerSendThread(); -// } + Logger.i("LocationClient onReceive " +paramStringMessage.cmd() ); + Deliver.triggerSendThread(); //响应定位指令 if ("StartLocate".equals(paramStringMessage.cmd()) ){ -// triggerSendThread(); forceLocation=1; this.startLocationProcess(WorkingMod); } if ("setWorkMod".equals(paramStringMessage.cmd())) { -// triggerSendThread(); int mod = 0; try { @@ -565,40 +432,21 @@ public void updateCellInfo() { runtime.getLocationInstance().setWorkingMod(mod); // runtime.getLocationInstance().setLocation_cycle(3); Logger.i("Set WorkMODE "+mod +" and reset Location AlarmCycle"); - protocolMainServer.getInstance().setLocationAlarm(mod); + CoreService.getInstance().setLocationAlarm(mod); // Logger.i("ResartLOCATION_MODE 2"); runtime.getContextProxy().sendBroadcast(LOCATION_MODE,runtime); forceLocation=1; this.startLocationProcess(mod); WorkingMod=mod; - } - - } - public void triggerSendThread(){ - this.mLock.lock(); - try { - linkOK = true; - this.mCondition.signal(); - - } finally { - this.mLock.unlock(); - } - } - MyThread2 mythread2=null; public void start() { this.mSignalUtil = SimSignalUtil.getInstance((runtime.getContextProxy()).context); - // 开启计步 -// EqcAlgorithmNative.EqcAlgorithmNativeSetInterface(this); -// EqcAlgorithmNative.native_EqcAlgorithm_Gsensor_eint_work_start(); -// EqcAlgorithmNative.native_EqcAlgorithmMethod2(); - ICJniUtils.enablePedometer();//.enableStepCounter(); //makesure enable stepCounter //获取LBS定位服务 this.mLbsHelper = runtime.getLbsHelper(); @@ -631,121 +479,90 @@ public void updateCellInfo() { intentFilter.addAction("android.intent.action.SCREEN_ON"); (runtime.getContextProxy()).context.registerReceiver(this.screenOnReceiver, intentFilter); - /*启动 阻塞队列buffer 发送县城,随时准备发送buffer的message*/ -// if (mythread2 == null) -// mythread2 = new MyThread2(this.mCondition, this.mLock); -// mythread2.exitthread=false; -// mythread2.start(); - this.haveChanegTo4GTime = SystemClock.elapsedRealtime(); + + + //暂时没有处理4G、2G切换问题 +// this.haveChanegTo4GTime = SystemClock.elapsedRealtime(); } public void stop() { -// mythread2.exitthread=true; -// if (mythread2 != null){ -//// triggerSendThread(); -//// mythread2.stop(); -// mythread2=null; -// } (runtime.getContextProxy()).context.unregisterReceiver(this.screenOnReceiver); -// this.executor.execute(new Runnable() { -// public void run() { LocationClient.AP16Queue(); } -// }); - this.gSensorListener.stopListen(); mLbsHelper.unRegisterBroadReceiver(); + this.executor.execute(new Runnable() { + public void run() { + Deliver.saveQueue(); + } + }); stopGpsLocate(); } - - static class MyThread2 extends Thread { - Condition condition; - - boolean isResent = false; - public boolean exitthread=false; - ReentrantLock lock; - - public MyThread2(Condition param1Condition, ReentrantLock param1ReentrantLock) { - this.condition = param1Condition; - this.lock = param1ReentrantLock; - } - - public void run() { - StringMessage stringMessage = null; - while (!exitthread) { - //循环发送queue 中的数据 - try { - Logger.i("Sending Thread Queue Take "); - StringMessage stringMessage1 = (StringMessage)LocationClient.queue.take(); - try { - if (runtime.getSignalStrength() + 110 < LocationClient.getMinSignalStrength(SimSignalUtil.getInstance((runtime.getContextProxy()).context).getNetworkType())) { - Logger.i("Skip Send for SignalStrengh "+(runtime.getSignalStrength() + 110 )+" < "+LocationClient.getMinSignalStrength(SimSignalUtil.getInstance((runtime.getContextProxy()).context).getNetworkType())); - //如果信号不好,把msg放回去 + private void notifiSetAirModeMethod() { (new Thread(new Runnable() { + public void run() { + SystemClock.sleep(3000L); + boolean bool = LocationClient.this.mSignalUtil.IsAirModeOn(); + byte b = 1; + if (bool != true) + b = 0; + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("AirMode=="); + stringBuilder.append(b); + Logger.i(stringBuilder.toString()); - LocationClient.queue.putFirst(stringMessage1); + } + })).start(); } - } else { - stringMessage=stringMessage1; + private void sendBatteryNotification() { + if (runtime.getHaveBatteryChange() && !runtime.getBatterychanging() && !this.batteryNotification) { +// connection.send(API.H05(runtime, "2")); + Logger.i("sendBatteryNotification LevelChanged "); + this.batteryNotification = true; + } + if (runtime.getBatteryLow() && !runtime.getBatterychanging() && !this.batteryLowNotification) { +// connection.send(API.H05(runtime, "1")); + Logger.i("sendBatteryNotification Low Battery "); + this.batteryLowNotification = true; + } + if (runtime.getBatterychanging()) { + this.batteryNotification = false; + this.batteryLowNotification = false; + } + } + // 飞行模式 1 开启 0 关闭 + public void setAirMode(int paramInt) { + boolean isAirModeOn = this.mSignalUtil.IsAirModeOn(); + boolean isScreenOn = this.mSignalUtil.isScreenON(); + switch (paramInt) { - Context context = (runtime.getContextProxy()).context; - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("send="); - stringBuilder.append(stringMessage.cmd()); - stringBuilder.append(", "); - stringBuilder.append(stringMessage.isFromCache()); - FileOutputUtil.fileOutput(runtime.getCacheDir(), "MessageInfo", stringBuilder.toString()); - Logger.i(stringBuilder.toString()); - if( connection.isServerConnected() ==false && !KeepAlive.isConnected ) { + case 1: + if (!isAirModeOn && !isScreenOn) { + this.mSignalUtil.setAirMode("OpenAirplane"); + runtime.isAirMode = true; + notifiSetAirModeMethod(); - Logger.i("Skip Send for connection and KeepAlive both false "); - //发现连接断开则重试连接 -// protocolMainServer.getInstance().startConnectionRetryTimer(); - //连接断开就把msg放回队列,以便重发 - LocationClient.queue.putFirst(stringMessage1); - }else{ - //连接状态都正常才发送包 - connection.send(stringMessage); - } + } + break; + case 0: - this.lock.lock(); - LocationClient.linkOK=false; - try { - if (KeepAlive.isConnected) { - //如果 服务器连接状态,等30秒,随时等待数据发送 - Logger.i("KeepAlive.isConnected "+KeepAlive.isConnected+" delay 30000ms"); - this.condition.await(30000L, TimeUnit.MILLISECONDS); - } else { - //如果服务器断开,等5秒 以便连接后尽快进入下一循环,尽量及时响应 - Logger.i("KeepAlive.isConnected "+KeepAlive.isConnected+ " , connection isconnected "+connection.isServerConnected()+" delay 5000ms"); - - this.condition.await(5000L, TimeUnit.MILLISECONDS); - } - if (linkOK) { - if (stringMessage.all() != null && stringMessage.all()[0].equals("AP16")) { - this.isResent = false; - Logger.i( " AP16 need wait for wifi scan list"); - Deliver.releaseWakeLockForGetWifiList(); - } - } - } catch (InterruptedException e) { - e.printStackTrace(); - }finally{ - this.lock.unlock(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); + if (isAirModeOn) { + this.mSignalUtil.setAirMode("CloseAirplane"); + runtime.isAirMode = false; + notifiSetAirModeMethod(); + return; } - }//while end + break; + + default: + break; } + } + } diff --git a/app/src/main/java/com/ic/protocol/MainActivity.java b/app/src/main/java/com/ic/protocol/MainActivity.java index ab36b24e..9f4cb621 100644 --- a/app/src/main/java/com/ic/protocol/MainActivity.java +++ b/app/src/main/java/com/ic/protocol/MainActivity.java @@ -14,8 +14,9 @@ import android.widget.CompoundButton; import android.widget.TextView; import android.widget.ToggleButton; +import com.enqualcomm.support.R; import com.ic.jni.ICJniUtils; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; import com.ic.protocol.utils.Logger; import java.util.Timer; @@ -23,6 +24,9 @@ import java.util.TimerTask; public class MainActivity extends AppCompatActivity { TextView tv; + + private boolean showmessage=false; + private Timer timer; Handler handler=new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message message) { @@ -31,25 +35,25 @@ public class MainActivity extends AppCompatActivity { StringBuilder sb=new StringBuilder(); try { + if (showmessage) { + sb.append("ppg is available ").append(ICJniUtils.isPPGavailable()) + .append(", ppg isstarted ").append(ICJniUtils.isPPGStarted()) + .append(",ppg ").append(ICJniUtils.getPPG()) + .append("weared ").append(ICJniUtils.isWeared()) + .append(",spo2 ").append(ICJniUtils.getSPO2()) + .append(",bph ").append(ICJniUtils.getHighBloodPressure()) + .append(",bpl ").append(ICJniUtils.getLowBloodPressure()) + .append("\n"); + sb.append(CoreService.getInstance().getServerAlive()); + tv.setText(sb.toString()); + } }catch(Exception e){ e.printStackTrace(); } - sb.append("ppg is available ").append(ICJniUtils.isPPGavailable()) - .append(", ppg isstarted ").append(ICJniUtils.isPPGStarted()) - .append(",ppg ").append(ICJniUtils.getPPG()) - .append("weared ").append(ICJniUtils.isWeared()) - .append(",spo2 ").append(ICJniUtils.getSPO2()) - .append(",bph ").append(ICJniUtils.getHighBloodPressure()) - .append(",bpl ").append(ICJniUtils.getLowBloodPressure()) - .append("\n"); - - sb.append(protocolMainServer.getInstance().getServerAlive()); - tv.setText( sb.toString()); - return false; } }); @@ -68,7 +72,7 @@ public class MainActivity extends AppCompatActivity { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - protocolMainServer.getInstance().send_at_to_onoff_simcard(b); + CoreService.getInstance().send_at_to_onoff_simcard(b); } }); ToggleButton tbtnblood = (ToggleButton)findViewById(R.id.toggleButton2); @@ -80,7 +84,7 @@ public class MainActivity extends AppCompatActivity { } }); - startService(new Intent(this,protocolMainServer.class));// protocol service + startService(new Intent(this,CoreService.class));// protocol service // double longitude=113.878339f; // double latitude=22.580827f; @@ -94,19 +98,39 @@ public class MainActivity extends AppCompatActivity { // latitude=last; // // Logger.i(" lat="+latitude+",lon="+longitude); + + + TextView tv_version=(TextView)findViewById(R.id.textViewVersion); + tv_version.setText( getVersionName(this)); + + } + + @Override + protected void onResume() { + super.onResume(); TimerTask tmt=new TimerTask() { @Override public void run() { handler.sendEmptyMessage(0); } }; - new Timer().schedule(tmt,0,2000); + timer=new Timer(); + timer.schedule(tmt,0,2000); + showmessage=true; + } - TextView tv_version=(TextView)findViewById(R.id.textViewVersion); - tv_version.setText( getVersionName(this)); + @Override + protected void onPause() { + super.onPause(); + if (timer!=null) { + timer.cancel(); + timer.purge(); + timer = null; + } + showmessage=false; - } + } /** * 得到当前应用版本名称的方法 * @@ -130,14 +154,16 @@ public class MainActivity extends AppCompatActivity { } + + private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnConnect: //进行连接Socket:这里使用的是,在本地上开启了一个服务器。 - stopService(new Intent(MainActivity.this,protocolMainServer.class));// protocol service - startService(new Intent(MainActivity.this,protocolMainServer.class));// protocol service + stopService(new Intent(MainActivity.this,CoreService.class));// protocol service + startService(new Intent(MainActivity.this,CoreService.class));// protocol service break; diff --git a/app/src/main/java/com/ic/protocol/adapter/protocolAPIHelper.java b/app/src/main/java/com/ic/protocol/adapter/protocolAPIHelper.java index a289a175..77f5cadc 100644 --- a/app/src/main/java/com/ic/protocol/adapter/protocolAPIHelper.java +++ b/app/src/main/java/com/ic/protocol/adapter/protocolAPIHelper.java @@ -5,15 +5,21 @@ import android.util.Log; import com.ic.protocol.Config; import com.ic.protocol.bean.Contact; +import com.ic.protocol.bean.Content; import com.ic.protocol.bean.ICLocation; import com.ic.protocol.bean.Runtime; import com.ic.protocol.bean.StringMessage; +import com.ic.protocol.bean.VoiceContent; import com.ic.protocol.bean.voicePacket; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; +import com.ic.protocol.service.Deliver; import com.ic.protocol.utils.Connection; import com.ic.protocol.utils.DBHelper; import com.ic.protocol.utils.Logger; +import com.ic.protocol.utils.NettyConnection; +import com.ic.protocol.utils.ProcessReceiver; import com.ic.protocol.utils.SharPreferenceUtil; +import com.ic.protocol.utils.TimeUtil; import com.ic.protocol.utils.Util; import java.util.ArrayList; @@ -305,8 +311,8 @@ public class protocolAPIHelper { //示例数据:IWAP03,06000908000102,5555,30# IWAP03,000000null00000,0,0# return new StringBuffer(CMDHEADER).append(cmdMap.get(CMD_TYPE.AP03)).append(CMDSPLIT).append(String.format("%03d",abs(ds.getSignalStrength()))) .append(ds.getGPSLocationStarNums()).append(ds.getBattery()).append("0") - .append(ds.getProtection()).append(ds.getWorkMode()).append(CMDSPLIT) - .append(ds.getTotalStepCount()).append(CMDSPLIT).append(0/*rolltime*/).append(CMDEND).toString(); + .append(ds.getProtection()).append(ds.getWorkModeStr()).append(CMDSPLIT) + .append(ds.getTotalStepCount()).append(CMDSPLIT).append(ds.getRolltimes()).append(CMDEND).toString(); } //处理 心跳 BP03 public void handleBP03(String cmd){ @@ -325,10 +331,10 @@ public class protocolAPIHelper { * 00:第一个0:是否需要回复地址信息,0:不回复,1回复. * HOME|74-DE-2B-44-88-8C|97&HOME1|74-DE-2B-44-88-8C|97&HOME2|74-DE-2B-44-88-8C|97&HOME3|74-DE-2B-44-88-8C|97# */ - return new StringBuffer(CMDHEADER).append(cmdMap.get(CMD_TYPE.AP10)).append(ds.getShortDate()) - .append(ds.getGPSData()).append(ds.getShortTime()).append(ds.getGPSHeading()).append(String.format("%03d",abs(ds.getSignalStrength()))) + return new StringBuffer(CMDHEADER).append(cmdMap.get(CMD_TYPE.AP10)).append(TimeUtil.getShortDate()) + .append(ds.getGPSData()).append(TimeUtil.getShortTime()).append(ds.getGPSHeading()).append(String.format("%03d",abs(ds.getSignalStrength()))) .append(ds.getGPSLocationStarNums()).append(ds.getBattery()).append("0") - .append(ds.getProtection()).append(ds.getWorkMode()).append(CMDSPLIT) + .append(ds.getProtection()).append(ds.getWorkModeStr()).append(CMDSPLIT) .append(ds.getLBSData()).append(CMDSPLIT) .append(ds.getAlarmType()).append(CMDSPLIT) .append(ds.getLanguage()).append(CMDSPLIT) @@ -343,10 +349,10 @@ public class protocolAPIHelper { // 460,0,9520,3671, // Home|74-DE-2B-44-88-8C|97& Home1|74-DE-2B-44-88-8C|97&Home2|74-DE-2B-44-88-8C|97& Home3|74-DE-2B-44-88-8C|97# // IWAP01191230A2232.9807N11404.9355E000.1161320000.0006000910000000,460,00,9520,3671,# - return new StringBuffer(CMDHEADER).append(cmdMap.get(CMD_TYPE.AP01)).append(ds.getShortDate()) - .append(ds.getGPSData()).append(ds.getShortTime()).append(ds.getGPSHeading()).append(String.format("%03d",abs(ds.getSignalStrength()))) + return new StringBuffer(CMDHEADER).append(cmdMap.get(CMD_TYPE.AP01)).append(TimeUtil.getShortDate()) + .append(ds.getGPSData()).append(TimeUtil.getShortTime()).append(ds.getGPSHeading()).append(String.format("%03d",abs(ds.getSignalStrength()))) .append(ds.getGPSLocationStarNums()).append(ds.getBattery()).append("0") - .append(ds.getProtection()).append(ds.getWorkMode()).append(CMDSPLIT) + .append(ds.getProtection()).append(ds.getWorkModeStr()).append(CMDSPLIT) .append(ds.getLBSData()).append(CMDSPLIT).append(ds.getWifiInfo()).append(CMDEND).toString(); } @@ -648,7 +654,8 @@ public class protocolAPIHelper { } } - runtime.getDbHelper().saveContacts(contactArray,false,false,true,false,false); + contactArray.add(new Contact(Contact.CATEGORY_ADMIN,"GROUP","123")); + runtime.getDbHelper().saveContacts(contactArray,true,false,true,false,false); }else{ Logger.i(" BP14 format error!"); @@ -778,6 +785,65 @@ public class protocolAPIHelper { + public static byte[] AP07(String packetTime,int count,int index,int datalen,byte[] amrdata){ +//IWAP07,20140818064408,6,1,1024,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX# +//说明: +//IW:标识符 +//AP07 : 命令字符 +//20140818064408 :yyyyMMddHHmmss 格式的年月日时分秒,设备录音时间 +//6:语音包分包总数 +//1 :当前包数,第一包为1,第二包为2,。。。。。。同一个语音包的语音时间相同 +//1024 :语音包长度 +//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:当前音频数据, 每个音频数据包大小为1024字节,最后一包不足1024的取实际字节数 +//语音包上传规则: +//按包次序依次上传,上传后如果没有收到服务器的响应包,则继续上传该语音包。 +//收到设备回复确认数据包接收成功状态后,继续开始依次上传下一个数据包。。。。。。 +//如果设备回复确认数据包接收失败状态,则重复发送上一个数据包 + + + String sb=new StringBuffer(CMDHEADER).append(cmdMap.get(CMD_TYPE.AP07)) + .append(CMDSPLIT).append(packetTime) + .append(CMDSPLIT).append(count) + .append(CMDSPLIT).append(index) + .append(CMDSPLIT).append(datalen) + .append(CMDSPLIT).toString(); + + byte[] sentbuf=new byte[sb.length()+datalen+1]; + System.arraycopy(sb.getBytes(),0,sentbuf,0,sb.length()); + System.arraycopy(amrdata,0,sentbuf,sb.length(),datalen); + sentbuf[sb.length()+datalen]='#'; + + return sentbuf; + + } + + + public void handleBP07(String cmd , NettyConnection connection ){ +//平台响应: IWBP07,20140818064408,6,1,1# +//20140818064408:设备语音时间,yyyyMMddHHmmss 格式的年月日时分秒 +//6:语音包分包总数 +//1:当前设备收到的是第几个包 +//1:表示服务器接受数据成功,0表示服务器接受数据失败 + String[] cmdlist=cmd.split(CMDSPLIT); + if (cmdlist.length==5){ + String time=cmdlist[1]; + int packetCount=Integer.valueOf(cmdlist[2]); + int packetIndex=Integer.valueOf(cmdlist[3]); + int receiveSuccess=Integer.valueOf(cmdlist[4]); + Logger.i("服务器在"+time+" 收到语音 "+packetIndex+"/"+packetCount+" "+ (receiveSuccess==1?"成功":"失敗")); + if (receiveSuccess == 1){ + //如果服务器接收 语音成功,则设置下一个要发送的语音包Index,当index == packetCount的时候表示所有包发送完毕,停止继续发送 + voicePacket.getInstanceSent().setCurrentIndexToSent(++packetIndex); + } + //发送消息,再次检查要发送的语音包,确认其发送完毕 + connection.DeliverCMDMessageToSystem("BP07","SentVoicePacket"); + + }else{ + Logger.i(" BP07 Format error!"); + } + } + + public static String AP33(String cmdindex,int workMode){ //IWAP33,080835,1# //080835:指令流水号 @@ -989,7 +1055,7 @@ public static String AP15(String index){ } //处理 BP28 语音消息 - public void handleBP28(Connection connection,String cmd,byte[] bytes) { + public void handleBP28(Connection connection,String cmd,Runtime runtime,byte[] bytes) { //log("handleBP28 msg"+cmd); /** * IWBP28, D3590D54,XXXX,6,1,1024,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX# @@ -1039,8 +1105,17 @@ public static String AP15(String index){ .append(",packetDatalen = ").append(packetData.length); log( stringBuffer.toString()); - voicePacket.getInstance().appendVoice(Name,appendIndex,packetCount,currentId,packetLen,packetData); connection.send(genStringMessage("AP28",AP28(Name,appendIndex,packetCount,currentId,1))); + voicePacket.getInstance().appendVoice(Name,appendIndex,packetCount,currentId,packetLen,packetData); + log("================"+voicePacket.getInstance().toString()); + if (voicePacket.getInstance().isFinished()) + { + String amrFilepath=Util.saveFile(voicePacket.getInstance().getVoicePacketBytes(),0,voicePacket.getInstance().getVoicePacketLen(),runtime.getCacheDir(),voicePacket.getInstance().getName()+".amr"); + Logger.i("save Amr file to "+amrFilepath); + voicePacket.getInstance().clearPacket(); + runtime.getDbHelper().insertMessage( VoiceContent.placeHolderIn(Content.CATEGORY_VOICE,"1234567890",amrFilepath)); + + } }else{ log("handleBP28","format Error"); diff --git a/app/src/main/java/com/ic/protocol/bean/ICLocation.java b/app/src/main/java/com/ic/protocol/bean/ICLocation.java index 46d487dd..c921356c 100644 --- a/app/src/main/java/com/ic/protocol/bean/ICLocation.java +++ b/app/src/main/java/com/ic/protocol/bean/ICLocation.java @@ -33,6 +33,7 @@ public class ICLocation { public static final int LOWPOWER_MOD=2; // location rate 1 time per hour public static final int EMERGNECY_MOD=3; //location rate 1 time per minutes public static final int REALTIME_MOD=4; //location rate 1 time per minutes + public static final int CUSTOM_MOD=5; //location rate 1 time per minutes private int mworkingMod; diff --git a/app/src/main/java/com/ic/protocol/bean/Runtime.java b/app/src/main/java/com/ic/protocol/bean/Runtime.java index f3a9f4dc..6d0d9648 100644 --- a/app/src/main/java/com/ic/protocol/bean/Runtime.java +++ b/app/src/main/java/com/ic/protocol/bean/Runtime.java @@ -78,19 +78,24 @@ public class Runtime { public String lacByAt; - private String latitude; - + private LBSHelper lbsHelper; private heartRateStatus HRS=null; -// private String location; - + + private boolean UseQueue=false; private boolean lockSimInfo=false; - - private String longitude; - + + + public void setUseQueue(boolean usequeue){ + UseQueue=usequeue; + } + + public boolean getUseQueue(){ + return UseQueue; + } private String mccAndMnc; private String language="zh-cn"; @@ -288,12 +293,10 @@ public class Runtime { this.lacByAt = paramString1; this.cellidByAt = paramString2; } - -// public void setLocation(String paramString) { this.location = paramString; } + public void setLockSimInfo(boolean paramBoolean) { this.lockSimInfo = paramBoolean; } - - public void setLongitude(String paramString) { this.longitude = paramString; } + public void setMccAndMnc(String MccMnc) { this.mccAndMnc = MccMnc; @@ -321,11 +324,6 @@ public class Runtime { public void setTotalStepCount(int paramInt) { this.totalStepCount = paramInt; } - - private final String UserDebug = "userdebug"; - private final String User = "user"; - - private ICLocation gpsp = null; private String wifiInfo=""; @@ -347,14 +345,6 @@ public class Runtime { } - /* - return UserDebug , User - */ - public String BuildType() { - return UserDebug; - } - - public String HardwareInfo() { return "SC9820E C41 V1.0"; } @@ -367,20 +357,24 @@ public class Runtime { /* AP03 心跳包 */ - + //暂时没有实现此功能 public String getGPSLocationStarNums() { return "000"; } + //此功能未实现 public String getProtection() { return "00"; } - public String getWorkMode() { - return "00"; - } + // + public String getWorkModeStr() { + String gpsStr=String.format("%02d",getLocationInstance().getWorkingMod()); + return gpsStr; + } + //未实现睡眠监测 public String getRolltimes() { return "00"; } @@ -388,53 +382,7 @@ public class Runtime { /* AP01 定位 */ - /* 返回 2位年2位月2位日, 如2019-12-30 返回 191230*/ - public String getShortDate() { - String DEFAULT_TIME_FORMAT = "yyMMdd"; - SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT); - String dateStr = dateFormatter.format(Calendar.getInstance().getTime());//获取当前时间 - return dateStr; - } - - public void parseDatetiime(String datetimeStr){ - SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);//输入的被转化的时间格式 - SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式 - SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); - Date date1 = null; - try { - date1 = dff.parse(datetimeStr); - } catch (ParseException e) { - e.printStackTrace(); - } - String str1 = df1.format(date1); - String str2 = df2.format(date1); - - } - /*061830: 格林尼治时间06 点18 分30 秒 */ - public String getShortTime(){ - String DEFAULT_TIME_FORMAT = "HHmmss"; - //设置时间的格式 - // yyyy-MM-dd 1969-12-31 - // yyyy-MM-dd 1970-01-01 - // yyyy-MM-dd HH:mm 1969-12-31 16:00 - // yyyy-MM-dd HH:mm 1970-01-01 00:00 - // yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800 - // yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000 - // yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800 - // yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000 - // yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800 - // yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000 - //注:HH显示的是24小时制,hh显示的是12小时制 - - SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT); - String dateStr = dateFormatter.format(Calendar.getInstance().getTime());//获取当前时间 -// SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);//输入的被转化的时间格式 -// SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式 -// SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); - - return dateStr; - } public boolean isGPSFixed(){ return (gpsp.getLocationStat() == ICLocation.LOCATION_STAT.LOCATION_FIXED); diff --git a/app/src/main/java/com/ic/protocol/bean/VoiceContent.java b/app/src/main/java/com/ic/protocol/bean/VoiceContent.java index 4930e483..43acfa68 100644 --- a/app/src/main/java/com/ic/protocol/bean/VoiceContent.java +++ b/app/src/main/java/com/ic/protocol/bean/VoiceContent.java @@ -12,26 +12,17 @@ public class VoiceContent extends Content { } - public static VoiceContent from(VoiceContent _voiceContent, byte[] amrData, File amrFilepath) { - byte b = amrData[0]; - byte[] arrayOfByte = new byte[b]; - System.arraycopy(amrData, 1, arrayOfByte, 0, b); - ArrayList arrayList = Util.split(arrayOfByte, (byte)59, 0); - StringBuilder stringBuilder1 = new StringBuilder(); - stringBuilder1.append(new String((byte[])arrayList.get(1))); - stringBuilder1.append(new String((byte[])arrayList.get(2))); - String str2 = stringBuilder1.toString(); - String str3 = new String((byte[])arrayList.get(4)); - int i = amrData.length - 1 - b; - int j = amrData.length; + public static VoiceContent from(VoiceContent _voiceContent, byte[] amrData, File amrFilepath,String servertime) { + StringBuilder stringBuilder2 = new StringBuilder(); - stringBuilder2.append(str3); +// stringBuilder2.append(str3); stringBuilder2.append(".amr"); - String str1 = Util.saveFile(amrData, j - i, i, amrFilepath, stringBuilder2.toString()); - i = Util.getDuration(str1); - _voiceContent.preview = (_voiceContent.content = str1).valueOf(i); + String str1 = Util.saveFile(amrData, 0, amrData.length, amrFilepath, stringBuilder2.toString()); + int duration = Util.getDuration(str1); + _voiceContent.content = str1; + _voiceContent.preview = String.valueOf(duration); _voiceContent.status = 2; - _voiceContent.serverTime = str2; + _voiceContent.serverTime = servertime; return _voiceContent; } diff --git a/app/src/main/java/com/ic/protocol/bean/voicePacket.java b/app/src/main/java/com/ic/protocol/bean/voicePacket.java index 7036a963..f7169d4b 100644 --- a/app/src/main/java/com/ic/protocol/bean/voicePacket.java +++ b/app/src/main/java/com/ic/protocol/bean/voicePacket.java @@ -1,21 +1,49 @@ package com.ic.protocol.bean; import java.util.ArrayList; +import java.util.Iterator; public class voicePacket { private static voicePacket gvoicePacket=null; - - public static voicePacket getInstance(){ if (gvoicePacket==null) gvoicePacket=new voicePacket(); return gvoicePacket; } + private static voicePacket gvoicepacket_sent=null; + public static voicePacket getInstanceSent(){ + if (gvoicepacket_sent==null) + gvoicepacket_sent=new voicePacket(); + return gvoicepacket_sent; + } + + String time=null; String Name=null; String appendIndex=null; int packetCount =0; + int currentIndexToSent=0;// 如果 (currentIndexToSent == (packetCount -1)) 则发送完毕 + + public void setCurrentIndexToSent(int index){ + currentIndexToSent=index; + } + + public int getCurrentIndexToSent(){ + return currentIndexToSent; + } + + public int getPacketCount(){ + return packetCount; + } + + + public void setPacketTime(String _time){ + time=_time; + } + public String getPacketTime(){ + return time; + } ArrayList packetArray =new ArrayList(); public class voicepacketItem{ int currentId; @@ -26,10 +54,17 @@ public class voicePacket { packetData=_packetData; currentId=_currentId; } + public byte[] getPacketData() + { + return packetData; + } + public int getPacketLen(){ + return packetLen; + } } public boolean appendVoice(String _Name, String _appendIndex,int _packetCount,int _currentId, int _packetLen, byte[] _packetData){ boolean ret=false; - if (_Name==null|| _appendIndex==null || _Name.isEmpty() || _appendIndex.isEmpty() ){ + if (_Name==null|| _appendIndex==null || _Name.isEmpty() ){ return false; } if (packetArray.size()==0) @@ -38,7 +73,7 @@ public class voicePacket { appendIndex=_appendIndex; packetCount=_packetCount; } - if (_packetCount==packetCount && appendIndex.equals(_appendIndex) && Name.equals(_Name) ){ + if (_packetCount==packetCount && Name.equals(_Name) ){ boolean packetfound=false; for ( voicepacketItem item: packetArray ) { if (item.currentId == _currentId){ @@ -65,7 +100,7 @@ public class voicePacket { @Override public String toString(){ StringBuilder stringBuilder=new StringBuilder(); - if (Name==null|| appendIndex==null || Name.isEmpty() || appendIndex.isEmpty() ){ + if (Name==null|| appendIndex==null || Name.isEmpty() ){ return stringBuilder.toString(); } @@ -89,4 +124,53 @@ public class voicePacket { Name=null; appendIndex=null; } + + public int getVoicePacketLen(){ + int len=0; + if (isFinished()){ + Iterator it= packetArray.iterator(); + while(it.hasNext()){ + len+=it.next().packetLen; + } + } + return len; + } + public voicepacketItem getVoicePacketWithIndex(int index){ + + for (int i=0;i< packetArray.size();i++){ + voicepacketItem tmp=packetArray.get(i); + if (tmp.currentId==index) + return tmp; + } + + return null; + } + public byte[] getVoicePacketBytes(){ + byte[] amrbuf; + int buflen=getVoicePacketLen(); + if (buflen>0){ + amrbuf=new byte[buflen]; + int index=0; + for(int i =0;i queue = new LinkedBlockingDeque(50); + + private static FileCache fileCache; + private static NettyConnection connection; + public static boolean is_active_location = false; private PowerManager.WakeLock ReceiveWakeLock; @@ -54,10 +83,10 @@ public class Deliver extends AbstractConnectionService { private Runnable delayTh; private Connection mConnection; - + private ConWifiReceiver mMyWifiReceiver; - private Runtime mRuntime; + private static Runtime mRuntime; private final String spilForWifi = "@EQCWIFI@"; @@ -72,14 +101,224 @@ public class Deliver extends AbstractConnectionService { static { } - + public Deliver(NettyConnection paramNettyConnection, Runtime paramRuntime) { + connection = paramNettyConnection; + mRuntime = paramRuntime; + //把queue 保存在磁盘中的缓存文件 + //此文件只缓存 除了 登录指令AP00,心跳AP03以及voice 分包指令以外的需要上传的指令。初步规划为 定位AP01和心率/血压 APHT + fileCache = new FileCache(paramRuntime.getFileDir()); + initQueue(); + } + public static void triggerSendThread(){ + if (mRuntime.getUseQueue()) { + mLock.lock(); + try { + mCondition.signal(); + + } finally { + mLock.unlock(); + } + } + } + MyThread2 mythread2=null; + + private void initQueue(){ + if (mRuntime.getUseQueue()) { + /*启动 阻塞队列buffer 发送县城,随时准备发送buffer的message*/ + if (mythread2 == null) + mythread2 = new MyThread2(this.mCondition, this.mLock); + mythread2.exitthread=false; + mythread2.start(); + } + } + + private void deInitQueue(){ + if (mRuntime.getUseQueue()) { + mythread2.exitthread = true; + if (mythread2 != null) { +// mythread2.stop(); + mythread2 = null; + } + } + } + private static void loadMessage2Queue() { + byte b = 0; + //一次只处理5条数据 + while (b < 5) { + String str = fileCache.load(); + if (str != null) { + byte b1 = ++b; + + try { + StringMessage stringMessage = new StringMessage(str); + //如果在queue中添加失败,则写回cache中 + if (!queue.offerLast(stringMessage)) { + fileCache.put(str); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + public static void saveQueue() { + lock.lock(); + try { + String str; + if (!queue.isEmpty()) { + StringBuilder stringBuilder = new StringBuilder(); + StringMessage stringMessage = queue.poll(); + while (stringMessage != null) { + String cmd=stringMessage.isFromCache(); + stringBuilder.append(cmd); + stringBuilder.append("\n"); + fileCache.put(cmd); + stringMessage = queue.poll(); + } + str = stringBuilder.toString(); + } else { + str = null; + } + Logger.i("save queue to cache : \n"+str); + lock.unlock(); + return; + } finally { + lock.unlock(); + } + } + + + static class MyThread2 extends Thread { + Condition condition; + + boolean isResent = false; + public boolean exitthread=false; + ReentrantLock lock; + + public MyThread2(Condition param1Condition, ReentrantLock param1ReentrantLock) { + this.condition = param1Condition; + this.lock = param1ReentrantLock; + } + + public void run() { + StringMessage stringMessage = null; + + while (!exitthread) { + + //循环发送queue 中的数据 + + try { + Logger.i("Sending Thread Queue Take "); + + StringMessage stringMessage1 = (StringMessage)queue.take(); + try { + + int signal=mRuntime.getSignalStrength(); + int networkType=SimSignalUtil.getInstance((mRuntime.getContextProxy()).context).getNetworkType(); + if (signal + 110 < getMinSignalStrength(networkType)) { + Logger.i("Skip Send for SignalStrengh "+(signal + 110 )+" < "+getMinSignalStrength(networkType)); + //如果信号不好,把msg放回去 + queue.putFirst(stringMessage1); + + } else { + + stringMessage=stringMessage1; + + Context context = (mRuntime.getContextProxy()).context; + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("send="); + stringBuilder.append(stringMessage.cmd()); + stringBuilder.append(", "); + stringBuilder.append(stringMessage.isFromCache()); + FileOutputUtil.fileOutput(mRuntime.getCacheDir(), "MessageInfo", stringBuilder.toString()); + Logger.i(stringBuilder.toString()); + if( connection.isServerConnected() ==false && !KeepAlive.isConnected ) { + + Logger.i("Skip Send for connection and KeepAlive both false "); + //发现连接断开则重试连接 +// CoreService.getInstance().startConnectionRetryTimer(); + //连接断开就把msg放回队列,以便重发 + queue.putFirst(stringMessage1); + }else{ + //连接状态都正常才发送包 + connection.send(stringMessage); + } + + + this.lock.lock(); + + try { + if (KeepAlive.isConnected) { + //如果 服务器连接状态,等30秒,随时等待数据发送 + Logger.i("KeepAlive.isConnected "+KeepAlive.isConnected+" delay 30000ms"); + this.condition.await(30000L, TimeUnit.MILLISECONDS); + } else { + //如果服务器断开,等5秒 以便连接后尽快进入下一循环,尽量及时响应 + Logger.i("KeepAlive.isConnected "+KeepAlive.isConnected+ " , connection isconnected "+connection.isServerConnected()+" delay 5000ms"); + + this.condition.await(5000L, TimeUnit.MILLISECONDS); + } + + + if (queue.peek() == null) { + loadMessage2Queue(); + this.lock.unlock(); + continue; + } + + } catch (InterruptedException e) { + e.printStackTrace(); + }finally{ + this.lock.unlock(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } catch (Exception e) { + e.printStackTrace(); + } + }//while end + } + } +public static void sendLocationMSG( String Msg){ + + if(mRuntime.getUseQueue()){ + ServiceUtil.offerQueue(protocolAPIHelper.genStringMessage("queue",Msg)); + triggerSendThread(); + }else { + if (connection.isServerConnected() && KeepAlive.isConnected) { + Logger.i(" first send " + Msg); + connection.send(protocolAPIHelper.genStringMessage("queue",Msg)); + } else { + Logger.i("offline skip " + Msg); + FileOutputUtil.fileOutput(mRuntime.getCacheDir(), "APILog", " offlineskip " + Msg); + } + } +} + private static int getMinSignalStrength(int paramInt) { + int b = -105; + switch (paramInt) { + case SimSignalUtil.IS_4G: + b = -100; + break; + case SimSignalUtil.IS_2G: + case SimSignalUtil.IS_3G: + default: + break; + } + return b; + } + public static PowerManager.WakeLock WakeLockForGetWifiList(Runtime paramRuntime) { - PowerManager.WakeLock wakeLock = ((PowerManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "waitForWifiListReply"); + PowerManager.WakeLock wakeLock = ((PowerManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, RECEIVE_WAKE_LOCKTAG); wakeLock.acquire(120000L); return wakeLock; } - private boolean isSilence(Runtime paramRuntime) { return SharPreferenceUtil.getPrefBoolean((paramRuntime.getContextProxy()).context, "KEY_ISSILENCE", false); } + private boolean isSilence(Runtime paramRuntime) { + return SharPreferenceUtil.getPrefBoolean((paramRuntime.getContextProxy()).context, "KEY_ISSILENCE", false); + } public static void releaseWakeLockForGetWifiList() { if (WifiListWakeLock == null) { @@ -93,7 +332,7 @@ public class Deliver extends AbstractConnectionService { } public PowerManager.WakeLock getWakeLock() { - PowerManager.WakeLock wakeLock = ((PowerManager)(this.mRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ReceiveWakelockTag"); + PowerManager.WakeLock wakeLock = ((PowerManager)(this.mRuntime.getContextProxy()).context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, RECEIVE_WAKE_LOCKTAG); wakeLock.acquire(40000L); return wakeLock; } @@ -109,449 +348,63 @@ public class Deliver extends AbstractConnectionService { public void onDetach(Connection paramConnection, Runtime paramRuntime) {} public boolean onReceive(StringMessage paramStringMessage, Connection paramConnection, final Runtime paramRuntime) { - StringBuilder stringBuilder4; - final String number; - StringBuilder stringBuilder3; - String[] arrayOfString6; - final WifiManager wifiManager; - long l; - int i=-1; - StringBuilder stringBuilder2; - Intent intent; - String str4; - String[] arrayOfString5; - String str3; - StringBuilder stringBuilder1; - String[] arrayOfString4; - String str2; - String[] arrayOfString2; - Context context; - String str1; - DBHelper dBHelper; - final String[] passWord; - String[] arrayOfString1; this.mConnection = paramConnection; this.mRuntime = paramRuntime; String cmd = paramStringMessage.cmd(); Logger.i("Deliver receive cmd "+paramStringMessage.cmd()); + if (cmd.equals("BP07") || cmd.equals("SentVoicePacket")){ + //收到BP07 表示服务器收到一个voicePacket 分包成功,开始检查下一个包是否存在需要发送。 + //收到SentVoicePacket 表示 有一个VoiceMessage要发送,需要开始检查并发送语音分包。 + voicePacket voicepacket= voicePacket.getInstanceSent(); + if (voicepacket.getCurrentIndexToSent() < voicepacket.getPacketCount()){ + Logger.i("voicepacket "+voicepacket.getName()+" "+voicepacket.getPacketTime()+" send "+(voicepacket.getCurrentIndexToSent()+1)+"/"+voicepacket.getPacketCount()); + ((NettyConnection)mConnection).sendMsg( + protocolAPIHelper.AP07(voicepacket.getPacketTime(), + voicepacket.getPacketCount(), + voicepacket.getCurrentIndexToSent(), + voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketLen(), + voicepacket.getVoicePacketWithIndex(voicepacket.getCurrentIndexToSent()).getPacketData()) + ); + }else{ + Logger.i("voicepacket "+voicepacket.getName()+" "+voicepacket.getPacketTime()+" sent Done!"); + } + return true; + } - if (cmd.startsWith("SmsSet")) { - arrayOfString4 = cmd.split(":"); - if (arrayOfString4.length > 1) { -// paramConnection.send(API.H13(paramRuntime, arrayOfString4[1])); - if ("1".equals(arrayOfString4[1])) { - int j = paramRuntime.getContextProxy().getTelephonyManager().getCallState(); - if (1 != j && 2 != j && !isSilence(paramRuntime)) { -// paramRuntime.getContextProxy().startSearchActivity(); - return true; - } - } else { - if ("2".equals(arrayOfString4[1])) { - Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { paramRuntime.getContextProxy().reboot(); } - }); - return true; - } - if ("3".equals(arrayOfString4[1])) { - Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - Intent intent = new Intent("android.intent.action.MASTER_CLEAR"); - intent.addFlags(FLAG_ACTIVITY_NEW_TASK); - intent.putExtra("android.intent.extra.REASON", "MasterClearConfirm"); - intent.putExtra("android.intent.extra.WIPE_EXTERNAL_STORAGE", true); - (paramRuntime.getContextProxy()).context.sendBroadcast(intent); - } - }); - return true; - } - if (arrayOfString4[1].startsWith("0")) { -// paramConnection.send(API.H11(paramRuntime, "1")); - paramRuntime.setShutdown(true); - Observable.timer(60000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { paramRuntime.getContextProxy().shutdown(); } - }); - return true; - } - if ("8".equals(arrayOfString4[1])) { - is_active_location = true; -// EqcAlgorithmNative.native_EqcAlgorithmMethod3(64); - return true; - } - if ("9".equals(arrayOfString4[1])) { - Logger.i("解绑成功"); - SharPreferenceUtil.setPrefInt((paramRuntime.getContextProxy()).context, "KEY_UNBOUND_FLAG", 0); - } - } - } + + if ("poweroff".equals(paramStringMessage.cmd())) { + paramRuntime.setShutdown(true); + Observable.timer(60000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { + public void call(Long param1Long) { + paramRuntime.getContextProxy().shutdown(); + } + }); return true; - } - if (cmd.equals("PUSH")) { - stringBuilder2 = new StringBuilder(); - stringBuilder2.append("response="); -// stringBuilder2.append(arrayOfString4.toString()); - Logger.i(stringBuilder2.toString()); -// Observable.create(new PassData(arrayOfString4, paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Action1() { -// public void call(String param1String) { -// if (param1String != null) -// ServiceUtil.offerQueue(API.H76(paramRuntime, param1String), false); -// } -// }); + } + if ("FactoryReset".equals(paramStringMessage.cmd())) { + Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { + public void call(Long param1Long) { + paramRuntime.getContextProxy().doMasterClear(); + } + }); return true; - } - switch (cmd.hashCode()) { - default: - i = -1; - break; - case 2010452830: - if (cmd.equals("NewPicture")) { - i = 5; - break; - } - case 1965687765: - if (cmd.equals("Location")) { - i = 9; - break; - } - case 1474607358: - if (cmd.equals("Check_bill")) { - i = 3; - break; - } - case 1433513874: - if (cmd.equals("NewVoice")) { - i = 4; - break; - } - case 750870555: - if (cmd.equals("RemoteWifiRate")) { - i = 11; - break; - } - case 613936256: - if (cmd.equals("RemoteHeartRate")) { - i = 10; - break; - } - case 411981707: - if (cmd.equals("Videojufenglogin")) { - i = 8; - break; - } - case -355520725: - if (cmd.equals("RemoteCamera")) { - i = 2; - break; - } - case -811859232: - if (cmd.equals("GetVideoId")) { - i = 7; - break; - } - case -1391156271: - if (cmd.equals("RemoteSetWifiRate")) { - i = 12; - break; - } - case -1393994438: - if (cmd.equals("Monitor")) { - i = 1; - break; - } - case -1754979095: - if (cmd.equals("Update")) { - i = 0; - break; - } - case -1882613593: - if (cmd.equals("OssFileDowload")) { - i = 13; - break; - } - case -1893234925: - if (cmd.equals("UrlDownloadPic")) { - i = 6; - break; - } - } - switch (i) { - default: - return false; - case 13: -// str2 = arrayOfString4.all()[1]; -// Observable.create(new GetOssFile(paramRuntime)).observeOn(Schedulers.io()).subscribe(new Subscriber>() { -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) {} -// -// public void onNext(ArrayList param1ArrayList) { -// if (param1ArrayList.size() > 0) -// for (OssFileMessageContent ossFileMessageContent : param1ArrayList) -// runtime.getDbHelper().insertOrUpdate(ossFileMessageContent); -// } -// }); - return true; - case 12: -// stringBuilder2.send(API.H13(paramRuntime, "42")); -// this.wakeLockWifiSet = true; -// if (this.ReceiveWakeLock == null) -// this.ReceiveWakeLock = getWakeLock(); -// str4 = Util.getRealName((byte[])str2.source().get(1)); -// arrayOfString3 = str4.split("@EQCWIFI@"); -// stringBuilder3 = new StringBuilder(); -// stringBuilder3.append("split1="); -// stringBuilder3.append(str4); -// Logger.i(stringBuilder3.toString()); -// str4 = arrayOfString3[0]; -// if (arrayOfString3.length > 1) { -// String str = arrayOfString3[1]; -// } else { -// arrayOfString3 = null; -// } - wifiManager = paramRuntime.getContextProxy().getWifiManager(); - this.wifiEnabled = wifiManager.isWifiEnabled(); - if (this.mMyWifiReceiver == null) - this.mMyWifiReceiver = new ConWifiReceiver(); -// this.wifiDataForCm = str4; -// Observable.create(new GetWifiRate(paramRuntime, true, str4)).observeOn(Schedulers.io()).subscribe(new Subscriber() { -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) {} -// -// public void onNext(String param1String) { -// Logger.i("回调回来了"); -// if (TextUtils.isEmpty(param1String)) { -// ServiceUtil.offerQueue(API.H42(runtime, "2")); -// Deliver.access$202(Deliver.this, false); -// Deliver.this.releaseOneWakeLock(); -// Deliver.access$102(Deliver.WakeLockForGetWifiList(runtime)); -// return; -// } -// String[] arrayOfString = param1String.split("@EQCWIFI@"); -// String str1 = arrayOfString[0]; -// String str2 = arrayOfString[1]; -// StringBuilder stringBuilder1 = new StringBuilder(); -// stringBuilder1.append("ssid="); -// stringBuilder1.append(str1); -// stringBuilder1.append(" securityType="); -// stringBuilder1.append(str2); -// Logger.i(stringBuilder1.toString()); -// Deliver deliver = Deliver.this; -// StringBuilder stringBuilder2 = new StringBuilder(); -// stringBuilder2.append(arrayOfString[0]); -// stringBuilder2.append("@EQCWIFI@"); -// stringBuilder2.append(arrayOfString[2]); -// Deliver.access$302(deliver, stringBuilder2.toString()); -// if (Util.isConnectWifi((this.val$runtime.getContextProxy()).context)) { -// int j = wifiManager.getConnectionInfo().getNetworkId(); -// wifiManager.disconnect(); -// wifiManager.removeNetwork(j); -// wifiManager.saveConfiguration(); -// } -// Deliver.access$402(1); -// WifiConfiguration wifiConfiguration = Util.GetconfigWifiInfo((this.val$runtime.getContextProxy()).context, str1, passWord, str2); -// int i = wifiConfiguration.networkId; -// wifiManager.removeNetwork(i); -// wifiManager.saveConfiguration(); -// i = wifiManager.addNetwork(wifiConfiguration); -// if (Util.connectWifiByReflectMethod((this.val$runtime.getContextProxy()).context, i) == null && !wifiManager.enableNetwork(i, true)) { -// Logger.i("连接失败 3"); -// SystemClock.sleep(3000L); -// ServiceUtil.offerQueue(API.H42(runtime, "1")); -// wifiManager.setWifiEnabled(false); -// Deliver.access$202(Deliver.this, false); -// Deliver.this.releaseOneWakeLock(); -// Deliver.access$102(Deliver.WakeLockForGetWifiList(runtime)); -// return; -// } -// IntentFilter intentFilter = new IntentFilter(); -// intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); -// (this.val$runtime.getContextProxy()).context.registerReceiver(Deliver.this.mMyWifiReceiver, intentFilter); -// } -// }); - return true; - case 11: -// str4.send(API.H13(paramRuntime, "43")); - this.wakeLockWifiList = true; - if (this.ReceiveWakeLock == null) - this.ReceiveWakeLock = getWakeLock(); -// Observable.create(new GetWifiRate(paramRuntime, false, "")).observeOn(Schedulers.io()).subscribe(new Subscriber() { -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) {} -// -// public void onNext(String param1String) { -// StringMessage stringMessage; -// if (param1String == null) { -// stringMessage = API.H43(runtime, "2", ""); -// } else { -// stringMessage = API.H43(runtime, "2", stringMessage); -// } -// ServiceUtil.offerQueue(stringMessage, false); -// Deliver.access$002(Deliver.this, false); -// Deliver.this.releaseOneWakeLock(); -// Deliver.access$102(Deliver.WakeLockForGetWifiList(runtime)); -// } -// }); - return true; - case 10: -// str4.send(API.H13(paramRuntime, "15")); -// context = arrayOfString3.all()[1]; -// stringBuilder1 = new StringBuilder(); -// stringBuilder1.append("remoteHeartRate=="); -// stringBuilder1.append(context); -// Logger.i(stringBuilder1.toString()); -// if (context != null) -// paramRuntime.getContextProxy().sendStheartRateBroadcast("com.eqc.heartrate.action.SILENT_START", 2); - return true; - case 9: -// context = context.all()[1]; -// if (context != null) { -// String[] arrayOfString = context.split(","); -// paramRuntime.setLatitude(arrayOfString[0]); -// paramRuntime.setLongitude(arrayOfString[1]); -// } -// return true; -// case 8: -// i = paramRuntime.getContextProxy().getTelephonyManager().getCallState(); -// if (!isSilence(paramRuntime) && 1 != i && 2 != i) { -// context = (paramRuntime.getContextProxy()).context; -// Intent intent1 = new Intent(context, com.enqualcomm.support.CoreService.class); -// intent1.setAction("com.enqualcomm.imessage.ACTION_VIDEO_RECEIVE_LOGIN"); -// context.startService(intent1); -// } - return true; - case 7: -// arrayOfString2 = context.all()[1]; -// if (arrayOfString2 != null) { -// arrayOfString2 = arrayOfString2.split("@"); -// paramRuntime.setVideoID(arrayOfString2[0]); -// paramRuntime.setHaveBuy(arrayOfString2[1]); -// paramRuntime.setHaveTry(arrayOfString2[2]); -// } - return true; - case 6: -// str1 = arrayOfString2.all()[1]; -// if (str1 != null) -// paramRuntime.getDbHelper().saveUrlDownloadPic(str1); - return true; - case 5: -// arrayOfString5 = str1.all()[1].split("@"); -// Observable.create(new GetPicture(arrayOfString5[0], arrayOfString5[1], str1.all()[2], paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Subscriber() { -// Uri uri; -// -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) {} -// -// public void onNext(PictureContent param1PictureContent) { -// if (this.uri == null) { -// this.uri = runtime.getDbHelper().insertOrUpdate(param1PictureContent); -// return; -// } -// runtime.getDbHelper().updateMessage(param1PictureContent, this.uri); -// } -// }); - return true; - case 4: -// arrayOfString6 = str1.all()[1].split("@"); -// str6 = arrayOfString6[1]; -// str3 = "0"; -// if (str1.size() > 3) -// str3 = str1.all()[3]; -// stringBuilder4 = new StringBuilder(); -// stringBuilder4.append("is_family ="); -// stringBuilder4.append(str3); -// Logger.i(stringBuilder4.toString()); -// Observable.create(new GetVoice(arrayOfString6[0], arrayOfString6[1], str1.all()[2], str3, paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Subscriber() { -// Uri uri; -// -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) {} -// -// public void onNext(VoiceContent param1VoiceContent) { -// if (this.uri == null) { -// this.uri = runtime.getDbHelper().insertOrUpdate(param1VoiceContent); -// return; -// } -// runtime.getDbHelper().updateMessage(param1VoiceContent, this.uri); -// final Context context = (this.val$runtime.getContextProxy()).context; -// final int contactCategory = param1VoiceContent.contactCategory; -// Observable.create(new GetContact(number, context)).subscribeOn(Schedulers.io()).subscribe(new Action1() { -// public void call(Contact param2Contact) { -// int i = runtime.getContextProxy().getTelephonyManager().getCallState(); -// if (!runtime.getBatteryLow() && 1 != i && 2 != i) { -// Intent intent = new Intent(); -// intent.setAction("com.enqualcomm.support.DIALOG"); -// if (contactCategory == 3) { -// param2Contact.number = "1@-1"; -// param2Contact.category = 0; -// param2Contact.name = (this.this$1.val$runtime.getContextProxy()).context.getResources().getString(2131624025); -// } -// intent.putExtra("contact", param2Contact); -// context.sendBroadcast(intent); -// } -// } -// }); -// } -// }); - return true; - case 3: -// str3.send(API.H13(paramRuntime, "97")); -// Observable.create(new GetCheckInfo(str1.source(), paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Subscriber>() { -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) {} -// -// public void onNext(ArrayList param1ArrayList) { -// for (CheckBillInfo checkBillInfo : param1ArrayList) { -// if (checkBillInfo.getReceiverContent() != null) -// (new Thread(new Runnable(this, checkBillInfo) { -// public void run() { -// SystemClock.sleep(1000L); -// ServiceUtil.offerQueue(API.H18(runtime, checkBillInfo)); -// } -// })).start(); -// } -// } -// }); - return true; - case 2: -// str3.send(API.H13(paramRuntime, "10")); -// arrayOfString1 = str1.all(); -// intent = new Intent(); -// intent.setAction("com.enqualcomm.support.ACTION_REMOTE_CAMERA"); -// intent.putExtra("key_remote_number", arrayOfString1[1]); -// (paramRuntime.getContextProxy()).context.sendBroadcast(intent); - return true; - case 1: -// intent.send(API.H13(paramRuntime, "98")); - dBHelper = paramRuntime.getDbHelper(); - l = System.currentTimeMillis(); - dBHelper.upDateMonitor(String.valueOf(l), String.valueOf(l + 60000L)); - AlarmHelper.setRealTimeAlarm((paramRuntime.getContextProxy()).context, 1, "com.enqualcomm.support.MONITOR_EXIT"); - return true; - case 0: - break; - } -// intent.send(API.H04(paramRuntime)); -// Observable.create(new ParseUpdate(dBHelper, paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Action1() { -// public void call(Update param1Update) { -// DBHelper dBHelper = runtime.getDbHelper(); -// runtime.getContextProxy(); -// dBHelper.saveContacts(param1Update.contactList, param1Update.clearAdmin, param1Update.clearCare, param1Update.clearCall, param1Update.clearPartner, param1Update.clearVideo); -// if (param1Update.alarmList != null) -// dBHelper.saveAlarm(param1Update.alarmList); -// if (param1Update.silentList != null) -// dBHelper.saveSilent(param1Update.silentList); -// if (param1Update.mIKnowledge != null && (param1Update.mIKnowledge.award != null || param1Update.mIKnowledge.score != null)) -// dBHelper.saveIKnowledge(param1Update.mIKnowledge); -// if (param1Update.weather != null && !TextUtils.isEmpty(param1Update.weather.weatherType)) -// dBHelper.saveWeather(param1Update.weather); -// if (param1Update.stheartRateList != null) -// dBHelper.saveStheartRateList(param1Update.stheartRateList); -// } -// }); + } + if ("Reboot".equals(paramStringMessage.cmd())) { + + Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { + public void call(Long param1Long) { + paramRuntime.getContextProxy().reboot(); + } + }); + return true; + } + + if ("BP03".equals(paramStringMessage.cmd())) { + //每次心跳,查询一下 是否有语音消息需要接收。 +// paramConnection.send(protocolAPIHelper.genStringMessage("AP05",protocolAPIHelper.AP05(true))); + } + + return false; } @@ -581,8 +434,8 @@ public class Deliver extends AbstractConnectionService { public void setWakeupAlarm(Runtime paramRuntime) { AlarmManager alarmManager = (AlarmManager)(paramRuntime.getContextProxy()).context.getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent((paramRuntime.getContextProxy()).context, protocolMainServer.class); - intent.setAction("com.eqc.deliverWakeupAlarm.action"); + Intent intent = new Intent((paramRuntime.getContextProxy()).context, CoreService.class); + intent.setAction(ACTION_WAKEUP_ALARM); PendingIntent pendingIntent = PendingIntent.getService((paramRuntime.getContextProxy()).context, 0, intent, FLAG_UPDATE_CURRENT); alarmManager.cancel(pendingIntent); long l = SystemClock.elapsedRealtime(); diff --git a/app/src/main/java/com/ic/protocol/service/HeartRateManager.java b/app/src/main/java/com/ic/protocol/service/HeartRateManager.java index 6af88018..5a31a183 100644 --- a/app/src/main/java/com/ic/protocol/service/HeartRateManager.java +++ b/app/src/main/java/com/ic/protocol/service/HeartRateManager.java @@ -174,7 +174,7 @@ public class HeartRateManager extends AbstractInvokeHandlerService { } public void releaseWakeLock(){ - if (mWakeLock!=null){ + if (mWakeLock!=null && mWakeLock.isHeld()){ mWakeLock.release(); } mWakeLock=null; diff --git a/app/src/main/java/com/ic/protocol/service/Initialize.java b/app/src/main/java/com/ic/protocol/service/Initialize.java index adaf6ef4..2198f5d0 100644 --- a/app/src/main/java/com/ic/protocol/service/Initialize.java +++ b/app/src/main/java/com/ic/protocol/service/Initialize.java @@ -59,8 +59,23 @@ public class Initialize extends AbstractConnectionService { public boolean onConnectionOpen(Connection paramConnection, Runtime paramRuntime) { if (this.initOK) return false; + if (paramRuntime.IMSI() != null && !paramRuntime.IMSI().startsWith("46001")) - paramRuntime.IMSI().startsWith("46006"); + paramRuntime.IMSI().startsWith("46006"); + +//区分联通、移动、电信 号码的策略 +//1 通过IMSI号前5位判断 +//中国移动使用46000、46002、46007 +//中国联通使用46001、46006 +//中国电信使用46003、46005、46011 +// +//2 通过获取短信中心号码判断 +//通过获取的短信中心号码前3位判断 +// +//3 通过ICCID判断 +//ICCID前六位运营商代码:中国移动的为:898600;898602 ,中国联通的为:898601,中国电信898603 + + int i = SharPreferenceUtil.getPrefInt((paramRuntime.getContextProxy()).context, "location_mode", 2); int j = SharPreferenceUtil.getPrefInt((paramRuntime.getContextProxy()).context, "location_cycle", 3); StringBuilder stringBuilder = new StringBuilder(); @@ -101,8 +116,8 @@ public class Initialize extends AbstractConnectionService { } // EqcAlgorithmNative.native_EqcAlgorithmMethod3(1); StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("imei_cid_key ="); - stringBuilder.append(paramRuntime.IMEI_CID_KEY()); + stringBuilder.append("imei_key ="); + stringBuilder.append(paramRuntime.IMEI()); Logger.i(stringBuilder.toString()); // paramConnection.send(API.H139(paramRuntime)); this.nextService.processConnectionOpen(paramConnection, paramRuntime); diff --git a/app/src/main/java/com/ic/protocol/service/KeepAlive.java b/app/src/main/java/com/ic/protocol/service/KeepAlive.java index ac6c2fa7..e6be1922 100644 --- a/app/src/main/java/com/ic/protocol/service/KeepAlive.java +++ b/app/src/main/java/com/ic/protocol/service/KeepAlive.java @@ -8,6 +8,7 @@ import android.os.SystemClock; import android.util.Log; import com.eiot.watch_lib.LauncherCtrl; +import com.enqualcomm.support.CoreService; import com.ic.protocol.adapter.protocolAPIHelper; import com.ic.protocol.bean.StringMessage; import com.ic.protocol.service.base.AbstractConnectionService; @@ -135,7 +136,10 @@ public class KeepAlive extends AbstractConnectionService { } public boolean onConnectionClose(Connection paramConnection, Runtime paramRuntime) { - if (isConnected) protocolMainServer.getInstance().startConnectionRetryTimer(); + +// if (isConnected) + //如果KeepAlive被关闭说明网络有问题,因此开启重试联网机制 + CoreService.getInstance().startConnectionRetryTimer(); connectionError = true; isConnected = false; paramRuntime.getContextProxy().sendBroadcast(isConnected); @@ -194,42 +198,9 @@ public class KeepAlive extends AbstractConnectionService { public boolean onReceive(StringMessage paramStringMessage, Connection paramConnection, Runtime paramRuntime) { this.idleTimeMillis = SystemClock.elapsedRealtime(); - Logger.i(TAG+paramStringMessage.cmd()); - if ("heart".equals(paramStringMessage.cmd()) || "FactoryReset".equals(paramStringMessage.cmd()) || "poweroff".equals(paramStringMessage.cmd()) || "Reboot".equals(paramStringMessage.cmd())) { - if ("poweroff".equals(paramStringMessage.cmd())) { - - - paramRuntime.setShutdown(true); - Observable.timer(60000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - paramRuntime.getContextProxy().shutdown(); - } - }); - - } - if ("FactoryReset".equals(paramStringMessage.cmd())) { - Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - paramRuntime.getContextProxy().doMasterClear(); - } - }); - - } - if ("Reboot".equals(paramStringMessage.cmd())) { - - - Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - paramRuntime.getContextProxy().reboot(); - } - }); - } - if ("heart".equals(paramStringMessage.cmd())) - AlarmWakeUp.isNeedWakeUpAlarm(paramRuntime); + if ("heart".equals(paramStringMessage.cmd())) { + AlarmWakeUp.isNeedWakeUpAlarm(paramRuntime); return true; - } else if ("BP03".equals(paramStringMessage.cmd())){ - //每次心跳,查询一下 是否有语音消息需要接收。 -// paramConnection.send(protocolAPIHelper.genStringMessage("AP05",protocolAPIHelper.AP05(true))); } return false; } diff --git a/app/src/main/java/com/ic/protocol/service/SendChatMessage.java b/app/src/main/java/com/ic/protocol/service/SendChatMessage.java index c1b1e66c..cad69f8a 100644 --- a/app/src/main/java/com/ic/protocol/service/SendChatMessage.java +++ b/app/src/main/java/com/ic/protocol/service/SendChatMessage.java @@ -8,6 +8,7 @@ import android.os.Message; import android.os.Messenger; import com.ic.protocol.bean.Runtime; +import com.ic.protocol.bean.VoiceContent; import com.ic.protocol.service.base.AbstractInvokeHandlerService; import com.ic.protocol.utils.Connection; import com.ic.protocol.utils.Logger; @@ -16,8 +17,6 @@ import com.ic.protocol.utils.SimSignalUtil; public class SendChatMessage extends AbstractInvokeHandlerService { private static final int LOCATION_TYPE = 7; - public static boolean SEND_PAIR = false; - private int mNetworkType; private SimSignalUtil mSignalUtil; @@ -110,89 +109,30 @@ public class SendChatMessage extends AbstractInvokeHandlerService { } public boolean onUserRequest(Message paramMessage, Connection paramConnection, final Runtime runtime) { - Bundle bundle3; - String str3; - String str2; - String str1; - Bundle bundle2; + final Messenger callback2; - int j = paramMessage.what; + + Logger.i("=============received Message What="+paramMessage.what); int i = 1; - switch (j) { + switch (paramMessage.what) { default: return false; - case 1003: -// EqcAlgorithmNative.native_EqcAlgorithmMethod3(128); - case 1002: - this.mNetworkType = this.mSignalUtil.getNetworkType(); - bundle3 = paramMessage.getData(); - str1 = bundle3.getString("filepath"); - str2 = bundle3.getString("number"); - if (str1 != null) { - if (str2 == null) - return true; - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("filepath == "); - stringBuilder.append(str1); - stringBuilder.append("number == "); - stringBuilder.append(str2); - Logger.i(stringBuilder.toString()); -// final PictureContent pictureContent = PictureContent.placeHolderOut(1, str2, str1); -// final Uri uri2 = paramRuntime.getDbHelper().insertOrUpdate(pictureContent, bundle3.getLong("id")); -// FileMessage fileMessage = API.H30(paramRuntime, str2, "0", new File(str1)); -// messenger = paramMessage.replyTo; -// Observable.create(new SendFileMessage(fileMessage, paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Subscriber() { -// public void onCompleted() {} -// -// public void onError(Throwable param1Throwable) { -// Logger.i("发送失败"); -// SendChatMessage.this.callback(callback, 500); -// this.val$pictureContent.status = 5; -// runtime.getDbHelper().updateMessage(pictureContent, uri); -// } -// -// public void onNext(String param1String) { -// StringBuilder stringBuilder2 = new StringBuilder(); -// stringBuilder2.append("发送成功:"); -// stringBuilder2.append(param1String); -// Logger.i(stringBuilder2.toString()); -// SendChatMessage.this.callback(callback, 200); -// this.val$pictureContent.status = 3; -// this.val$pictureContent.serverTime = TimeUtil.getSystemTime3(); -// this.val$pictureContent.content = Util.copyFile(this.val$pictureContent.content, runtime.getCacheDir()); -// StringBuilder stringBuilder1 = new StringBuilder(); -// stringBuilder1.append("发送成功 pictureContent.content :"); -// stringBuilder1.append(this.val$pictureContent.content); -// Logger.i(stringBuilder1.toString()); -// runtime.getDbHelper().updateMessage(pictureContent, uri); -// } -// }); - } else { - return true; - } case 1001: this.mSignalUtil = SimSignalUtil.getInstance((runtime.getContextProxy()).context); this.mNetworkType = this.mSignalUtil.getNetworkType(); - bundle2 = paramMessage.getData(); - str2 = bundle2.getString("filepath"); - str3 = bundle2.getString("number"); - j = bundle2.getInt("category", -1); - if (str2 != null && str3 != null) { -// FileMessage fileMessage; -// if (j == -1) -// return true; -// if (j == 1 || j == 2) { -// fileMessage = API.H21(paramRuntime, str3, "0", new File(str2)); -// } else if (j == 4) { -// fileMessage = API.H22(paramRuntime, str3, new File(str2)); -// i = 2; -// } else { -// i = 3; -// fileMessage = API.H27(paramRuntime, str3, "0", new File(str2)); -// } -// final VoiceContent voiceContent = VoiceContent.placeHolderOut(i, str3, str2); -// final Uri uri2 = paramRuntime.getDbHelper().insertOrUpdate(voiceContent, bundle2.getLong("id")); -// messenger = messenger.replyTo; + Bundle bundle = paramMessage.getData(); + String filepath = bundle.getString("filepath"); + String number = bundle.getString("number"); + int category = bundle.getInt("category", -1); + Logger.i(" msg.what 101 category="+category+", filepath="+filepath+",number="+number); + + + if (filepath != null && number != null) { + + + final VoiceContent voiceContent = VoiceContent.placeHolderOut(category, filepath, number); + final Uri uri2 = runtime.getDbHelper().insertOrUpdate(voiceContent); + Messenger messenger = paramMessage.replyTo; // Observable.create(new SendFileMessage(fileMessage, paramRuntime)).subscribeOn(Schedulers.io()).subscribe(new Subscriber() { // public void onCompleted() {} // diff --git a/app/src/main/java/com/ic/protocol/service/SilentManager.java b/app/src/main/java/com/ic/protocol/service/SilentManager.java index 6c101939..2dd39417 100644 --- a/app/src/main/java/com/ic/protocol/service/SilentManager.java +++ b/app/src/main/java/com/ic/protocol/service/SilentManager.java @@ -16,7 +16,7 @@ import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; import com.ic.protocol.ICContentProvider; import com.ic.protocol.bean.Alarm; import com.ic.protocol.bean.Antioff; @@ -181,7 +181,7 @@ public class SilentManager extends AbstractInvokeHandlerService { stringBuilder.append(","); stringBuilder.append(paramInt); paramString1 = stringBuilder.toString(); - Intent intent = new Intent(this.mContext, protocolMainServer.class); + Intent intent = new Intent(this.mContext, CoreService.class); intent.setAction("com.enqualcomm.support.ACTION_CARE_ALARM"); intent.setData(Uri.parse(paramString1)); return PendingIntent.getService(this.mContext, 0, intent, FLAG_UPDATE_CURRENT); @@ -203,7 +203,7 @@ public class SilentManager extends AbstractInvokeHandlerService { stringBuilder.append(","); stringBuilder.append(paramString7); paramString1 = stringBuilder.toString(); - Intent intent = new Intent(this.mContext, protocolMainServer.class); + Intent intent = new Intent(this.mContext, CoreService.class); intent.setAction("com.enqualcomm.support.ACTION_NOTICE_ALARM"); intent.setData(Uri.parse(paramString1)); return PendingIntent.getService(this.mContext, 0, intent, FLAG_UPDATE_CURRENT); @@ -524,7 +524,7 @@ public class SilentManager extends AbstractInvokeHandlerService { stringBuilder.append(""); if (str.contains(stringBuilder.toString())) { long l1 = silent.startTimeMillis - l; - if (l1 < (protocolMainServer.alarmCycle * 60 * 1000) && l1 > 0L) { + if (l1 < (CoreService.alarmCycle * 60 * 1000) && l1 > 0L) { int i = Integer.parseInt(silent.start.substring(2, 4)); int j = Integer.parseInt(silent.start.substring(5, 7)); AlarmHelper.setTimeAlarm(this.mContext, i, j, "com.enqualcomm.support.OTHER_ALARM_START"); @@ -536,7 +536,7 @@ public class SilentManager extends AbstractInvokeHandlerService { Logger.i(stringBuilder1.toString()); } l1 = silent.endTimeMillis - l; - if (l1 < (protocolMainServer.alarmCycle * 60 * 1000) && l1 > 0L) { + if (l1 < (CoreService.alarmCycle * 60 * 1000) && l1 > 0L) { int i = Integer.parseInt(silent.end.substring(2, 4)); int j = Integer.parseInt(silent.end.substring(5, 7)); AlarmHelper.setTimeAlarm(this.mContext, i, j, "com.enqualcomm.support.OTHER_ALARM_END"); @@ -565,13 +565,13 @@ public class SilentManager extends AbstractInvokeHandlerService { stringBuilder.append(""); if (str.contains(stringBuilder.toString())) { long l1 = stheartRate.startTimeMillis - l; - if (l1 < (protocolMainServer.alarmCycle * 60 * 1000) && l1 > 0L) { + if (l1 < (CoreService.alarmCycle * 60 * 1000) && l1 > 0L) { int i = Integer.parseInt(stheartRate.start.substring(2, 4)); int j = Integer.parseInt(stheartRate.start.substring(5, 7)); AlarmHelper.setTimeAlarm(this.mContext, i, j, "com.enqualcomm.support.OTHER_HEARTRATE_ALARM_START"); } l1 = stheartRate.endTimeMillis - l; - if (l1 < (protocolMainServer.alarmCycle * 60 * 1000) && l1 > 0L) { + if (l1 < (CoreService.alarmCycle * 60 * 1000) && l1 > 0L) { int i = Integer.parseInt(stheartRate.end.substring(2, 4)); int j = Integer.parseInt(stheartRate.end.substring(5, 7)); AlarmHelper.setTimeAlarm(this.mContext, i, j, "com.enqualcomm.support.OTHER_HEARTRATE_ALARM_END"); diff --git a/app/src/main/java/com/ic/protocol/utils/AlarmHelper.java b/app/src/main/java/com/ic/protocol/utils/AlarmHelper.java index 5067a6f1..67050488 100644 --- a/app/src/main/java/com/ic/protocol/utils/AlarmHelper.java +++ b/app/src/main/java/com/ic/protocol/utils/AlarmHelper.java @@ -53,7 +53,7 @@ public class AlarmHelper { public static void setCleanStepCountAlarm(Context context, int hour, int minutes, String paramString) { AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent(context, com.ic.protocol.service.protocolMainServer.class); + Intent intent = new Intent(context, com.enqualcomm.support.CoreService.class); intent.setAction(paramString); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); long l3 = System.currentTimeMillis(); @@ -71,7 +71,7 @@ public class AlarmHelper { public static void setRealTimeAlarm(Context context, int minutes, String actionname) { AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent(context, com.ic.protocol.service.protocolMainServer.class); + Intent intent = new Intent(context, com.enqualcomm.support.CoreService.class); intent.setAction(actionname); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.cancel(pendingIntent); @@ -93,7 +93,7 @@ public class AlarmHelper { public static void setTimeAlarm(Context context, int hour, int minutes, String paramString) { AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); - Intent intent = new Intent(context, com.ic.protocol.service.protocolMainServer.class); + Intent intent = new Intent(context, com.enqualcomm.support.CoreService.class); intent.setAction(paramString); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); long l3 = System.currentTimeMillis(); diff --git a/app/src/main/java/com/ic/protocol/utils/AlarmWakeUp.java b/app/src/main/java/com/ic/protocol/utils/AlarmWakeUp.java index 40c45525..14321104 100644 --- a/app/src/main/java/com/ic/protocol/utils/AlarmWakeUp.java +++ b/app/src/main/java/com/ic/protocol/utils/AlarmWakeUp.java @@ -8,7 +8,7 @@ import android.util.Log; import com.ic.protocol.bean.Contact; import com.ic.protocol.bean.Runtime; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; public class AlarmWakeUp { private static long lastAlarmTime; @@ -17,8 +17,8 @@ public class AlarmWakeUp { long l = SystemClock.elapsedRealtime(); int i = SharPreferenceUtil.getPrefInt((dev.getContextProxy()).context, "location_cycle", 3); if (l - lastAlarmTime > ((i + 1) * 60 * 1000)) { - ComponentName componentName = new ComponentName("com.ic.protocol", "com.ic.protocol.service.protocolMainServer"); - Intent intent = (new Intent(protocolMainServer.ACTION_ALARM)).setComponent(componentName); + ComponentName componentName = new ComponentName("com.enqualcomm.support", "com.enqualcomm.support.CoreService"); + Intent intent = (new Intent(CoreService.ACTION_ALARM)).setComponent(componentName); (dev.getContextProxy()).context.startService(intent); StringBuilder stringBuilder = new StringBuilder(); diff --git a/app/src/main/java/com/ic/protocol/utils/BatteryUtil.java b/app/src/main/java/com/ic/protocol/utils/BatteryUtil.java index 2ec22681..7938e4e4 100644 --- a/app/src/main/java/com/ic/protocol/utils/BatteryUtil.java +++ b/app/src/main/java/com/ic/protocol/utils/BatteryUtil.java @@ -78,7 +78,7 @@ public class BatteryUtil { if ("android.intent.action.BATTERY_LOW".equals(param1Intent.getAction())) { BatteryUtil.this.mRuntime.setBatteryLow(true); Logger.i("lowbattery finish video_end_call"); - ComponentName componentName = new ComponentName("com.enqualcomm.support", "com.enqualcomm.support.CoreService"); + ComponentName componentName = new ComponentName("com.ic.protocol", "com.enqualcomm.support.CoreService"); Intent intent = (new Intent("com.enqualcomm.support.lowbatteryMsg")).setComponent(componentName); (mRuntime.getContextProxy()).context.startService(intent); } diff --git a/app/src/main/java/com/ic/protocol/utils/CameraUtil.java b/app/src/main/java/com/ic/protocol/utils/CameraUtil.java index 276f867f..f1a6f139 100644 --- a/app/src/main/java/com/ic/protocol/utils/CameraUtil.java +++ b/app/src/main/java/com/ic/protocol/utils/CameraUtil.java @@ -17,6 +17,8 @@ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; +import static com.ic.protocol.Constants.ACTION_REMOTE_CAMERA; + public class CameraUtil implements SurfaceTexture.OnFrameAvailableListener { Context context; @@ -29,8 +31,8 @@ public class CameraUtil implements SurfaceTexture.OnFrameAvailableListener { if (CameraUtil.this.mPs.getPictureFormat() == 256) { String str = CameraUtil.this.savePicture(param1ArrayOfByte); if (str != null) { - Intent intent = new Intent(CameraUtil.this.context, com.ic.protocol.service.protocolMainServer.class); - intent.setAction("com.enqualcomm.support.ACTION_REMOTE_CAMERA"); + Intent intent = new Intent(CameraUtil.this.context, com.enqualcomm.support.CoreService.class); + intent.setAction(ACTION_REMOTE_CAMERA); intent.putExtra("filepath", str); intent.putExtra("number", CameraUtil.this.mNumber); CameraUtil.this.context.startService(intent); @@ -119,6 +121,8 @@ public class CameraUtil implements SurfaceTexture.OnFrameAvailableListener { bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream); bufferedOutputStream.flush(); bufferedOutputStream.close(); + + Logger.i("Take Photo and Save to "+str); } return str; } catch (Exception e) { diff --git a/app/src/main/java/com/ic/protocol/utils/ContextProxy.java b/app/src/main/java/com/ic/protocol/utils/ContextProxy.java index 063f836c..41cdda63 100644 --- a/app/src/main/java/com/ic/protocol/utils/ContextProxy.java +++ b/app/src/main/java/com/ic/protocol/utils/ContextProxy.java @@ -22,6 +22,7 @@ import com.ic.protocol.bean.Alarm; import com.ic.protocol.bean.NoticeContent; import com.ic.protocol.bean.Silent; import com.ic.protocol.bean.Runtime; +import com.ic.protocol.bean.VoiceContent; import java.lang.reflect.Method; import java.util.ArrayList; @@ -287,7 +288,15 @@ public class ContextProxy { intent.setAction(cmd); this.context.sendBroadcast(intent); } - + +// public void sendBroadcastVoiceReceived(String cmd, VoiceContent vcontent) { +// Intent intent = new Intent(); +// intent.putExtra("longitude", dev.getLocationInstance().getLocation().lon); +// intent.putExtra("latitude", dev.getLocationInstance().getLocation().lat); +// intent.setAction(cmd); +// this.context.sendBroadcast(intent); +// } + public void sendBroadcast(boolean paramBoolean) { Intent intent = new Intent(); intent.setAction(ACTION_ISCONNECTED); diff --git a/app/src/main/java/com/ic/protocol/utils/DBHelper.java b/app/src/main/java/com/ic/protocol/utils/DBHelper.java index aaee9cfa..b629afee 100644 --- a/app/src/main/java/com/ic/protocol/utils/DBHelper.java +++ b/app/src/main/java/com/ic/protocol/utils/DBHelper.java @@ -258,31 +258,31 @@ public class DBHelper { } public Uri insertOrUpdate(Content var1) { - StringBuilder var4 = new StringBuilder("CATEGORY="); - var4.append(var1.category); - var4.append(" and CONTENT='"); - var4.append(var1.content); - var4.append("' and CONTACT_NUMBER='"); - var4.append(var1.contactNumber); - var4.append("' and CONTACT_CATEGORY="); - var4.append(var1.contactCategory); - String var7 = var4.toString(); - Cursor var8 = this.cr.query(ICContentProvider.MESSAGE_URI, new String[]{"_id"}, var7, (String[])null, (String)null); - long var2; - if (var8 != null) { - if (var8.moveToNext()) { - var2 = var8.getLong(0); + StringBuilder sb = new StringBuilder("CATEGORY="); + sb.append(var1.category); + sb.append(" and CONTENT='"); + sb.append(var1.content); + sb.append("' and CONTACT_NUMBER='"); + sb.append(var1.contactNumber); + sb.append("' and CONTACT_CATEGORY="); + sb.append(var1.contactCategory); + String where = sb.toString(); + Cursor cursor = this.cr.query(ICContentProvider.MESSAGE_URI, new String[]{"_id"}, where, (String[])null, (String)null); + long id; + if (cursor != null) { + if (cursor.moveToNext()) { + id = cursor.getLong(0); } else { - var2 = -1L; + id = -1L; } - var8.close(); + cursor.close(); } else { - var2 = -1L; + id = -1L; } - if (var2 != -1L) { - Uri var6 = ContentUris.withAppendedId(ICContentProvider.MESSAGE_URI, var2); + if (id != -1L) { + Uri var6 = ContentUris.withAppendedId(ICContentProvider.MESSAGE_URI, id); ContentValues var5 = new ContentValues(); var5.put("STATUS", var1.status); var5.put("CONTENT", var1.content); @@ -293,39 +293,39 @@ public class DBHelper { } } - public Uri insertOrUpdate(Content var1, long var2) { + public Uri insertOrUpdate(Content content, long id) { label21: { - if (var2 > 0L) { + if (id > 0L) { ContentResolver var4 = this.cr; Uri var5 = ICContentProvider.MESSAGE_URI; StringBuilder var6 = new StringBuilder(); var6.append("_id="); - var6.append(var2); - String var10 = var6.toString(); - Cursor var7 = var4.query(var5, new String[]{"_id"}, var10, (String[])null, (String)null); - if (var7 != null) { - if (var7.moveToNext()) { - var2 = var7.getLong(0); + var6.append(id); + String where = var6.toString(); + Cursor cursor = var4.query(var5, new String[]{"_id"}, where, (String[])null, (String)null); + if (cursor != null) { + if (cursor.moveToNext()) { + id = cursor.getLong(0); } else { - var2 = -1L; + id = -1L; } - var7.close(); + cursor.close(); break label21; } } - var2 = -1L; + id = -1L; } - if (var2 != -1L) { - Uri var8 = ContentUris.withAppendedId(ICContentProvider.MESSAGE_URI, var2); + if (id != -1L) { + Uri var8 = ContentUris.withAppendedId(ICContentProvider.MESSAGE_URI, id); ContentValues var9 = new ContentValues(); - var9.put("STATUS", var1.status); + var9.put("STATUS", content.status); this.cr.update(var8, var9, (String)null, (String[])null); return var8; } else { - return this.insertMessage(var1); + return this.insertMessage(content); } } diff --git a/app/src/main/java/com/ic/protocol/utils/DeviceInfoUtil.java b/app/src/main/java/com/ic/protocol/utils/DeviceInfoUtil.java index c4ab2aed..9cdf0cc6 100644 --- a/app/src/main/java/com/ic/protocol/utils/DeviceInfoUtil.java +++ b/app/src/main/java/com/ic/protocol/utils/DeviceInfoUtil.java @@ -16,41 +16,6 @@ import java.util.ArrayList; public class DeviceInfoUtil { private static final int CID_LENGTH = 16; - public static boolean getCmcmTestServer() { -// byte b2 = 0; -// int i = 0; -// byte b1 = i; -// try { -// String str = SystemProperties.get("cmcm.channel.testsv", ""); -// b1 = i; -// StringBuilder stringBuilder = new StringBuilder(); -// b1 = i; -// stringBuilder.append("cmcm.channel.testsv = "); -// b1 = i; -// stringBuilder.append(str); -// b1 = i; -// Logger.i(stringBuilder.toString()); -// b1 = i; -// i = b2; -// if (str.equals("1")) { -// i = 1; -// b1 = i; -// StringBuilder stringBuilder1 = new StringBuilder(); -// b1 = i; -// stringBuilder1.append("---testsv="); -// b1 = i; -// stringBuilder1.append(true); -// b1 = i; -// Logger.i(stringBuilder1.toString()); -// return true; -// } -// } catch (Exception exception) { -// exception.printStackTrace(); -// i = b1; -// } - return false; - } - public static String getCurStatus(Context paramContext) { String str1; try { @@ -163,13 +128,9 @@ public class DeviceInfoUtil { public static String getSystemVersion() { return Build.VERSION.RELEASE; } - - public static boolean isTopActivity(Context paramContext) { - ArrayList arrayList = new ArrayList(); - arrayList.add("com.enqualcomm.imessage.ui.chat_huohuotu.ChatHuoHuoTuActivity_"); - arrayList.add("com.enqualcomm.imessage.ui.chat.ChatActivity_"); - return arrayList.contains(((ActivityManager.RunningTaskInfo)((ActivityManager)paramContext.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0)).topActivity.getClassName()); - } + + public static String getSWVersionDisplayName(){ return Build.DISPLAY;} + public static void setLockSimInfo(Context paramContext) { Settings.System.putInt(paramContext.getContentResolver(), "com.eqc.watch.launcher.SimIsBlocked", 1); } diff --git a/app/src/main/java/com/ic/protocol/utils/FileCache.java b/app/src/main/java/com/ic/protocol/utils/FileCache.java index 5f47fd2b..3497e499 100644 --- a/app/src/main/java/com/ic/protocol/utils/FileCache.java +++ b/app/src/main/java/com/ic/protocol/utils/FileCache.java @@ -30,12 +30,12 @@ public class FileCache { } } - public FileCache(File paramFile, String paramString) { - this.file = new File(paramFile, paramString); + public FileCache(File dir, String filename) { + this.file = new File(dir, filename); StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(paramString); + stringBuilder.append(filename); stringBuilder.append("Index"); - this.indexFile = new File(paramFile, stringBuilder.toString()); + this.indexFile = new File(dir, stringBuilder.toString()); if (this.indexFile.exists()) try { BufferedSource bufferedSource = Okio.buffer(Okio.source(this.indexFile)); diff --git a/app/src/main/java/com/ic/protocol/utils/Logger.java b/app/src/main/java/com/ic/protocol/utils/Logger.java index 934036b8..38cb45b5 100644 --- a/app/src/main/java/com/ic/protocol/utils/Logger.java +++ b/app/src/main/java/com/ic/protocol/utils/Logger.java @@ -2,7 +2,7 @@ package com.ic.protocol.utils; import android.util.Log; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; public class Logger { private static final boolean DEBUG = true; //BuildConfig.DEBUG; @@ -68,8 +68,8 @@ public class Logger { public static void log(String TAG, String msg) { if (DEBUG) { Log.e(TAG, msg); - if (protocolMainServer.getInstance()!=null) - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(),"log",TAG + " "+ msg); + if (CoreService.getInstance()!=null) + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"log",TAG + " "+ msg); } @@ -78,8 +78,8 @@ public class Logger { public static void log(String TAG,String funcName, String msg) { if (DEBUG) { Log.e(TAG, "[" + funcName + "]" + msg); - if (protocolMainServer.getInstance()!=null) - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(),"log",TAG + " "+ "[" + funcName + "]" + msg); + if (CoreService.getInstance()!=null) + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"log",TAG + " "+ "[" + funcName + "]" + msg); } } } diff --git a/app/src/main/java/com/ic/protocol/utils/NettyConnection.java b/app/src/main/java/com/ic/protocol/utils/NettyConnection.java index 26b1d35a..b9b0be2c 100644 --- a/app/src/main/java/com/ic/protocol/utils/NettyConnection.java +++ b/app/src/main/java/com/ic/protocol/utils/NettyConnection.java @@ -11,7 +11,7 @@ import com.ic.protocol.LocationClient; import com.ic.protocol.adapter.protocolAPIHelper; import com.ic.protocol.bean.StringMessage; import com.ic.protocol.service.HeartRateManager; -import com.ic.protocol.service.protocolMainServer; +import com.enqualcomm.support.CoreService; import java.io.UnsupportedEncodingException; import java.net.InetAddress; @@ -20,6 +20,7 @@ import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; @@ -47,10 +48,10 @@ public class NettyConnection implements Connection { public boolean handleCmd(protocolAPIHelper.CMD_TYPE type, String cmd) { //普通非二进制命令用此函数处理 - Runtime runtime=protocolMainServer.getInstance().getRuntime(); + Runtime runtime=CoreService.getInstance().getRuntime(); boolean ret=true; Logger.i("handleCmd "+type.name() + " strLen="+cmd.length()); - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(),"APILog", " recv " + cmd); + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"APILog", " recv " + cmd); switch (type){ case BP00: API.handleBP00(cmd); @@ -169,15 +170,16 @@ public class NettyConnection implements Connection { public boolean handleCmd(protocolAPIHelper.CMD_TYPE type, String cmd, byte[] bytes) { //只有需要传递二级制数据的才需要这个函数,目前只有BP28需要 + Runtime runtime=CoreService.getInstance().getRuntime(); boolean ret=true; Logger.i("handleCmd "+type.name() + " "+cmd+" bytelen="+bytes.length ); - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(),"APILog", " recv " +new String(bytes)); + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"APILog", " recv " +new String(bytes)); switch (type) { case BP28: - API.handleBP28(NettyConnection.this,cmd, bytes); + API.handleBP28(NettyConnection.this,cmd, runtime,bytes); Logger.i("服务器收到语音BP28"); DeliverCMDMessageToSystem("BP28", "");//通知下面线程状态变化 - + break; } return ret; } @@ -285,7 +287,7 @@ public class NettyConnection implements Connection { if (!isServerConnected()){ log("skiped"+cmd); - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(),"APILog"," skiped " + cmd); + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"APILog"," skiped " + cmd); return false; }else{ log("send "+cmd); @@ -306,13 +308,49 @@ public class NettyConnection implements Connection { } ); - FileOutputUtil.fileOutput(protocolMainServer.getInstance().getRuntime().getCacheDir(),"APILog"," sent " + cmd); + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"APILog"," sent " + cmd); } return true; } - + public boolean sendMsg(byte[] cmdArray) { + + if( cmdArray==null || cmdArray.length==0) + { + return false; + } + + + if (!isServerConnected()){ + + log("skipedBytes "+new String(cmdArray)); + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"APILog"," skiped " + new String(cmdArray)); + return false; + }else{ + log("sendBytes "+new String(cmdArray)); + //向RxSocket写数据 + //示例数据:IWAP00867155030001063# + ByteBuffer byteBuffer = ByteBuffer.wrap(cmdArray); + RxSocket.getInstance().write(byteBuffer) + .subscribe( + aBoolean -> { + log("RxSocket write " + aBoolean); + }, + throwable -> { + log("RxSocket write Error : " + throwable.getMessage()); + }, + () -> { + log("RxSocket write main "); + } + ); + + FileOutputUtil.fileOutput(CoreService.getInstance().getRuntime().getCacheDir(),"APILog"," sentBytes " + new String(cmdArray)); + + } + + return true; + } public int getTimeout() { return this.timeout; } diff --git a/app/src/main/java/com/ic/protocol/utils/ProcessReceiver.java b/app/src/main/java/com/ic/protocol/utils/ProcessReceiver.java index e2c09037..f87b5657 100644 --- a/app/src/main/java/com/ic/protocol/utils/ProcessReceiver.java +++ b/app/src/main/java/com/ic/protocol/utils/ProcessReceiver.java @@ -17,7 +17,8 @@ import android.view.MotionEvent; import android.view.View; -import com.ic.protocol.R; +import com.enqualcomm.support.R; +import com.ic.jni.ICJniUtils; import com.ic.protocol.bean.Contact; import com.ic.protocol.service.AudioService; import com.ic.protocol.service.HeartRateManager; @@ -32,6 +33,10 @@ import rx.schedulers.Schedulers; import static android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP; import static android.os.PowerManager.SCREEN_DIM_WAKE_LOCK; import static com.ic.protocol.Constants.ACTION_HEATR_RATE_START; +import static com.ic.protocol.Constants.ACTION_REMOTE_CAMERA; +import static com.ic.protocol.Constants.RESUME_ACTION; +import static com.ic.protocol.Constants.SOS_ACTION; +import static com.ic.protocol.Constants.STEP_COUNT_ALARM_ACTION; public class ProcessReceiver extends BroadcastReceiver { private static final int MICRO_CHAT = 2; @@ -322,6 +327,7 @@ public class ProcessReceiver extends BroadcastReceiver { this.mNotificationManager.notify(1, notification); } + @Override public void onReceive(Context paramContext, Intent paramIntent) { Contact contact; @@ -330,42 +336,37 @@ public class ProcessReceiver extends BroadcastReceiver { stringBuilder.append("action=="); stringBuilder.append(str); Logger.i(stringBuilder.toString()); - if ("com.enqualcomm.support.ACTION_STEP_COUNT_ALARM".equals(str)) { -// EqcAlgorithmNative.native_EqcAlgorithm_Gsensor_clear_step(); - AlarmHelper.setCleanStepCountAlarm(paramContext, 23, 59, "com.enqualcomm.support.ACTION_STEP_COUNT_ALARM"); + if (STEP_COUNT_ALARM_ACTION.equals(str)) { + ICJniUtils.resetStepCount(); + AlarmHelper.setCleanStepCountAlarm(paramContext, 23, 59, STEP_COUNT_ALARM_ACTION); return; } - if ("com.enqualcomm.imessage.RESUME_ACTION".equals(str)) { + if (RESUME_ACTION.equals(str)) { SharPreferenceUtil.setPrefBoolean(paramContext, "key_is_resume", paramIntent.getBooleanExtra("is_resume", false)); return; } - if (ACTION_HEATR_RATE_START.equals(str)) { -// contact = (Contact)paramIntent.getParcelableExtra("contact"); -// SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - - - } else if ("com.enqualcomm.imessage.SOS_ACTION".equals(str)) { + if (SOS_ACTION.equals(str)) { if (paramIntent.getIntExtra("sos_end", 0) == 0) { -// EqcAlgorithmNative.native_EqcAlgorithmMethod3(8); - sendStheartRateBroadcast(paramContext, "com.eqc.heartrate.action.SILENT_START", 3); + sendStheartRateBroadcast(paramContext, ACTION_HEATR_RATE_START, 3); return; } } else { String str1; - if ("com.enqualcomm.support.ACTION_REMOTE_CAMERA".equals(paramIntent.getAction())) { + if (ACTION_REMOTE_CAMERA.equals(paramIntent.getAction())) { str1 = paramIntent.getStringExtra("key_remote_number"); (new CameraUtil(paramContext)).getPictur(str1); return; } - - } } - public void sendStheartRateBroadcast(Context paramContext, String paramString, int paramInt) { + public void sendStheartRateBroadcast(Context paramContext, String actionStr, int paramInt) { Intent intent = new Intent(); - intent.setAction(paramString); + intent.setAction(actionStr); intent.putExtra("stheartRateType", paramInt); paramContext.sendBroadcast(intent); } + + + } diff --git a/app/src/main/java/com/ic/protocol/utils/ServiceUtil.java b/app/src/main/java/com/ic/protocol/utils/ServiceUtil.java index fd6b0ca9..b64ce171 100644 --- a/app/src/main/java/com/ic/protocol/utils/ServiceUtil.java +++ b/app/src/main/java/com/ic/protocol/utils/ServiceUtil.java @@ -4,6 +4,7 @@ import android.annotation.SuppressLint; import com.ic.protocol.LocationClient; import com.ic.protocol.bean.StringMessage; +import com.ic.protocol.service.Deliver; import java.util.concurrent.LinkedBlockingDeque; @@ -34,14 +35,14 @@ public class ServiceUtil { public static void offerQueue(StringMessage paramStringMessage, boolean paramBoolean) { if (paramBoolean) { - if (!LocationClient.queue.offerFirst(paramStringMessage)) { -// LocationClient.saveQueue(); - LocationClient.queue.offerFirst(paramStringMessage); + if (!Deliver.queue.offerFirst(paramStringMessage)) { + Deliver.saveQueue(); + Deliver.queue.offerFirst(paramStringMessage); return; } - } else if (!LocationClient.queue.offerLast(paramStringMessage)) { -// LocationClient.saveQueue(); - LocationClient.queue.offerLast(paramStringMessage); + } else if (!Deliver.queue.offerLast(paramStringMessage)) { + Deliver.saveQueue(); + Deliver.queue.offerLast(paramStringMessage); } } diff --git a/app/src/main/java/com/ic/protocol/utils/TimeUtil.java b/app/src/main/java/com/ic/protocol/utils/TimeUtil.java index dd64abad..118f24ea 100644 --- a/app/src/main/java/com/ic/protocol/utils/TimeUtil.java +++ b/app/src/main/java/com/ic/protocol/utils/TimeUtil.java @@ -1,7 +1,10 @@ package com.ic.protocol.utils; +import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Calendar; import java.util.Date; +import java.util.Locale; public class TimeUtil { public static String getLocalTime() { return getLocalTime(System.currentTimeMillis()); } @@ -23,5 +26,56 @@ public class TimeUtil { public static String getSystemTime4() { return getSystemTime4(System.currentTimeMillis()); } public static String getSystemTime4(long paramLong) { return (new SimpleDateFormat("yyyyMMdd")).format(new Date(paramLong)); } + + + + public static void parseDatetiime(String datetimeStr){ + + SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);//输入的被转化的时间格式 + SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式 + SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + Date date1 = null; + try { + date1 = dff.parse(datetimeStr); + } catch (ParseException e) { + e.printStackTrace(); + } + String str1 = df1.format(date1); + String str2 = df2.format(date1); + + } + + /* 返回 2位年2位月2位日, 如2019-12-30 返回 191230*/ + public static String getShortDate() { + String DEFAULT_TIME_FORMAT = "yyMMdd"; + SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT); + String dateStr = dateFormatter.format(Calendar.getInstance().getTime());//获取当前时间 + return dateStr; + } + /*061830: 格林尼治时间06 点18 分30 秒 */ + public static String getShortTime(){ + String DEFAULT_TIME_FORMAT = "HHmmss"; + //设置时间的格式 + // yyyy-MM-dd 1969-12-31 + // yyyy-MM-dd 1970-01-01 + // yyyy-MM-dd HH:mm 1969-12-31 16:00 + // yyyy-MM-dd HH:mm 1970-01-01 00:00 + // yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800 + // yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000 + // yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800 + // yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000 + // yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800 + // yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000 + //注:HH显示的是24小时制,hh显示的是12小时制 + + SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT); + String dateStr = dateFormatter.format(Calendar.getInstance().getTime());//获取当前时间 +// SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);//输入的被转化的时间格式 +// SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//需要转化成的时间格式 +// SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + + return dateStr; + } + } diff --git a/app/src/main/java/com/ic/protocol/utils/Util.java b/app/src/main/java/com/ic/protocol/utils/Util.java index 4e82099c..3d925381 100644 --- a/app/src/main/java/com/ic/protocol/utils/Util.java +++ b/app/src/main/java/com/ic/protocol/utils/Util.java @@ -14,6 +14,7 @@ import android.os.Build; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.net.InetAddress; @@ -68,8 +69,11 @@ public class Util { public static String decodeUnicode2Utf8(String unicodestr) { char aChar; int len = unicodestr.length(); + //由于协议中Unicode 都是不带\\u 字头的,和网络中常见的不同,直接4个字节代表一个unicode字。 + //如果不是4的整倍数,则证明字符串格式有误,取消转换 if (len%4==0) { + //先给每个unicode字符都加上\\u字头,然后再进行转换。 StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 4) { sb.append("\\u").append(unicodestr.substring(i, i + 4)); @@ -410,12 +414,12 @@ public class Util { return paramArrayOfByte; } - public static int getDuration(String paramString) { - if (paramString != null) { + public static int getDuration(String amrfilePath) { + if (amrfilePath != null) { double d1; MediaPlayer mediaPlayer = new MediaPlayer(); try { - mediaPlayer.setDataSource(paramString); + mediaPlayer.setDataSource(amrfilePath); mediaPlayer.prepare(); int i = mediaPlayer.getDuration(); d1 = i; @@ -487,29 +491,28 @@ public class Util { public static File makeDir(File paramFile, String paramString) { StringBuilder stringBuilder = new StringBuilder(Integer.toHexString(paramString.hashCode())); - for (byte b = 2; b < stringBuilder.length(); b += 3) - stringBuilder.insert(b, "/"); +// for (byte b = 2; b < stringBuilder.length(); b += 3) +// stringBuilder.insert(b, "/"); paramFile = new File(paramFile, stringBuilder.toString()); paramFile.mkdirs(); return paramFile; } - public static String saveFile(byte[] paramArrayOfByte, int paramInt1, int paramInt2, File paramFile, String paramString) { + public static String saveFile(byte[] buf, int start, int size, File dir, String filename) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(UUID.randomUUID().toString()); stringBuilder.append("_"); - stringBuilder.append(paramString); - paramString = stringBuilder.toString(); - paramFile = makeDir(paramFile, paramString); + stringBuilder.append(filename); + filename = stringBuilder.toString(); + File paramFile = makeDir(dir, filename); //建立以文件名Hash命名的路径 try { - paramFile = new File(paramFile, paramString); - BufferedSink bufferedSink = Okio.buffer(Okio.sink(paramFile)); - bufferedSink.write(paramArrayOfByte, paramInt1, paramInt2); - bufferedSink.close(); + paramFile = new File(paramFile, filename);//在路径下再建立文件 + FileOutputStream fos=new FileOutputStream(paramFile); + fos.write(buf,start,size); + fos.close(); return paramFile.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); - } return null; }