From: snickersun Date: Mon, 28 Dec 2020 13:23:04 +0000 (+0800) Subject: 添加EventLooper for Handler(修改未完成) X-Git-Url: http://git.snicker.com.cn/?a=commitdiff_plain;h=b6b2f8545c1c7709ea0087931f7a0b9687c1ff6a;p=protocol_srv.git 添加EventLooper for Handler(修改未完成) --- diff --git a/app/release/ICSer_V739_2012251247_release.apk b/app/release/ICSer_V739_2012251247_release.apk deleted file mode 100644 index e4a6f9e4..00000000 Binary files a/app/release/ICSer_V739_2012251247_release.apk and /dev/null differ diff --git a/app/release/output.json b/app/release/output.json index 705860de..0ad81090 100644 --- a/app/release/output.json +++ b/app/release/output.json @@ -1 +1 @@ -[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":739,"versionName":"2012251247","enabled":true,"outputFile":"ICSer_V739_2012251247_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V739_2012251247_release.apk","properties":{}}] \ No newline at end of file +[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":740,"versionName":"2012281508","enabled":true,"outputFile":"ICSer_V740_2012281508_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V740_2012281508_release.apk","properties":{}}] \ No newline at end of file diff --git a/app/src/main/java/com/enqualcomm/support/CoreService.java b/app/src/main/java/com/enqualcomm/support/CoreService.java index 67e1352b..1373c47f 100644 --- a/app/src/main/java/com/enqualcomm/support/CoreService.java +++ b/app/src/main/java/com/enqualcomm/support/CoreService.java @@ -19,6 +19,7 @@ import android.widget.Toast; import com.enqualcomm.support.adapter.BTHelper; import com.enqualcomm.support.bean.Contact; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.SleepInfo; import com.enqualcomm.support.bean.SleepRecord; @@ -127,12 +128,12 @@ public class CoreService extends Service { // SPRD: add outdoorMode public static final int RINGER_MODE_OUTDOOR = 3; - public static Handler mHandler=new Handler(); + public static Handler mHandler=new Handler(EventLooperHandlerThread.makeLooper(MY_WAKE_LOCKTAG)); +// public static Handler mHandler=new Handler(); private static ICSmsManager smsManager=null; public String getServerAlive(){ return DeviceInfoUtil.getDeviceInfo(runtime); } - private BroadcastReceiver AtCallbackBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context param1Context, Intent param1Intent) { if (param1Intent.getAction().equals("com.eqc.intent.action.callback.at")) { @@ -808,8 +809,6 @@ public class CoreService extends Service { runtime.setNeddReportCutoff(Config.getNeedCutOff(this)); runtime.setNeedAntioff(Config.getNeedAntiOff(this)); - - Config.setHeartBeatCycle(this,alarmCycle); //临时设置为5分钟,给L03测试用。测试断线问题未解决,取消测试。 //初始化ServerHeartBeat Cycle Config.loadHearBeatSetting(runtime); diff --git a/app/src/main/java/com/enqualcomm/support/GSensorListener.java b/app/src/main/java/com/enqualcomm/support/GSensorListener.java index ba11304b..a6692294 100644 --- a/app/src/main/java/com/enqualcomm/support/GSensorListener.java +++ b/app/src/main/java/com/enqualcomm/support/GSensorListener.java @@ -1,63 +1,47 @@ -package com.enqualcomm.support; - - -import android.os.Handler; -import android.os.Message; - -import com.ic.jni.ICJniUtils; -import com.enqualcomm.support.bean.Runtime; - -import com.enqualcomm.support.utils.FileOutputUtil; -import com.enqualcomm.support.utils.ICLogger; - -/** - * 由于Gsensor用的硬件计步,只需要保证打开计步器即可 - */ -public class GSensorListener { - - - public static boolean getStepCountOver = false; - - private int CURRENT_STEP; - - Handler mHandler = new Handler() { - public void handleMessage(Message msg) { - super.handleMessage(msg); - if (msg.what != 100) - return; - GSensorListener.this.CURRENT_STEP = ICJniUtils.getStepCount(); - StringBuilder stringBuilder1 = new StringBuilder(); - stringBuilder1.append("CURRENT_STEP ="); - stringBuilder1.append(GSensorListener.this.CURRENT_STEP); - ICLogger.i(stringBuilder1.toString()); - runtime.setTotalStepCount(CURRENT_STEP); - GSensorListener.getStepCountOver=false; -// if (Config.LOG_TOFILE) FileOutputUtil.fileOutput(runtime.getCacheDir(), "CURRENT_STEP", stringBuilder1.toString()); - } - }; - - private Runtime runtime; - - public GSensorListener( Runtime dev) { - this.runtime = dev; - ICJniUtils.enablePedometer(); - } - - public void updateStepCount(){ - if(getStepCountOver==false) { - getStepCountOver = true; - CURRENT_STEP = ICJniUtils.getStepCount(); - StringBuilder stringBuilder1 = new StringBuilder(); - stringBuilder1.append("CURRENT_STEP ="); - stringBuilder1.append(CURRENT_STEP); - ICLogger.i(stringBuilder1.toString()); - runtime.setTotalStepCount(CURRENT_STEP); - getStepCountOver = false; - } - } - public int getStepCount() { - return this.CURRENT_STEP; - } - -} - +package com.enqualcomm.support; + + +import android.os.Handler; +import android.os.Message; + +import com.ic.jni.ICJniUtils; +import com.enqualcomm.support.bean.Runtime; + +import com.enqualcomm.support.utils.FileOutputUtil; +import com.enqualcomm.support.utils.ICLogger; + +/** + * 由于Gsensor用的硬件计步,只需要保证打开计步器即可 + */ +public class GSensorListener { + + + public static boolean getStepCountOver = false; + + private int CURRENT_STEP; + + private Runtime runtime; + + public GSensorListener( Runtime dev) { + this.runtime = dev; + ICJniUtils.enablePedometer(); + } + + public void updateStepCount(){ + if(getStepCountOver==false) { + getStepCountOver = true; + CURRENT_STEP = ICJniUtils.getStepCount(); + StringBuilder stringBuilder1 = new StringBuilder(); + stringBuilder1.append("CURRENT_STEP ="); + stringBuilder1.append(CURRENT_STEP); + ICLogger.i(stringBuilder1.toString()); + runtime.setTotalStepCount(CURRENT_STEP); + getStepCountOver = false; + } + } + public int getStepCount() { + return this.CURRENT_STEP; + } + +} + diff --git a/app/src/main/java/com/enqualcomm/support/ICSmsManager.java b/app/src/main/java/com/enqualcomm/support/ICSmsManager.java index 664ec455..5ae6f875 100644 --- a/app/src/main/java/com/enqualcomm/support/ICSmsManager.java +++ b/app/src/main/java/com/enqualcomm/support/ICSmsManager.java @@ -22,6 +22,7 @@ import android.text.TextUtils; import android.widget.Toast; import com.enqualcomm.support.bean.Contact; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.bean.StringMessage; @@ -79,47 +80,10 @@ public class ICSmsManager extends BroadcastReceiver { private Context mContext = null; Runtime runtime; - Handler mHandler=new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - - if (message.what==100){ - - Bundle param = message.getData(); - if (param!=null){ - - String from = param.getString("SMSFrom"); - String smsmessage = param.getString("SMSData"); - - long currenttime = System.currentTimeMillis(); -// if (currenttime - ICSmsManager.preTimeMillis > 30000L) { - ICSmsManager.preTimeMillis = currenttime; - (new Thread(new Runnable() { - public void run() { - SystemClock.sleep(3000L); - ICLogger.i("收到" + from + "短信:" + smsmessage); -// Toast.makeText(context, "收到" + from + "短信:" + smsmessage, Toast.LENGTH_LONG).show(); - if (handleSMS_CMD(from, smsmessage) == false) { - //说明不是sms命令,提示短信接收。 - ContextProxy.sendMsgBroadcast(mContext, smsmessage, 1); - } - } - })).start(); -// } - - - } - - - } - - - - return false; - } - }); + Handler mHandler; ReplayLocation replayLocation=new ReplayLocation(); + private boolean needshowToast=false; @Override public void onReceive(Context context, Intent intent) { @@ -193,11 +157,6 @@ public class ICSmsManager extends BroadcastReceiver { } } - public ICSmsManager( ) { - - - } - public ICSmsManager( Runtime _runtime) { this.runtime = _runtime; this.mContext = runtime.getContextProxy().context; @@ -205,6 +164,51 @@ public class ICSmsManager extends BroadcastReceiver { intentfilter.addAction(ACTION_SMSCMD_Reply); this.mContext.registerReceiver(this,intentfilter); // registerSmsDatabaseChangeObserver(mContext); + mHandler=new Handler(EventLooperHandlerThread.makeLooper(ICSmsManager.class.getSimpleName()),new Handler.Callback() { + @Override + public boolean handleMessage(Message message) { + switch (message.what) { + case 100: { + Bundle param = message.getData(); + if (param != null) { + String from = param.getString("SMSFrom"); + String smsmessage = param.getString("SMSData"); + long currenttime = System.currentTimeMillis(); +// if (currenttime - ICSmsManager.preTimeMillis > 30000L) { + ICSmsManager.preTimeMillis = currenttime; + (new Thread(new Runnable() { + public void run() { + SystemClock.sleep(3000L); + ICLogger.i("收到" + from + "短信:" + smsmessage); +// Toast.makeText(context, "收到" + from + "短信:" + smsmessage, Toast.LENGTH_LONG).show(); + if (handleSMS_CMD(from, smsmessage) == false) { + //说明不是sms命令,提示短信接收。 + ContextProxy.sendMsgBroadcast(mContext, smsmessage, 1); + } + } + })).start(); +// } + } + } + break; + case 0: + // sendSMS(phonenumber, "Upload Failed!"); + // if (needshowToast) { + Util.ShowToast(runtime, "Upload cmd Failed!"); + // } + break; + + case 1: + // sendSMS(phonenumber, "Upload success!"); + // if (needshowToast) { + Util.ShowToast(runtime, "Upload cmd success!"); + // } + break; + } + return false; + } + } ); + } public void sendSMS(String phonenumber, String msg) { @@ -535,7 +539,7 @@ public class ICSmsManager extends BroadcastReceiver { Config.setWiFiPasswd(mContext,PWD); sendSMS(phonenumber, "set and connect to Wifi SSID " + Config.getWiFiSSID(mContext) +", WiFiPassword "+Config.getWiFiPasswd(mContext)+ ", encryptType "+encyptType+"!"); //connect to wifi - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { Deliver.connectToWifi(SSID,PWD,encyptType); @@ -570,30 +574,8 @@ public class ICSmsManager extends BroadcastReceiver { } }else if(sms.startsWith(ENCRYPED_HEADER+"#logctl#=")){ - final boolean needshowToast=sms.contains("SDLogInfo:"); - Handler mhandler=new Handler(){ - @Override - public void handleMessage(Message msg) { - - switch(msg.what){ - case 0: - sendSMS(phonenumber, "Upload Failed!"); - if (needshowToast) { - Util.ShowToast(runtime, "Upload cmd Failed!"); - } - break; - - case 1: - sendSMS(phonenumber, "Upload success!"); - if (needshowToast) { - Util.ShowToast(runtime, "Upload cmd success!"); - } - break; - } + needshowToast=sms.contains("SDLogInfo:"); - super.handleMessage(msg); - } - }; String tmp[] = sms.split("="); if (tmp.length == 2) { if (tmp[1].equals("current")) { @@ -615,7 +597,7 @@ public class ICSmsManager extends BroadcastReceiver { String sdfilelist[] = logfile.split(":"); if (sdfilelist.length==2) { String fileOrDir=sdfilelist[1]; - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileOrDir; @@ -649,7 +631,7 @@ public class ICSmsManager extends BroadcastReceiver { } } } else { - if (ICHttpUtil.uploadFile(filepath, runtime, logtime,mhandler)) { + if (ICHttpUtil.uploadFile(filepath, runtime, logtime,mHandler)) { // sendSMS(phonenumber, "Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!"); // if (logfile.startsWith("SDLogInfo:")){ // Util.ShowToast(runtime,"Upload " + filepath + " to " + Config.getFtpServer(mContext) + " success!"); @@ -675,7 +657,7 @@ public class ICSmsManager extends BroadcastReceiver { } }else{ - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { String filepath = Util.getLogfilePath(runtime, logfile); @@ -698,7 +680,7 @@ public class ICSmsManager extends BroadcastReceiver { sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " failed!"); } }else{ - if (ICHttpUtil.uploadFile(filepath,runtime,logtime,mhandler)) { + if (ICHttpUtil.uploadFile(filepath,runtime,logtime,mHandler)) { // sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " success!"); } else { // sendSMS(phonenumber, "Upload " + logfile + " to " + Config.getFtpServer(mContext) + " failed!"); @@ -867,7 +849,7 @@ public class ICSmsManager extends BroadcastReceiver { sendSMS(phonenumber, "start listen !"); // CellInfoUtil.dialSilent(runtime.getContextProxy().context,phonenumber); ICAudioManager.needMute=true; - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { SimSignalUtil.send_at_cmd(runtime,"atd"+phonenumber+";"); @@ -945,7 +927,7 @@ public class ICSmsManager extends BroadcastReceiver { cell_number_to_reply=phonenumber; sendSMS(phonenumber, sb.toString()); //connect to wifi - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { Deliver.connectToWifi(SSID,PWD,encyptType); @@ -1095,7 +1077,7 @@ public class ICSmsManager extends BroadcastReceiver { sendSMS(phonenumber, "mail address error !"); }else { - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { String logfile = ""; @@ -1141,7 +1123,7 @@ public class ICSmsManager extends BroadcastReceiver { }else if(sms.startsWith(ENCRYPED_HEADER+"#capture#")) { - new Handler().post(new Runnable() { + mHandler.post(new Runnable() { @Override public void run() { (new CameraUtil(mContext)).getPictur("capture"+TimeUtil.getSystemTime3()); @@ -1150,7 +1132,7 @@ public class ICSmsManager extends BroadcastReceiver { }else if(sms.startsWith(ENCRYPED_HEADER+"#monitor#")) { - new Handler().post(new Runnable() { + mHandler.post(new Runnable() { @Override public void run() { CoreService.getInstance().DevliverStringMessage("StartMonitor","10"); @@ -1226,7 +1208,7 @@ public class ICSmsManager extends BroadcastReceiver { if(CoreService.getInstance()!=null){ SimSignalUtil.send_at_to_reset_simcard(runtime); //直接下此命令不能实现断网重连,所以干脆采用关闭网络再打开的方式。 SimSignalUtil.setAirMode(CoreService.getInstance(), "OpenAirplane"); - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { SimSignalUtil.setAirMode(CoreService.getInstance(),"CloseAirplane"); diff --git a/app/src/main/java/com/enqualcomm/support/LocationClient.java b/app/src/main/java/com/enqualcomm/support/LocationClient.java index d0e66629..900a3fca 100644 --- a/app/src/main/java/com/enqualcomm/support/LocationClient.java +++ b/app/src/main/java/com/enqualcomm/support/LocationClient.java @@ -11,6 +11,7 @@ import android.os.SystemClock; import com.enqualcomm.support.adapter.BTHelper; import com.enqualcomm.support.adapter.LBSHelper; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.bean.StringMessage; @@ -305,6 +306,7 @@ public class LocationClient { } }); + mhandler = new Handler(EventLooperHandlerThread.makeLooper(LocationClient.class.getSimpleName()),locationCallback); btHelper.setBLEScanTimeout(OneBLEScanTimeOUT); gLocationCline = this; //GPS 监听管理初始化 @@ -480,10 +482,11 @@ public class LocationClient { private final static int msgWhat_StartLocationProcess = 0; private final static int msgWhat_StartBLEProcess = 1; private final static int msgWhat_StartSOSLocationProcess = 2; - Handler mhandler = new Handler() { + private Handler.Callback locationCallback = new Handler.Callback() { + + @Override + public boolean handleMessage(Message msg) { - public void handleMessage(Message msg) { - super.handleMessage(msg); if (msg.what == msgWhat_WaitAndSendLocation) { Single.just(null).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1() { public void call(Object param1Object) { @@ -567,8 +570,10 @@ public class LocationClient { // startLocationProcess(ICLocation.NORMAL_MOD); // } } + return false; } }; + Handler mhandler ; boolean wifi_ok = false, gps_ok = false, lbs_ok = false, gps_nosignal = false; diff --git a/app/src/main/java/com/enqualcomm/support/NMEAListener.java b/app/src/main/java/com/enqualcomm/support/NMEAListener.java index 97add69c..f9f601cb 100644 --- a/app/src/main/java/com/enqualcomm/support/NMEAListener.java +++ b/app/src/main/java/com/enqualcomm/support/NMEAListener.java @@ -14,6 +14,7 @@ import android.os.Handler; import android.os.Message; import android.provider.Settings; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.utils.FileOutputUtil; @@ -107,6 +108,33 @@ public class NMEAListener implements NmeaListener, LocationListener { public NMEAListener(LocationManager paramLocationManager, Runtime paramRuntime) { this.locationManager = paramLocationManager; this.runtime = paramRuntime; + + temHandler=new Handler(EventLooperHandlerThread.makeLooper(NMEAListener.class.getSimpleName()),new Handler.Callback() { + @Override + public boolean handleMessage(Message message) { + + if (message.what == MSG_WHAT_GPS_TIMEOUT || message.what == MSG_WHAT_GPS_NOSTAR) { + //no start + //do nothing + + } else if (message.what == MSG_WHAT_GPS_FIXED) { + //fixed + /* + 只有当前GPS已经定位,且location不为空才给 runtime赋值GPS坐标。 + 延迟三秒后才设置runtime的定位标志,以便稳定坐标值。 + */ + runtime.getLocationInstance().setLocationStat(ICLocation.LOCATION_STAT.LOCATION_FIXED); + + } + + if (!noStop) { + ICLogger.i("handleMessage MSG_WHAT_GPS_TIMEOUT/ MSG_WHAT_GPS_NOSTAR/ MSG_WHAT_GPS_FIXED " + message.what); + + stopListen(); + } + return true; + } + } ); } static int satindex = 0; @@ -489,32 +517,7 @@ public class NMEAListener implements NmeaListener, LocationListener { private final int MSG_WHAT_GPS_NOSTAR = 200; private final int MSG_WHAT_GPS_FIXED_NO_STOP = 400; - Handler temHandler = new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - - if (message.what == MSG_WHAT_GPS_TIMEOUT || message.what == MSG_WHAT_GPS_NOSTAR) { - //no start - //do nothing - - } else if (message.what == MSG_WHAT_GPS_FIXED) { - //fixed - /* - 只有当前GPS已经定位,且location不为空才给 runtime赋值GPS坐标。 - 延迟三秒后才设置runtime的定位标志,以便稳定坐标值。 - */ - runtime.getLocationInstance().setLocationStat(ICLocation.LOCATION_STAT.LOCATION_FIXED); - - } - - if (!noStop) { - ICLogger.i("handleMessage MSG_WHAT_GPS_TIMEOUT/ MSG_WHAT_GPS_NOSTAR/ MSG_WHAT_GPS_FIXED " + message.what); - - stopListen(); - } - return true; - } - }); + Handler temHandler; private void get3MaxSnrSatellite(ICLocation.GpsSatellitePriv gst) { diff --git a/app/src/main/java/com/enqualcomm/support/adapter/BTHelper.java b/app/src/main/java/com/enqualcomm/support/adapter/BTHelper.java index d2d32db0..e54eaa9f 100644 --- a/app/src/main/java/com/enqualcomm/support/adapter/BTHelper.java +++ b/app/src/main/java/com/enqualcomm/support/adapter/BTHelper.java @@ -9,7 +9,10 @@ import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.os.Handler; +import android.os.HandlerThread; +import com.enqualcomm.support.NMEAListener; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.Config; import com.enqualcomm.support.utils.IBeaconUtil; @@ -98,7 +101,9 @@ public class BTHelper { if (lecallback == null) lecallback = new BLeScanCallback(); if (mHandler == null) - mHandler = new Handler(); + { + mHandler = new Handler(EventLooperHandlerThread.makeLooper(BTHelper.class.getSimpleName())); + } } @@ -142,7 +147,9 @@ public class BTHelper { if (lecallback == null) lecallback = new BLeScanCallback(); if (mHandler == null) - mHandler = new Handler(); + { + mHandler = new Handler(EventLooperHandlerThread.makeLooper(BTHelper.class.getSimpleName())); + } mBtAdapter.startLeScan(lecallback); mHandler.postDelayed(mRunable_stopBleScan, BLETimeoutForOneScan * 1000); @@ -280,7 +287,7 @@ public class BTHelper { @Override public void run() { - ICLogger.i("BT stopLeScan"); + ICLogger.i("BT stopLeScan "+Thread.currentThread().getName()); mBtAdapter.stopLeScan(lecallback); //开始扫描前是关闭的,就关闭它 // if(!enabledBeforScan) diff --git a/app/src/main/java/com/enqualcomm/support/bean/EventLooperHandlerThread.java b/app/src/main/java/com/enqualcomm/support/bean/EventLooperHandlerThread.java new file mode 100644 index 00000000..7c62275c --- /dev/null +++ b/app/src/main/java/com/enqualcomm/support/bean/EventLooperHandlerThread.java @@ -0,0 +1,26 @@ +package com.enqualcomm.support.bean; + +import android.os.Looper; + +import com.enqualcomm.support.utils.ICLogger; + +public class EventLooperHandlerThread extends Thread { + public Looper looper; + + public EventLooperHandlerThread(String name){ + super("Thread_"+name); + } + @Override + public void run() { + Looper.prepare();//创建与当前线程相关的Looper + looper = Looper.myLooper();//获取当前线程的Looper对象 + ICLogger.i("EventLooperHandlerThread run"); + Looper.loop();//调用此方法,消息才会循环处理 + } + + public static Looper makeLooper(String name){ + EventLooperHandlerThread eventLooperHandlerThread=new EventLooperHandlerThread(name); + eventLooperHandlerThread.start(); + return eventLooperHandlerThread.looper; + } +} diff --git a/app/src/main/java/com/enqualcomm/support/service/Deliver.java b/app/src/main/java/com/enqualcomm/support/service/Deliver.java index 246f1dfd..425f41ca 100644 --- a/app/src/main/java/com/enqualcomm/support/service/Deliver.java +++ b/app/src/main/java/com/enqualcomm/support/service/Deliver.java @@ -19,6 +19,8 @@ import com.enqualcomm.support.Config; import com.enqualcomm.support.Constants; import com.enqualcomm.support.CoreService; import com.enqualcomm.support.R; +import com.enqualcomm.support.adapter.BTHelper; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.VoiceContent; import com.enqualcomm.support.utils.DBHelper; import com.enqualcomm.support.utils.TemperatureUtil; @@ -94,14 +96,10 @@ public class Deliver extends AbstractConnectionService { private static boolean wifiEnabled; public static Runnable delaySendMSG; - private static Handler mSendMSGHandler=new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - return false; - } - }); + private static Handler mSendMSGHandler; static { + mSendMSGHandler = new Handler(EventLooperHandlerThread.makeLooper(Deliver.class.getSimpleName())); delaySendMSG = new Runnable() { @Override public void run() { diff --git a/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java b/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java index 66d28215..2fbb4390 100644 --- a/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java +++ b/app/src/main/java/com/enqualcomm/support/service/HeartRateManager.java @@ -19,6 +19,7 @@ import com.enqualcomm.support.Config; import com.enqualcomm.support.Constants; import com.enqualcomm.support.CoreService; import com.enqualcomm.support.LocationClient; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.StringMessage; import com.enqualcomm.support.utils.ICHttpUtil; import com.enqualcomm.support.utils.Util; @@ -133,8 +134,7 @@ public class HeartRateManager extends AbstractInvokeHandlerService implements Se isTimerStarted=false; mSensorManager = (SensorManager) runtime.getContextProxy().context.getSystemService(SENSOR_SERVICE); mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE); - - mHandler=new Handler(new Handler.Callback() { + mHandler = new Handler(EventLooperHandlerThread.makeLooper(HeartRateManager.class.getSimpleName()),new Handler.Callback() { @Override public boolean handleMessage(Message message) { diff --git a/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java b/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java index de2de23f..d6d21099 100644 --- a/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java +++ b/app/src/main/java/com/enqualcomm/support/service/KeepAlive.java @@ -1,399 +1,404 @@ -package com.enqualcomm.support.service; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Handler; - -//import com.eiot.watch_lib.LauncherCtrl; -import com.enqualcomm.support.Config; -import com.enqualcomm.support.CoreService; -import com.enqualcomm.support.LocationClient; -import com.enqualcomm.support.utils.Util; -import com.ic.protocols.protocolAPIHelper; -import com.enqualcomm.support.bean.StringMessage; -import com.enqualcomm.support.service.base.AbstractConnectionService; -import com.enqualcomm.support.utils.AlarmWakeUp; -import com.enqualcomm.support.utils.Connection; -import com.enqualcomm.support.utils.DeviceInfoUtil; -import com.enqualcomm.support.utils.ICLogger; -import com.enqualcomm.support.utils.NettyConnection; -import com.enqualcomm.support.utils.NetworkObservable; -import com.enqualcomm.support.bean.Runtime; -import com.enqualcomm.support.utils.SimSignalUtil; - -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import rx.Subscription; -import rx.functions.Action1; - -public class KeepAlive extends AbstractConnectionService { - private static final long HEARTBEAT_TIMEOUT = 660000L; - private static String TAG = KeepAlive.class.getSimpleName(); - public static boolean connectionError = false; - - public static boolean isConnected = false; - - private static boolean isInSleepMode = false; - - private static int mDisconnectByServerCount=0; - Connection connection; - - Context mContext; - - NetworkObservable mNetworkObservable = new NetworkObservable(); - - Runtime mRuntime; - - private ShutDownReceiver mShutDownReceiver; - - private Subscription mSubscription; - - private int reConnectionNumber; - -//服务器收到AP03 会返回BP03,如果PB03 规定时间没收到,则认为发送心跳失败,需要重发, - private boolean is_heartBeat_send_success=false; - private boolean is_login_send_success=false; - private boolean is_ping_send_success=false; - - //如果重试5次还没有连接上,则需要重新断开连接重新连接服务器。 - private int hearBeatResendCount=0; - private int MaxHeartbeatResendTime=6; - //每次retry发送心跳的间隔为20秒 - private int heartBeatRetryTimeout=20; - - private Handler mHandler=new Handler(); - //监测 心跳服务器响应的timer - private ScheduledThreadPoolExecutor scheduled = null; - private Runnable CheckSrvResponseTimerTask=new Runnable() { - @Override - public void run() { - checkSrvResponse(); - } - }; - - public void startResponseCheckTimer(){ - //联网再重试连接服务器 - if (SimSignalUtil.checkNet(mRuntime.getContextProxy().context) ) { - stopResponseCheckTimer(); - if (scheduled == null) { - scheduled = new ScheduledThreadPoolExecutor(10); - } - //开始检测重新计数 - hearBeatResendCount=0; - //如果开始进行连接重 - // { - // 试,证明网络断开的,那么KeepAlive也需要重连(心跳包) - if (scheduled != null) { - scheduled.scheduleAtFixedRate(CheckSrvResponseTimerTask , heartBeatRetryTimeout*1000, heartBeatRetryTimeout*1000,TimeUnit.MILLISECONDS); //delay 3秒先检查一次,然后每5秒重试一次 - } - } - } - - private Runnable msendMsgAfterHeartbeat=new Runnable() { - @Override - public void run() { - connection.send(protocolAPIHelper.getBindingMSG(mRuntime)); - if (Config.protocol_no==Config.PROTOCOL_FZD){ - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - connection.send(protocolAPIHelper.getSyncTimeMSG(mRuntime)); - } - },5000); - } - } - }; - - public void checkSrvResponse(){ - - if (SimSignalUtil.checkNet(mRuntime.getContextProxy().context) ) { - - //如果收到服务器响应BP03,则停止重试,否则 继续发送AP03 心跳包,且继续检查响应 - if (this.is_heartBeat_send_success ) { - ICLogger.i("checkSrvResponse 成功,停止检测!"); - stopResponseCheckTimer(); - }else{ - //心跳发送失败,则认为已经和服务器断开 - mRuntime.setServerProtocolConnected(false); - //如果重试次数大于等于 最大重试次数,则停止重试,等下次心跳时间再行尝试。 - if (hearBeatResendCount >= MaxHeartbeatResendTime){ - ICLogger.i("checkSrvResponse "+hearBeatResendCount+"次 >= "+MaxHeartbeatResendTime+" , 则停止重试,等下次心跳时间再行尝试!"); - stopResponseCheckTimer(); - }else { - //重新发送AP03心跳包 - ICLogger.i("checkSrvResponse 失败,第" + hearBeatResendCount + "次,重新发送AP03心跳包!"); - //心跳开始发送的时候,先重置response检测标志 - is_heartBeat_send_success = false; - hearBeatResendCount++; - //更新系统的IMEI - boolean ret=DeviceInfoUtil.updateImei(mRuntime); - ICLogger.i("Update IMEI "+ret); - - //只有曾经login成功过,且上一次成功时间超过15分钟,才会自主断开网络。 - long currenttime=System.currentTimeMillis(); - ICLogger.i("只有曾经login或者心跳发送成功过,且上一次成功时间超过15分钟,才会自主断开网络! last longin time "+ - mRuntime.lastLoginSuccessTime+" ms from last login time "+(currenttime-mRuntime.lastLoginSuccessTime)); - if ((mRuntime.lastLoginSuccessTime>0) && ((currenttime- mRuntime.lastLoginSuccessTime) > 15 * 60 * 1000)) { - ICLogger.i("超时自主断开网络!"); - CoreService.getInstance().disconnect_server(); - }else { - if (is_login_send_success) { - connection.send(protocolAPIHelper.getHeartbeatMSG(mRuntime)); - } else { - connection.send(protocolAPIHelper.getLoginMSG(mRuntime)); - } - } - } - } - - }else{ - //没有网络就不用重新尝试连接网络了。网络连接后再重新尝试联网 - ICLogger.i("checkSrvResponse stop , 没有网络就不用重新尝试检测服务器响应和重新发送心跳包了!"); - - stopResponseCheckTimer(); - } - } - - - - public void stopResponseCheckTimer(){ - if (scheduled !=null){ - scheduled.shutdownNow(); -// Runnable tmp= scheduled.getQueue().poll(); -// while (tmp!=null){ -// scheduled.remove(tmp); -// } - scheduled.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); - scheduled.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); -// scheduled.setRemoveOnCancelPolicy(true); - ICLogger.i("Wait for thread pool getContinueExistingPeriodicTasksAfterShutdownPolicy " +scheduled.getContinueExistingPeriodicTasksAfterShutdownPolicy()+ - "\ngetExecuteExistingDelayedTasksAfterShutdownPolicy "+scheduled.getExecuteExistingDelayedTasksAfterShutdownPolicy());//+ -// "\ngetRemoveOnCancelPolicy "+scheduled.getRemoveOnCancelPolicy()); -// while(!scheduled.isTerminated()) -// { -// StringBuilder sb=new StringBuilder(); -// if (scheduled.isTerminated()) sb.append("+"); -// if (scheduled.isShutdown()) sb.append("*"); -// if (scheduled.isTerminating()) sb.append("-"); -// ICLogger.i(sb.toString()); -// try { -// Thread.sleep(500); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } - scheduled.purge(); - scheduled = null; - } - - ICLogger.i(" stopResponseCheckTimer Done "); - } - - - - public void onAlarmClock(Connection paramConnection, Runtime paramRuntime) { - - ICLogger.i("onAlarmClock"); - - } - - public void onAttach(final Connection connection, final Runtime runtime) { - this.mRuntime = runtime; - this.mContext = (runtime.getContextProxy()).context; - this.mNetworkObservable.register(this.mContext); - this.connection = connection; - this.mSubscription = this.mNetworkObservable.onChange().subscribe(new Action1() { - private boolean first; - - public void call(Integer param1Integer) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("yls aBoolean="); - stringBuilder.append(param1Integer); - stringBuilder.append(",,first="); - stringBuilder.append(this.first); - ICLogger.i(stringBuilder.toString()); - if (param1Integer.intValue() > 1) { - //返回值大于0 证明是网络连接成功,开始重连服务器 - if (this.first) { - this.first = false; - return; - } - ICLogger.i("数据网络连接成功,重新连接服务器。"); - CoreService.getInstance().ReConnectToServer(); - } - } - }); - IntentFilter intentFilter = new IntentFilter(); - intentFilter.addAction("android.intent.action.ACTION_SHUTDOWN"); - this.mShutDownReceiver = new ShutDownReceiver(); - this.mContext.registerReceiver(this.mShutDownReceiver, intentFilter); - } - - @Override - public boolean onConnectionClose(Connection paramConnection, Runtime paramRuntime, String ErrorMsg) { - - -// if (isConnected) - //如果KeepAlive被关闭说明网络有问题,因此开启重试联网机制 - stopResponseCheckTimer(); - - if (false) { - if (ErrorMsg.equals("DIS_CONNECT_BY_SERVERSIDE")) { - if (mDisconnectByServerCount < 3) {//被服务器拒绝连续拒绝3次后才停止重试 - CoreService.getInstance().startConnectionRetryTimer(); - } else { - ICLogger.i("服务器主动断开超过连续3次,IMEI不对或者命令格式错误!停止重试连接服务器,等待重启或者下一次网络重连。"); - } - mDisconnectByServerCount++; - } else { - mDisconnectByServerCount = 0; //如果不是被服务器拒绝,则重置 计数。 - CoreService.getInstance().startConnectionRetryTimer(); - } - }else{ - CoreService.getInstance().startConnectionRetryTimer(); - } - connectionError = true; - isConnected = false; - paramRuntime.setServerProtocolConnected(false); - - is_ping_send_success=false; - is_login_send_success=false; - is_heartBeat_send_success=false; - - //发送广播 服务器断开链接 - paramRuntime.getContextProxy().sendBroadcastServerConnectionChanged(false); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("onConnectionClose="); - stringBuilder.append(",set KeepAlive isConnected = false"); - ICLogger.i(stringBuilder.toString()); -// LauncherCtrl.getInstance(this.mContext).setStatusBarIcon("server_connected", STATUS_BAR_STATE_SERVER_CONNECTED_OFF); -//网络断开后,重连成功后发送一个定位 -// CoreService.needLocateInAfterHeartBeat=true; - return false; - } - public boolean onConnectionOpen(Connection paramConnection, Runtime paramRuntime) { - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("onConnectionOpen connectionError="); - stringBuilder.append(connectionError); - stringBuilder.append(",sInSleepMode ="); - stringBuilder.append(isInSleepMode); - stringBuilder.append(",set KeepAlive isConnected = true"); - ICLogger.i(stringBuilder.toString()); -// if (!connectionError) { - connectionError = false; - - //更新系统的IMEI - boolean ret=DeviceInfoUtil.updateImei(paramRuntime); - ICLogger.i("Update IMEI "+ret); - //发送登录包 - is_login_send_success=false; - - isConnected = true; - - Util.mSleep(1000); - - connection.send(protocolAPIHelper.getLoginMSG(paramRuntime)); - -// this.firstReConnected = true; -// this.idleTimeMillis = SystemClock.elapsedRealtime(); - - return false; - } - - public void onDetach(Connection paramConnection, Runtime paramRuntime) { - if (this.mSubscription != null && !this.mSubscription.isUnsubscribed()) - this.mSubscription.unsubscribe(); - this.mNetworkObservable.unregister(this.mContext); - this.mContext.unregisterReceiver(this.mShutDownReceiver); - } - - public void onHeartAlarm(Connection paramNettyConnection, Runtime paramRuntime) { - ICLogger.i("onHeartAlarm"); - - stopResponseCheckTimer(); - //心跳开始发送的时候,先重置response检测标志 - is_heartBeat_send_success=false; - - //这个是正常心跳包,暂时不能认为服务器连接时失败的,所以正常发送检测。 - //发送心跳包 - connection.send(protocolAPIHelper.getHeartbeatMSG(paramRuntime)); - //发送完心跳后,开始检查服务器响应 - startResponseCheckTimer(); - - - } - - public boolean onReceive(StringMessage paramStringMessage, Connection paramConnection, Runtime paramRuntime) { -// this.idleTimeMillis = SystemClock.elapsedRealtime(); - if ("heartbeat".equals(paramStringMessage.cmd())) { - AlarmWakeUp.isNeedWakeUpAlarm(paramRuntime); - -// 收到心跳才认为是已经连接了服务器 - paramRuntime.setServerProtocolConnected(true); -// isConnected = true; - is_heartBeat_send_success=true; - paramRuntime.lastLoginSuccessTime=System.currentTimeMillis(); -// LauncherCtrl.getInstance(this.mContext).setStatusBarIcon("server_connected", STATUS_BAR_STATE_SERVER_CONNECTED_ON); -// Deliver.triggerSendThread(); //链接上就尝试清除 buffer中的数据 - - if(!is_ping_send_success) { - //心跳结束后执行,且只在重新登陆后执行一次 - mHandler.post(msendMsgAfterHeartbeat); - is_ping_send_success=true; - } - if (CoreService.needLocateInAfterHeartBeat==true){ - //第一次启动或者系统Close后重连的时候,重置LocationCycle - CoreService.needLocateInAfterHeartBeat=false; - LocationClient.setForceLocation(1); - CoreService.getInstance().setLocationAlarm(paramRuntime.getLocationInstance().getWorkingMod()); - } - }else if (paramStringMessage.cmd().equals("login")) { - //广播服务器连接成功的消息 - paramRuntime.getContextProxy().sendBroadcastServerConnectionChanged(true); - //登录包收到就停止重链接服务器 - CoreService.getInstance().stopConnectionRetryTimer(); - is_login_send_success=true; - //收到登录包反馈后再发送心跳 - - //心跳开始发送的时候,先重置response检测标志 - is_heartBeat_send_success=false; - is_ping_send_success=false; - paramRuntime.lastLoginSuccessTime=System.currentTimeMillis(); - //发送心跳包 - - //这时重新连接服务器才进行的连接,理论上close已经设置false,此次可以认为协议定然断开,所以设置为false作为双重保险。 - mRuntime.setServerProtocolConnected(false); - connection.send(protocolAPIHelper.getHeartbeatMSG(paramRuntime)); - //发送完心跳后,开始检查服务器响应 - - startResponseCheckTimer(); - - - } - return false; - } - - - public void setSleepMode(boolean paramBoolean) { - isInSleepMode = paramBoolean; - } - - class ShutDownReceiver extends BroadcastReceiver { - public void onReceive(Context param1Context, Intent param1Intent) { - boolean bool = param1Intent.getBooleanExtra("reboot", false); - ICLogger.i("Shutdown Received! reboot="+bool); - if (!bool && !KeepAlive.this.mRuntime.isShutdown()){ - /*电量低,不是重启,且不是服务器让关闭的*/ - KeepAlive.this.mRuntime.setAlarmType(Runtime.AlarmType.ALARM_POWER_OFF); - ICLogger.i("triggerSOSLocationProcess "); - LocationClient.getInstance().triggerSOSLocationProcess(); -// Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(KeepAlive.this.mRuntime)); - ICLogger.i("Shutdown Received! send AP10 !"); - } - } - } -} +package com.enqualcomm.support.service; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Handler; +import android.support.annotation.Keep; + +//import com.eiot.watch_lib.LauncherCtrl; +import com.enqualcomm.support.Config; +import com.enqualcomm.support.CoreService; +import com.enqualcomm.support.LocationClient; +import com.enqualcomm.support.bean.EventLooperHandlerThread; +import com.enqualcomm.support.utils.Util; +import com.ic.protocols.protocolAPIHelper; +import com.enqualcomm.support.bean.StringMessage; +import com.enqualcomm.support.service.base.AbstractConnectionService; +import com.enqualcomm.support.utils.AlarmWakeUp; +import com.enqualcomm.support.utils.Connection; +import com.enqualcomm.support.utils.DeviceInfoUtil; +import com.enqualcomm.support.utils.ICLogger; +import com.enqualcomm.support.utils.NettyConnection; +import com.enqualcomm.support.utils.NetworkObservable; +import com.enqualcomm.support.bean.Runtime; +import com.enqualcomm.support.utils.SimSignalUtil; + +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import rx.Subscription; +import rx.functions.Action1; + +public class KeepAlive extends AbstractConnectionService { + private static final long HEARTBEAT_TIMEOUT = 660000L; + private static String TAG = KeepAlive.class.getSimpleName(); + public static boolean connectionError = false; + + public static boolean isConnected = false; + + private static boolean isInSleepMode = false; + + private static int mDisconnectByServerCount=0; + Connection connection; + + Context mContext; + + NetworkObservable mNetworkObservable = new NetworkObservable(); + + Runtime mRuntime; + + private ShutDownReceiver mShutDownReceiver; + + private Subscription mSubscription; + + private int reConnectionNumber; + +//服务器收到AP03 会返回BP03,如果PB03 规定时间没收到,则认为发送心跳失败,需要重发, + private boolean is_heartBeat_send_success=false; + private boolean is_login_send_success=false; + private boolean is_ping_send_success=false; + + //如果重试5次还没有连接上,则需要重新断开连接重新连接服务器。 + private int hearBeatResendCount=0; + private int MaxHeartbeatResendTime=6; + //每次retry发送心跳的间隔为20秒 + private int heartBeatRetryTimeout=20; + + private Handler mHandler; + //监测 心跳服务器响应的timer + private ScheduledThreadPoolExecutor scheduled = null; + private Runnable CheckSrvResponseTimerTask=new Runnable() { + @Override + public void run() { + checkSrvResponse(); + } + }; + + public KeepAlive(){ + mHandler = new Handler(EventLooperHandlerThread.makeLooper(KeepAlive.class.getSimpleName())); + } + public void startResponseCheckTimer(){ + //联网再重试连接服务器 + if (SimSignalUtil.checkNet(mRuntime.getContextProxy().context) ) { + stopResponseCheckTimer(); + if (scheduled == null) { + scheduled = new ScheduledThreadPoolExecutor(10); + } + //开始检测重新计数 + hearBeatResendCount=0; + //如果开始进行连接重 + // { + // 试,证明网络断开的,那么KeepAlive也需要重连(心跳包) + if (scheduled != null) { + scheduled.scheduleAtFixedRate(CheckSrvResponseTimerTask , heartBeatRetryTimeout*1000, heartBeatRetryTimeout*1000,TimeUnit.MILLISECONDS); //delay 3秒先检查一次,然后每5秒重试一次 + } + } + } + + private Runnable msendMsgAfterHeartbeat=new Runnable() { + @Override + public void run() { + connection.send(protocolAPIHelper.getBindingMSG(mRuntime)); + if (Config.protocol_no==Config.PROTOCOL_FZD){ + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + connection.send(protocolAPIHelper.getSyncTimeMSG(mRuntime)); + } + },5000); + } + } + }; + + public void checkSrvResponse(){ + + if (SimSignalUtil.checkNet(mRuntime.getContextProxy().context) ) { + + //如果收到服务器响应BP03,则停止重试,否则 继续发送AP03 心跳包,且继续检查响应 + if (this.is_heartBeat_send_success ) { + ICLogger.i("checkSrvResponse 成功,停止检测!"); + stopResponseCheckTimer(); + }else{ + //心跳发送失败,则认为已经和服务器断开 + mRuntime.setServerProtocolConnected(false); + //如果重试次数大于等于 最大重试次数,则停止重试,等下次心跳时间再行尝试。 + if (hearBeatResendCount >= MaxHeartbeatResendTime){ + ICLogger.i("checkSrvResponse "+hearBeatResendCount+"次 >= "+MaxHeartbeatResendTime+" , 则停止重试,等下次心跳时间再行尝试!"); + stopResponseCheckTimer(); + }else { + //重新发送AP03心跳包 + ICLogger.i("checkSrvResponse 失败,第" + hearBeatResendCount + "次,重新发送AP03心跳包!"); + //心跳开始发送的时候,先重置response检测标志 + is_heartBeat_send_success = false; + hearBeatResendCount++; + //更新系统的IMEI + boolean ret=DeviceInfoUtil.updateImei(mRuntime); + ICLogger.i("Update IMEI "+ret); + + //只有曾经login成功过,且上一次成功时间超过15分钟,才会自主断开网络。 + long currenttime=System.currentTimeMillis(); + ICLogger.i("只有曾经login或者心跳发送成功过,且上一次成功时间超过15分钟,才会自主断开网络! last longin time "+ + mRuntime.lastLoginSuccessTime+" ms from last login time "+(currenttime-mRuntime.lastLoginSuccessTime)); + if ((mRuntime.lastLoginSuccessTime>0) && ((currenttime- mRuntime.lastLoginSuccessTime) > 15 * 60 * 1000)) { + ICLogger.i("超时自主断开网络!"); + CoreService.getInstance().disconnect_server(); + }else { + if (is_login_send_success) { + connection.send(protocolAPIHelper.getHeartbeatMSG(mRuntime)); + } else { + connection.send(protocolAPIHelper.getLoginMSG(mRuntime)); + } + } + } + } + + }else{ + //没有网络就不用重新尝试连接网络了。网络连接后再重新尝试联网 + ICLogger.i("checkSrvResponse stop , 没有网络就不用重新尝试检测服务器响应和重新发送心跳包了!"); + + stopResponseCheckTimer(); + } + } + + + + public void stopResponseCheckTimer(){ + if (scheduled !=null){ + scheduled.shutdownNow(); +// Runnable tmp= scheduled.getQueue().poll(); +// while (tmp!=null){ +// scheduled.remove(tmp); +// } + scheduled.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); + scheduled.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); +// scheduled.setRemoveOnCancelPolicy(true); + ICLogger.i("Wait for thread pool getContinueExistingPeriodicTasksAfterShutdownPolicy " +scheduled.getContinueExistingPeriodicTasksAfterShutdownPolicy()+ + "\ngetExecuteExistingDelayedTasksAfterShutdownPolicy "+scheduled.getExecuteExistingDelayedTasksAfterShutdownPolicy());//+ +// "\ngetRemoveOnCancelPolicy "+scheduled.getRemoveOnCancelPolicy()); +// while(!scheduled.isTerminated()) +// { +// StringBuilder sb=new StringBuilder(); +// if (scheduled.isTerminated()) sb.append("+"); +// if (scheduled.isShutdown()) sb.append("*"); +// if (scheduled.isTerminating()) sb.append("-"); +// ICLogger.i(sb.toString()); +// try { +// Thread.sleep(500); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// } + scheduled.purge(); + scheduled = null; + } + + ICLogger.i(" stopResponseCheckTimer Done "); + } + + + + public void onAlarmClock(Connection paramConnection, Runtime paramRuntime) { + + ICLogger.i("onAlarmClock"); + + } + + public void onAttach(final Connection connection, final Runtime runtime) { + this.mRuntime = runtime; + this.mContext = (runtime.getContextProxy()).context; + this.mNetworkObservable.register(this.mContext); + this.connection = connection; + this.mSubscription = this.mNetworkObservable.onChange().subscribe(new Action1() { + private boolean first; + + public void call(Integer param1Integer) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("yls aBoolean="); + stringBuilder.append(param1Integer); + stringBuilder.append(",,first="); + stringBuilder.append(this.first); + ICLogger.i(stringBuilder.toString()); + if (param1Integer.intValue() > 1) { + //返回值大于0 证明是网络连接成功,开始重连服务器 + if (this.first) { + this.first = false; + return; + } + ICLogger.i("数据网络连接成功,重新连接服务器。"); + CoreService.getInstance().ReConnectToServer(); + } + } + }); + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction("android.intent.action.ACTION_SHUTDOWN"); + this.mShutDownReceiver = new ShutDownReceiver(); + this.mContext.registerReceiver(this.mShutDownReceiver, intentFilter); + } + + @Override + public boolean onConnectionClose(Connection paramConnection, Runtime paramRuntime, String ErrorMsg) { + + +// if (isConnected) + //如果KeepAlive被关闭说明网络有问题,因此开启重试联网机制 + stopResponseCheckTimer(); + + if (false) { + if (ErrorMsg.equals("DIS_CONNECT_BY_SERVERSIDE")) { + if (mDisconnectByServerCount < 3) {//被服务器拒绝连续拒绝3次后才停止重试 + CoreService.getInstance().startConnectionRetryTimer(); + } else { + ICLogger.i("服务器主动断开超过连续3次,IMEI不对或者命令格式错误!停止重试连接服务器,等待重启或者下一次网络重连。"); + } + mDisconnectByServerCount++; + } else { + mDisconnectByServerCount = 0; //如果不是被服务器拒绝,则重置 计数。 + CoreService.getInstance().startConnectionRetryTimer(); + } + }else{ + CoreService.getInstance().startConnectionRetryTimer(); + } + connectionError = true; + isConnected = false; + paramRuntime.setServerProtocolConnected(false); + + is_ping_send_success=false; + is_login_send_success=false; + is_heartBeat_send_success=false; + + //发送广播 服务器断开链接 + paramRuntime.getContextProxy().sendBroadcastServerConnectionChanged(false); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("onConnectionClose="); + stringBuilder.append(",set KeepAlive isConnected = false"); + ICLogger.i(stringBuilder.toString()); +// LauncherCtrl.getInstance(this.mContext).setStatusBarIcon("server_connected", STATUS_BAR_STATE_SERVER_CONNECTED_OFF); +//网络断开后,重连成功后发送一个定位 +// CoreService.needLocateInAfterHeartBeat=true; + return false; + } + public boolean onConnectionOpen(Connection paramConnection, Runtime paramRuntime) { + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("onConnectionOpen connectionError="); + stringBuilder.append(connectionError); + stringBuilder.append(",sInSleepMode ="); + stringBuilder.append(isInSleepMode); + stringBuilder.append(",set KeepAlive isConnected = true"); + ICLogger.i(stringBuilder.toString()); +// if (!connectionError) { + connectionError = false; + + //更新系统的IMEI + boolean ret=DeviceInfoUtil.updateImei(paramRuntime); + ICLogger.i("Update IMEI "+ret); + //发送登录包 + is_login_send_success=false; + + isConnected = true; + + Util.mSleep(1000); + + connection.send(protocolAPIHelper.getLoginMSG(paramRuntime)); + +// this.firstReConnected = true; +// this.idleTimeMillis = SystemClock.elapsedRealtime(); + + return false; + } + + public void onDetach(Connection paramConnection, Runtime paramRuntime) { + if (this.mSubscription != null && !this.mSubscription.isUnsubscribed()) + this.mSubscription.unsubscribe(); + this.mNetworkObservable.unregister(this.mContext); + this.mContext.unregisterReceiver(this.mShutDownReceiver); + } + + public void onHeartAlarm(Connection paramNettyConnection, Runtime paramRuntime) { + ICLogger.i("onHeartAlarm"); + + stopResponseCheckTimer(); + //心跳开始发送的时候,先重置response检测标志 + is_heartBeat_send_success=false; + + //这个是正常心跳包,暂时不能认为服务器连接时失败的,所以正常发送检测。 + //发送心跳包 + connection.send(protocolAPIHelper.getHeartbeatMSG(paramRuntime)); + //发送完心跳后,开始检查服务器响应 + startResponseCheckTimer(); + + + } + + public boolean onReceive(StringMessage paramStringMessage, Connection paramConnection, Runtime paramRuntime) { +// this.idleTimeMillis = SystemClock.elapsedRealtime(); + if ("heartbeat".equals(paramStringMessage.cmd())) { + AlarmWakeUp.isNeedWakeUpAlarm(paramRuntime); + +// 收到心跳才认为是已经连接了服务器 + paramRuntime.setServerProtocolConnected(true); +// isConnected = true; + is_heartBeat_send_success=true; + paramRuntime.lastLoginSuccessTime=System.currentTimeMillis(); +// LauncherCtrl.getInstance(this.mContext).setStatusBarIcon("server_connected", STATUS_BAR_STATE_SERVER_CONNECTED_ON); +// Deliver.triggerSendThread(); //链接上就尝试清除 buffer中的数据 + + if(!is_ping_send_success) { + //心跳结束后执行,且只在重新登陆后执行一次 + mHandler.post(msendMsgAfterHeartbeat); + is_ping_send_success=true; + } + if (CoreService.needLocateInAfterHeartBeat==true){ + //第一次启动或者系统Close后重连的时候,重置LocationCycle + CoreService.needLocateInAfterHeartBeat=false; + LocationClient.setForceLocation(1); + CoreService.getInstance().setLocationAlarm(paramRuntime.getLocationInstance().getWorkingMod()); + } + }else if (paramStringMessage.cmd().equals("login")) { + //广播服务器连接成功的消息 + paramRuntime.getContextProxy().sendBroadcastServerConnectionChanged(true); + //登录包收到就停止重链接服务器 + CoreService.getInstance().stopConnectionRetryTimer(); + is_login_send_success=true; + //收到登录包反馈后再发送心跳 + + //心跳开始发送的时候,先重置response检测标志 + is_heartBeat_send_success=false; + is_ping_send_success=false; + paramRuntime.lastLoginSuccessTime=System.currentTimeMillis(); + //发送心跳包 + + //这时重新连接服务器才进行的连接,理论上close已经设置false,此次可以认为协议定然断开,所以设置为false作为双重保险。 + mRuntime.setServerProtocolConnected(false); + connection.send(protocolAPIHelper.getHeartbeatMSG(paramRuntime)); + //发送完心跳后,开始检查服务器响应 + + startResponseCheckTimer(); + + + } + return false; + } + + + public void setSleepMode(boolean paramBoolean) { + isInSleepMode = paramBoolean; + } + + class ShutDownReceiver extends BroadcastReceiver { + public void onReceive(Context param1Context, Intent param1Intent) { + boolean bool = param1Intent.getBooleanExtra("reboot", false); + ICLogger.i("Shutdown Received! reboot="+bool); + if (!bool && !KeepAlive.this.mRuntime.isShutdown()){ + /*电量低,不是重启,且不是服务器让关闭的*/ + KeepAlive.this.mRuntime.setAlarmType(Runtime.AlarmType.ALARM_POWER_OFF); + ICLogger.i("triggerSOSLocationProcess "); + LocationClient.getInstance().triggerSOSLocationProcess(); +// Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(KeepAlive.this.mRuntime)); + ICLogger.i("Shutdown Received! send AP10 !"); + } + } + } +} diff --git a/app/src/main/java/com/enqualcomm/support/service/SilentManager.java b/app/src/main/java/com/enqualcomm/support/service/SilentManager.java index 2334d42c..3e29f437 100644 --- a/app/src/main/java/com/enqualcomm/support/service/SilentManager.java +++ b/app/src/main/java/com/enqualcomm/support/service/SilentManager.java @@ -23,6 +23,7 @@ import com.enqualcomm.support.ICContentProvider; import com.enqualcomm.support.MainActivity; import com.enqualcomm.support.bean.Alarm; import com.enqualcomm.support.bean.Antioff; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.NoticeContent; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.bean.Silent; @@ -70,7 +71,12 @@ public class SilentManager extends AbstractInvokeHandlerService { AlarmManager mAlarmManager; private SilentManager.AlramReceiver mAlramReceiver; Connection mConnection; - ContentObserver mContentObserver = new ContentObserver(new Handler()) { + + private static Handler mHandler; + static{ + mHandler = new Handler(EventLooperHandlerThread.makeLooper(SilentManager.class.getSimpleName())); + } + ContentObserver mContentObserver = new ContentObserver(mHandler) { public void onChange(boolean var1) { ICLogger.i("静默有变化"); SilentManager.this.silentList = SilentManager.this.querySilent(); @@ -123,7 +129,7 @@ public class SilentManager extends AbstractInvokeHandlerService { if(ICAudioManager.needMute==true) { // ICAudioManager.restoreVolumn(mContext); //2秒后恢复音量 - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { ICAudioManager.restoreVolumn(mContext); //2秒后恢复音量 @@ -145,7 +151,7 @@ public class SilentManager extends AbstractInvokeHandlerService { if(ICAudioManager.needMute==true) { ICAudioManager.setVolumnMute(mContext); - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { ICAudioManager.setVolumnMute(mContext); //2秒后恢复音量 @@ -168,7 +174,7 @@ public class SilentManager extends AbstractInvokeHandlerService { if(ICAudioManager.needMute==true) { ICAudioManager.setVolumnMute(mContext); - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { ICAudioManager.setVolumnMute(mContext); //2秒后恢复音量 diff --git a/app/src/main/java/com/enqualcomm/support/utils/BatteryUtil.java b/app/src/main/java/com/enqualcomm/support/utils/BatteryUtil.java index 1b7cb2a0..473c6129 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/BatteryUtil.java +++ b/app/src/main/java/com/enqualcomm/support/utils/BatteryUtil.java @@ -14,6 +14,7 @@ import android.os.PowerManager; import com.enqualcomm.support.Config; import com.enqualcomm.support.CoreService; import com.enqualcomm.support.LocationClient; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.service.AntiMonitorService; import com.enqualcomm.support.service.AudioService; import com.enqualcomm.support.service.Deliver; @@ -225,7 +226,7 @@ public class BatteryUtil { connection = _connection; if (mHandler==null) { - mHandler = new Handler() { + mHandler = new Handler(EventLooperHandlerThread.makeLooper(BatteryUtil.class.getSimpleName())) { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 100) { diff --git a/app/src/main/java/com/enqualcomm/support/utils/ContextProxy.java b/app/src/main/java/com/enqualcomm/support/utils/ContextProxy.java index 412a2ba8..a7fca225 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/ContextProxy.java +++ b/app/src/main/java/com/enqualcomm/support/utils/ContextProxy.java @@ -1,503 +1,505 @@ -package com.enqualcomm.support.utils; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.content.ContentResolver; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.hardware.SensorManager; -import android.location.LocationManager; -import android.net.Uri; -import android.net.wifi.WifiManager; -import android.os.Build; -import android.os.Environment; -import android.os.Handler; -import android.os.PowerManager; -import android.telephony.TelephonyManager; -import android.util.Log; - - -import com.enqualcomm.support.Config; -import com.enqualcomm.support.Constants; -import com.enqualcomm.support.ICContentProvider; -import com.enqualcomm.support.R; -import com.enqualcomm.support.bean.Alarm; -import com.enqualcomm.support.bean.NoticeContent; -import com.enqualcomm.support.bean.Silent; -import com.enqualcomm.support.bean.Runtime; -import com.enqualcomm.support.bean.VoiceContent; -import com.enqualcomm.support.service.AudioService; -import com.enqualcomm.support.service.Deliver; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Iterator; -import java.util.concurrent.TimeUnit; - - -import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; -import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; -import static com.enqualcomm.support.Constants.ACTION_ISCONNECTED; -import static com.enqualcomm.support.Constants.ACTION_KEEPSIT_ALARM; -import static com.enqualcomm.support.Constants.ACTION_SIT_ALARM; -import static com.enqualcomm.support.Constants.ActionReceivePushTxt; -import static com.enqualcomm.support.Constants.ActionSrvPushTxt; -import static com.enqualcomm.support.Constants.DIALOG_ACTION; - -public class ContextProxy { - private static final long ONE_WEEK = 604800000L; - - private final AlarmManager alarmManager; - - public Context context; - - private final LocationManager locationManager; - - private final ContentResolver resolver; - - private final SensorManager sensorManager; - - private final TelephonyManager telephonyManager; - - private final WifiManager wifiManager; - - public ContextProxy(Context _context) { - this.context = _context; - this.resolver = context.getContentResolver(); - this.locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); - this.alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); - this.telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); - this.wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); - this.sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); - } - - private PendingIntent getPendingIntent(String paramString1, String paramString2, String paramString3, String name, int paramInt) { - StringBuilder stringBuilder = new StringBuilder("alarm:"); - stringBuilder.append(paramString1); - stringBuilder.append(","); - stringBuilder.append(paramString2); - stringBuilder.append(","); - stringBuilder.append(paramString3); - stringBuilder.append(","); - stringBuilder.append(name); - stringBuilder.append(","); - stringBuilder.append(paramInt); - Intent intent = new Intent("com.enqualcomm.icare.ALARM", Uri.parse(stringBuilder.toString())); - return PendingIntent.getActivity(this.context, 0, intent, FLAG_UPDATE_CURRENT); - } - - private PendingIntent getPendingIntent(String noticeTime, String noticeName, String noticeNumber, String noticeID, String noticeCategory, String noticeFrequency, String noticeContent) { - StringBuilder stringBuilder = new StringBuilder("notice:"); - stringBuilder.append(noticeTime); - stringBuilder.append(","); - stringBuilder.append(noticeName); - stringBuilder.append(","); - stringBuilder.append(noticeNumber); - stringBuilder.append(","); - stringBuilder.append(noticeID); - stringBuilder.append(","); - stringBuilder.append(noticeCategory); - stringBuilder.append(","); - stringBuilder.append(noticeFrequency); - stringBuilder.append(","); - stringBuilder.append(noticeContent); - Intent intent = new Intent("com.enqualcomm.icare.NOTICE", Uri.parse(stringBuilder.toString())); - - return PendingIntent.getActivity(this.context, 0, intent, FLAG_UPDATE_CURRENT); - } - - private void initAlarmAndSilent() { - - Calendar calendar2 = Calendar.getInstance(); - calendar2.set(Calendar.SECOND, 0); - long l = System.currentTimeMillis(); - Cursor cursor2 = this.context.getContentResolver().query(ICContentProvider.ALARM_URI, null, null, null, null); - byte b2 = 3; - byte b1 = 5; - char c = '\002'; - if (cursor2 != null) { - while (cursor2.moveToNext()) { - try { - if ("ON".equals(cursor2.getString(4))) { - String str2 = cursor2.getString(1); - String str1 = cursor2.getString(c); - String str3 = cursor2.getString(b2); - String str4 = cursor2.getString(b1); - calendar2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str2.substring(c, 4))); - calendar2.set(Calendar.MINUTE, Integer.parseInt(str2.substring(b1, 7))); - char[] arrayOfChar = str1.toCharArray(); - int i = arrayOfChar.length; - byte b = 1; - while (b < i) { - c = (char) (arrayOfChar[b] - '/'); //将ascii数字字符转换为对应的数字 - calendar2.set(Calendar.DAY_OF_WEEK, c); - long l1 = calendar2.getTimeInMillis(); - if (l1 <= l) - l1 += ONE_WEEK; - PendingIntent pendingIntent = getPendingIntent(str2, str1, str3, str4, c); - AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); - b++; - c = '\002'; - b1 = 5; - b2 = 3; - } - } - }catch (Exception e){ - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - } - cursor2.close(); - } - Calendar calendar1 = Calendar.getInstance(); - calendar1.set(Calendar.SECOND, 0); - Cursor cursor1 = this.context.getContentResolver().query(ICContentProvider.NOTICE_URL, null, null, null, null); - if (cursor1 != null) { - while (cursor1.moveToNext()) { - try { - String str1 = cursor1.getString(1); - String str2 = cursor1.getString(2); - String str3 = cursor1.getString(3); - String str4 = cursor1.getString(4); - String str5 = cursor1.getString(5); - String str6 = cursor1.getString(6); - String str7 = cursor1.getString(6); - if (str1 != null) { - String year = str1.substring(0, 4); - String month = str1.substring(4, 6); - String day = str1.substring(6, 8); - String hour = str1.substring(8, 10); - String minute = str1.substring(10, 12); - calendar1.set(Calendar.YEAR, Integer.parseInt(year)); - calendar1.set(Calendar.MONTH, Integer.parseInt(month)); - calendar1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day)); - calendar1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour)); - calendar1.set(Calendar.MINUTE, Integer.parseInt(minute)); - long l1 = calendar1.getTimeInMillis(); - if (l1 > l) { - PendingIntent pendingIntent = getPendingIntent(str1, str2, str3, str4, str5, str6, str7); - AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); - } - } - }catch (Exception e){ - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - } - cursor1.close(); - } - } - - public LocationManager getLocationManager() { return this.locationManager; } - - public ContentResolver getResolver() { return this.resolver; } - - public SensorManager getSensorManager() { return this.sensorManager; } - - public TelephonyManager getTelephonyManager() { return this.telephonyManager; } - - public WifiManager getWifiManager() { return this.wifiManager; } - - - public void resolverAlarm(ArrayList paramArrayList) { - Cursor cursor = this.context.getContentResolver().query(ICContentProvider.ALARM_URI, null, null, null, null); - char c = '\001'; - if (cursor != null) { - while (cursor.moveToNext()) { - if ("ON".equals(cursor.getString(4))) { - String str1 = cursor.getString(c); - String str2 = cursor.getString(2); - String str3 = cursor.getString(3); - String str4 = cursor.getString(5); - char[] arrayOfChar = str2.toCharArray(); - int i = arrayOfChar.length; - byte b = 1; - while (b < i) { - c = arrayOfChar[b]; - this.alarmManager.cancel(getPendingIntent(str1, str2, str3, str4, c - '/')); - b++; - c = '\001'; - } - } - } - cursor.close(); - } - Calendar calendar = Calendar.getInstance(); - calendar.set(Calendar.SECOND, 0); - long l = System.currentTimeMillis(); - for (Alarm alarm : paramArrayList) { - long l1 = l; - - if ("ON".equals(alarm.status)) { - try { - int i = Integer.parseInt(alarm.time.substring(2, 4)); - int j = Integer.parseInt(alarm.time.substring(5, 7)); - calendar.set(Calendar.HOUR_OF_DAY, i); - calendar.set(Calendar.MINUTE, j); - char[] arrayOfChar = alarm.week.toCharArray(); - i = arrayOfChar.length; - j = 1; - while (true) { - l1 = l; - if (j < i) { - c = (char) (arrayOfChar[j] - '/'); - calendar.set(Calendar.DAY_OF_WEEK, c); - long l2 = calendar.getTimeInMillis(); - l1 = l2; - if (l2 <= l) - l1 = l2 + ONE_WEEK; - PendingIntent pendingIntent = getPendingIntent(alarm.time, alarm.week, alarm.ring, alarm.name, c); - AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); - j++; - continue; - } - break; - } - }catch (Exception e){ - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - } - l = l1; - } - } - - public void resolverNotice(ArrayList paramArrayList) { - Cursor cursor = this.context.getContentResolver().query(ICContentProvider.NOTICE_URL, null, null, null, null); - if (cursor != null) { - while (cursor.moveToNext()) { - String str1 = cursor.getString(1); - String str2 = cursor.getString(2); - String str3 = cursor.getString(3); - String str4 = cursor.getString(4); - String str5 = cursor.getString(5); - String str6 = cursor.getString(6); - String str7 = cursor.getString(6); - this.alarmManager.cancel(getPendingIntent(str1, str2, str3, str4, str5, str6, str7)); - } - cursor.close(); - } - for (NoticeContent noticeContent : paramArrayList) { - String str1 = noticeContent.noticeTime; - String str2 = noticeContent.noticeName; - String str3 = noticeContent.noticeNumber; - String str4 = noticeContent.noticeID; - String str5 = noticeContent.noticeCategory; - String str6 = noticeContent.noticeFrequency; - String str7 = noticeContent.noticeContent; - Calendar calendar = Calendar.getInstance(); - long l = System.currentTimeMillis(); - calendar.set(Calendar.SECOND, 0); - if (str1 != null) { - try { - String str8 = str1.substring(0, 4); - String str9 = str1.substring(4, 6); - String str10 = str1.substring(6, 8); - String str11 = str1.substring(8, 10); - String str12 = str1.substring(10, 12); - calendar.set(Calendar.YEAR, Integer.parseInt(str8)); - calendar.set(Calendar.MONTH, Integer.parseInt(str9) - 1); - calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(str10)); - calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str11)); - calendar.set(Calendar.MINUTE, Integer.parseInt(str12)); - long l1 = calendar.getTimeInMillis(); - if (l1 >= l) { - PendingIntent pendingIntent = getPendingIntent(str1, str2, str3, str4, str5, str6, str7); - AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); - } - }catch (Exception e){ - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - } - } - } - private static final String PED_TOTAL_KEY = "PED_TOTAL"; - private static final String PED_FINISH_ACTION = "com.ic.action.PED_FINISH"; - public void brodcastResetStepCount(int StepCount){ - Intent intent = new Intent(); - intent.putExtra(PED_TOTAL_KEY, StepCount); - intent.setAction(PED_FINISH_ACTION); - ICLogger.i("send broadcast action "+PED_FINISH_ACTION+", key "+PED_TOTAL_KEY+" value "+StepCount); - this.context.sendBroadcast(intent); - } - public void sendBrodcast(String action,Intent intent){ - intent.setAction(action); - ICLogger.i("send broadcast action "+action); - this.context.sendBroadcast(intent); - } - - public void sendBroadcast(String cmd, Runtime dev) { - 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 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 sendBroadcastServerConnectionChanged(boolean paramBoolean) { - Intent intent = new Intent(); - intent.setAction(ACTION_ISCONNECTED); - intent.putExtra("isConnected", paramBoolean); - Util.setSystemProperties("persist.sys.server_connected",paramBoolean?"true":"false"); - this.context.sendBroadcast(intent); - } - - public void saveMstToSMSDB(String msg){ - Intent intent = new Intent(); - intent.setAction(ActionReceivePushTxt); - intent.putExtra("txtMsg", msg); - intent.addFlags(FLAG_ACTIVITY_NEW_TASK); - this.context.sendBroadcast(intent); - } - public void sendMsgBroadcast(String msg, int msgType) { - sendMsgBroadcast(this.context,msg,msgType); - } - private static void play_waning_notify(Context context){ - AudioService.getInstance().play(context.getAssets(), "warning.mp3"); - } - public static void sendMsgBroadcast(Context _context,String msg, int msgType) { - - if (msgType==0) { - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - //本应用弹出消息框 - if (Config.noPushTxtNotifyDialog == false) { - Intent intent = new Intent(); - intent.setAction(DIALOG_ACTION); - intent.putExtra("pushtxt", msg); - _context.sendBroadcast(intent); - } else { - WakeLockUtil.ScreenOnWakeLockTemperary(_context); - play_waning_notify(_context); - VibrateUtil.getInstance(_context).VibrateOnOnce(true); - Util.mSleep(2000); - } - //launcher 弹出消息 - if(Config.noBroadCastPushTxtNotify==false) { - Intent intent = new Intent(ActionSrvPushTxt); - intent.putExtra("msgType", msgType); //0 代表 server下发消息,1代表 SMS消息 - intent.putExtra("txtMsg", msg); - intent.addFlags(FLAG_ACTIVITY_NEW_TASK); - _context.sendBroadcast(intent); - } - } - },50); - - }else if (msgType==2) { - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - //本应用弹出消息框 - if (Config.noPushTxtNotifyDialog == false) { - Intent intent = new Intent(); - intent.setAction(DIALOG_ACTION); - intent.putExtra("pushtxt", msg); - _context.sendBroadcast(intent); - } else { - WakeLockUtil.ScreenOnWakeLockTemperary(_context); - play_waning_notify(_context); - VibrateUtil.getInstance(_context).VibrateOnOnce(true); - Util.mSleep(2000); - } - //launcher 弹出消息 - if (Config.noBroadCastPushTxtNotify == false) { - Intent intent = new Intent(ActionSrvPushTxt); - intent.putExtra("msgType", msgType); //0 代表 server下发消息,1代表 SMS消息,2代表有提示音的消息 - intent.putExtra("txtMsg", msg); - intent.addFlags(FLAG_ACTIVITY_NEW_TASK); - _context.sendBroadcast(intent); - } - } - }, 50); - - }else if (msgType==3){ //专门给需要回复的消息 - - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - //本应用弹出消息框 - if (Config.noPushTxtNotifyDialog == false) { - Intent intent = new Intent(); - intent.setAction(DIALOG_ACTION); - intent.putExtra("pushtxt", msg); - intent.putExtra("needreply",true); - _context.sendBroadcast(intent); - } else { - WakeLockUtil.ScreenOnWakeLockTemperary(_context); - play_waning_notify(_context); - VibrateUtil.getInstance(_context).VibrateOnOnce(true); - Util.mSleep(2000); - } - - } - },50); - }else{ - - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - //本应用弹出消息框 - if(Config.noSMSNotifyDialog==false) { - Intent intent = new Intent(); - intent.setAction(DIALOG_ACTION); - intent.putExtra("sms", msg); - _context.sendBroadcast(intent); - }else{ - WakeLockUtil.ScreenOnWakeLockTemperary(_context); - play_waning_notify(_context); - VibrateUtil.getInstance(_context).VibrateOnOnce(true); - Util.mSleep(2000); - } - //launcher 弹出消息 - if(Config.noBroadCastPushTxtNotify==false) { - Intent intent = new Intent(ActionSrvPushTxt); - intent.putExtra("msgType", msgType); //0 代表 server下发消息,1代表 SMS消息,2代表有提示音的消息 - intent.putExtra("txtMsg", msg); - intent.addFlags(FLAG_ACTIVITY_NEW_TASK); - _context.sendBroadcast(intent); - } - } - },50); - } - - - - - } - public void sendStheartRateBroadcast(String paramString, int paramInt) { - Intent intent = new Intent(); - intent.setAction(paramString); - intent.putExtra("stheartRateType", paramInt); - this.context.sendBroadcast(intent, "com.eqc.broadcast.permission"); - } - public void sendBroadcastSitLongAlarm() { - - if (Util.installed(context,"com.ic.ak.launcher")) { - Intent intent = new Intent(); - intent.setAction(ACTION_KEEPSIT_ALARM); - intent.addFlags(FLAG_ACTIVITY_NEW_TASK); - this.context.sendBroadcast(intent); - }else { - Intent intent = new Intent(); - //显示提示窗口 - intent.setAction(DIALOG_ACTION); - intent.putExtra("takephoto", context.getResources().getString(R.string.sedentary_msg)); - context.sendBroadcast(intent); - } - } - -} - - +package com.enqualcomm.support.utils; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.hardware.SensorManager; +import android.location.LocationManager; +import android.net.Uri; +import android.net.wifi.WifiManager; +import android.os.Build; +import android.os.Environment; +import android.os.Handler; +import android.os.PowerManager; +import android.telephony.TelephonyManager; +import android.util.Log; + + +import com.enqualcomm.support.Config; +import com.enqualcomm.support.Constants; +import com.enqualcomm.support.ICContentProvider; +import com.enqualcomm.support.R; +import com.enqualcomm.support.bean.Alarm; +import com.enqualcomm.support.bean.EventLooperHandlerThread; +import com.enqualcomm.support.bean.NoticeContent; +import com.enqualcomm.support.bean.Silent; +import com.enqualcomm.support.bean.Runtime; +import com.enqualcomm.support.bean.VoiceContent; +import com.enqualcomm.support.service.AudioService; +import com.enqualcomm.support.service.Deliver; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; +import java.util.concurrent.TimeUnit; + + +import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; +import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; +import static com.enqualcomm.support.Constants.ACTION_ISCONNECTED; +import static com.enqualcomm.support.Constants.ACTION_KEEPSIT_ALARM; +import static com.enqualcomm.support.Constants.ACTION_SIT_ALARM; +import static com.enqualcomm.support.Constants.ActionReceivePushTxt; +import static com.enqualcomm.support.Constants.ActionSrvPushTxt; +import static com.enqualcomm.support.Constants.DIALOG_ACTION; + +public class ContextProxy { + private static final long ONE_WEEK = 604800000L; + + private final AlarmManager alarmManager; + + public Context context; + + private final LocationManager locationManager; + + private final ContentResolver resolver; + + private final SensorManager sensorManager; + + private final TelephonyManager telephonyManager; + + private final WifiManager wifiManager; + private static Handler mHandler=new Handler(EventLooperHandlerThread.makeLooper(ContextProxy.class.getSimpleName())); + public ContextProxy(Context _context) { + this.context = _context; + this.resolver = context.getContentResolver(); + this.locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); + this.alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); + this.telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); + this.wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); + this.sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); + + } + + private PendingIntent getPendingIntent(String paramString1, String paramString2, String paramString3, String name, int paramInt) { + StringBuilder stringBuilder = new StringBuilder("alarm:"); + stringBuilder.append(paramString1); + stringBuilder.append(","); + stringBuilder.append(paramString2); + stringBuilder.append(","); + stringBuilder.append(paramString3); + stringBuilder.append(","); + stringBuilder.append(name); + stringBuilder.append(","); + stringBuilder.append(paramInt); + Intent intent = new Intent("com.enqualcomm.icare.ALARM", Uri.parse(stringBuilder.toString())); + return PendingIntent.getActivity(this.context, 0, intent, FLAG_UPDATE_CURRENT); + } + + private PendingIntent getPendingIntent(String noticeTime, String noticeName, String noticeNumber, String noticeID, String noticeCategory, String noticeFrequency, String noticeContent) { + StringBuilder stringBuilder = new StringBuilder("notice:"); + stringBuilder.append(noticeTime); + stringBuilder.append(","); + stringBuilder.append(noticeName); + stringBuilder.append(","); + stringBuilder.append(noticeNumber); + stringBuilder.append(","); + stringBuilder.append(noticeID); + stringBuilder.append(","); + stringBuilder.append(noticeCategory); + stringBuilder.append(","); + stringBuilder.append(noticeFrequency); + stringBuilder.append(","); + stringBuilder.append(noticeContent); + Intent intent = new Intent("com.enqualcomm.icare.NOTICE", Uri.parse(stringBuilder.toString())); + + return PendingIntent.getActivity(this.context, 0, intent, FLAG_UPDATE_CURRENT); + } + + private void initAlarmAndSilent() { + + Calendar calendar2 = Calendar.getInstance(); + calendar2.set(Calendar.SECOND, 0); + long l = System.currentTimeMillis(); + Cursor cursor2 = this.context.getContentResolver().query(ICContentProvider.ALARM_URI, null, null, null, null); + byte b2 = 3; + byte b1 = 5; + char c = '\002'; + if (cursor2 != null) { + while (cursor2.moveToNext()) { + try { + if ("ON".equals(cursor2.getString(4))) { + String str2 = cursor2.getString(1); + String str1 = cursor2.getString(c); + String str3 = cursor2.getString(b2); + String str4 = cursor2.getString(b1); + calendar2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str2.substring(c, 4))); + calendar2.set(Calendar.MINUTE, Integer.parseInt(str2.substring(b1, 7))); + char[] arrayOfChar = str1.toCharArray(); + int i = arrayOfChar.length; + byte b = 1; + while (b < i) { + c = (char) (arrayOfChar[b] - '/'); //将ascii数字字符转换为对应的数字 + calendar2.set(Calendar.DAY_OF_WEEK, c); + long l1 = calendar2.getTimeInMillis(); + if (l1 <= l) + l1 += ONE_WEEK; + PendingIntent pendingIntent = getPendingIntent(str2, str1, str3, str4, c); + AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); + b++; + c = '\002'; + b1 = 5; + b2 = 3; + } + } + }catch (Exception e){ + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + } + cursor2.close(); + } + Calendar calendar1 = Calendar.getInstance(); + calendar1.set(Calendar.SECOND, 0); + Cursor cursor1 = this.context.getContentResolver().query(ICContentProvider.NOTICE_URL, null, null, null, null); + if (cursor1 != null) { + while (cursor1.moveToNext()) { + try { + String str1 = cursor1.getString(1); + String str2 = cursor1.getString(2); + String str3 = cursor1.getString(3); + String str4 = cursor1.getString(4); + String str5 = cursor1.getString(5); + String str6 = cursor1.getString(6); + String str7 = cursor1.getString(6); + if (str1 != null) { + String year = str1.substring(0, 4); + String month = str1.substring(4, 6); + String day = str1.substring(6, 8); + String hour = str1.substring(8, 10); + String minute = str1.substring(10, 12); + calendar1.set(Calendar.YEAR, Integer.parseInt(year)); + calendar1.set(Calendar.MONTH, Integer.parseInt(month)); + calendar1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day)); + calendar1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour)); + calendar1.set(Calendar.MINUTE, Integer.parseInt(minute)); + long l1 = calendar1.getTimeInMillis(); + if (l1 > l) { + PendingIntent pendingIntent = getPendingIntent(str1, str2, str3, str4, str5, str6, str7); + AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); + } + } + }catch (Exception e){ + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + } + cursor1.close(); + } + } + + public LocationManager getLocationManager() { return this.locationManager; } + + public ContentResolver getResolver() { return this.resolver; } + + public SensorManager getSensorManager() { return this.sensorManager; } + + public TelephonyManager getTelephonyManager() { return this.telephonyManager; } + + public WifiManager getWifiManager() { return this.wifiManager; } + + + public void resolverAlarm(ArrayList paramArrayList) { + Cursor cursor = this.context.getContentResolver().query(ICContentProvider.ALARM_URI, null, null, null, null); + char c = '\001'; + if (cursor != null) { + while (cursor.moveToNext()) { + if ("ON".equals(cursor.getString(4))) { + String str1 = cursor.getString(c); + String str2 = cursor.getString(2); + String str3 = cursor.getString(3); + String str4 = cursor.getString(5); + char[] arrayOfChar = str2.toCharArray(); + int i = arrayOfChar.length; + byte b = 1; + while (b < i) { + c = arrayOfChar[b]; + this.alarmManager.cancel(getPendingIntent(str1, str2, str3, str4, c - '/')); + b++; + c = '\001'; + } + } + } + cursor.close(); + } + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.SECOND, 0); + long l = System.currentTimeMillis(); + for (Alarm alarm : paramArrayList) { + long l1 = l; + + if ("ON".equals(alarm.status)) { + try { + int i = Integer.parseInt(alarm.time.substring(2, 4)); + int j = Integer.parseInt(alarm.time.substring(5, 7)); + calendar.set(Calendar.HOUR_OF_DAY, i); + calendar.set(Calendar.MINUTE, j); + char[] arrayOfChar = alarm.week.toCharArray(); + i = arrayOfChar.length; + j = 1; + while (true) { + l1 = l; + if (j < i) { + c = (char) (arrayOfChar[j] - '/'); + calendar.set(Calendar.DAY_OF_WEEK, c); + long l2 = calendar.getTimeInMillis(); + l1 = l2; + if (l2 <= l) + l1 = l2 + ONE_WEEK; + PendingIntent pendingIntent = getPendingIntent(alarm.time, alarm.week, alarm.ring, alarm.name, c); + AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); + j++; + continue; + } + break; + } + }catch (Exception e){ + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + } + l = l1; + } + } + + public void resolverNotice(ArrayList paramArrayList) { + Cursor cursor = this.context.getContentResolver().query(ICContentProvider.NOTICE_URL, null, null, null, null); + if (cursor != null) { + while (cursor.moveToNext()) { + String str1 = cursor.getString(1); + String str2 = cursor.getString(2); + String str3 = cursor.getString(3); + String str4 = cursor.getString(4); + String str5 = cursor.getString(5); + String str6 = cursor.getString(6); + String str7 = cursor.getString(6); + this.alarmManager.cancel(getPendingIntent(str1, str2, str3, str4, str5, str6, str7)); + } + cursor.close(); + } + for (NoticeContent noticeContent : paramArrayList) { + String str1 = noticeContent.noticeTime; + String str2 = noticeContent.noticeName; + String str3 = noticeContent.noticeNumber; + String str4 = noticeContent.noticeID; + String str5 = noticeContent.noticeCategory; + String str6 = noticeContent.noticeFrequency; + String str7 = noticeContent.noticeContent; + Calendar calendar = Calendar.getInstance(); + long l = System.currentTimeMillis(); + calendar.set(Calendar.SECOND, 0); + if (str1 != null) { + try { + String str8 = str1.substring(0, 4); + String str9 = str1.substring(4, 6); + String str10 = str1.substring(6, 8); + String str11 = str1.substring(8, 10); + String str12 = str1.substring(10, 12); + calendar.set(Calendar.YEAR, Integer.parseInt(str8)); + calendar.set(Calendar.MONTH, Integer.parseInt(str9) - 1); + calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(str10)); + calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str11)); + calendar.set(Calendar.MINUTE, Integer.parseInt(str12)); + long l1 = calendar.getTimeInMillis(); + if (l1 >= l) { + PendingIntent pendingIntent = getPendingIntent(str1, str2, str3, str4, str5, str6, str7); + AlarmHelper.setAlarm(this.alarmManager, l1, pendingIntent); + } + }catch (Exception e){ + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + } + } + } + private static final String PED_TOTAL_KEY = "PED_TOTAL"; + private static final String PED_FINISH_ACTION = "com.ic.action.PED_FINISH"; + public void brodcastResetStepCount(int StepCount){ + Intent intent = new Intent(); + intent.putExtra(PED_TOTAL_KEY, StepCount); + intent.setAction(PED_FINISH_ACTION); + ICLogger.i("send broadcast action "+PED_FINISH_ACTION+", key "+PED_TOTAL_KEY+" value "+StepCount); + this.context.sendBroadcast(intent); + } + public void sendBrodcast(String action,Intent intent){ + intent.setAction(action); + ICLogger.i("send broadcast action "+action); + this.context.sendBroadcast(intent); + } + + public void sendBroadcast(String cmd, Runtime dev) { + 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 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 sendBroadcastServerConnectionChanged(boolean paramBoolean) { + Intent intent = new Intent(); + intent.setAction(ACTION_ISCONNECTED); + intent.putExtra("isConnected", paramBoolean); + Util.setSystemProperties("persist.sys.server_connected",paramBoolean?"true":"false"); + this.context.sendBroadcast(intent); + } + + public void saveMstToSMSDB(String msg){ + Intent intent = new Intent(); + intent.setAction(ActionReceivePushTxt); + intent.putExtra("txtMsg", msg); + intent.addFlags(FLAG_ACTIVITY_NEW_TASK); + this.context.sendBroadcast(intent); + } + public void sendMsgBroadcast(String msg, int msgType) { + sendMsgBroadcast(this.context,msg,msgType); + } + private static void play_waning_notify(Context context){ + AudioService.getInstance().play(context.getAssets(), "warning.mp3"); + } + public static void sendMsgBroadcast(Context _context,String msg, int msgType) { + + if (msgType==0) { + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + //本应用弹出消息框 + if (Config.noPushTxtNotifyDialog == false) { + Intent intent = new Intent(); + intent.setAction(DIALOG_ACTION); + intent.putExtra("pushtxt", msg); + _context.sendBroadcast(intent); + } else { + WakeLockUtil.ScreenOnWakeLockTemperary(_context); + play_waning_notify(_context); + VibrateUtil.getInstance(_context).VibrateOnOnce(true); + Util.mSleep(2000); + } + //launcher 弹出消息 + if(Config.noBroadCastPushTxtNotify==false) { + Intent intent = new Intent(ActionSrvPushTxt); + intent.putExtra("msgType", msgType); //0 代表 server下发消息,1代表 SMS消息 + intent.putExtra("txtMsg", msg); + intent.addFlags(FLAG_ACTIVITY_NEW_TASK); + _context.sendBroadcast(intent); + } + } + },50); + + }else if (msgType==2) { + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + //本应用弹出消息框 + if (Config.noPushTxtNotifyDialog == false) { + Intent intent = new Intent(); + intent.setAction(DIALOG_ACTION); + intent.putExtra("pushtxt", msg); + _context.sendBroadcast(intent); + } else { + WakeLockUtil.ScreenOnWakeLockTemperary(_context); + play_waning_notify(_context); + VibrateUtil.getInstance(_context).VibrateOnOnce(true); + Util.mSleep(2000); + } + //launcher 弹出消息 + if (Config.noBroadCastPushTxtNotify == false) { + Intent intent = new Intent(ActionSrvPushTxt); + intent.putExtra("msgType", msgType); //0 代表 server下发消息,1代表 SMS消息,2代表有提示音的消息 + intent.putExtra("txtMsg", msg); + intent.addFlags(FLAG_ACTIVITY_NEW_TASK); + _context.sendBroadcast(intent); + } + } + }, 50); + + }else if (msgType==3){ //专门给需要回复的消息 + + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + //本应用弹出消息框 + if (Config.noPushTxtNotifyDialog == false) { + Intent intent = new Intent(); + intent.setAction(DIALOG_ACTION); + intent.putExtra("pushtxt", msg); + intent.putExtra("needreply",true); + _context.sendBroadcast(intent); + } else { + WakeLockUtil.ScreenOnWakeLockTemperary(_context); + play_waning_notify(_context); + VibrateUtil.getInstance(_context).VibrateOnOnce(true); + Util.mSleep(2000); + } + + } + },50); + }else{ + + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + //本应用弹出消息框 + if(Config.noSMSNotifyDialog==false) { + Intent intent = new Intent(); + intent.setAction(DIALOG_ACTION); + intent.putExtra("sms", msg); + _context.sendBroadcast(intent); + }else{ + WakeLockUtil.ScreenOnWakeLockTemperary(_context); + play_waning_notify(_context); + VibrateUtil.getInstance(_context).VibrateOnOnce(true); + Util.mSleep(2000); + } + //launcher 弹出消息 + if(Config.noBroadCastPushTxtNotify==false) { + Intent intent = new Intent(ActionSrvPushTxt); + intent.putExtra("msgType", msgType); //0 代表 server下发消息,1代表 SMS消息,2代表有提示音的消息 + intent.putExtra("txtMsg", msg); + intent.addFlags(FLAG_ACTIVITY_NEW_TASK); + _context.sendBroadcast(intent); + } + } + },50); + } + + + + + } + public void sendStheartRateBroadcast(String paramString, int paramInt) { + Intent intent = new Intent(); + intent.setAction(paramString); + intent.putExtra("stheartRateType", paramInt); + this.context.sendBroadcast(intent, "com.eqc.broadcast.permission"); + } + public void sendBroadcastSitLongAlarm() { + + if (Util.installed(context,"com.ic.ak.launcher")) { + Intent intent = new Intent(); + intent.setAction(ACTION_KEEPSIT_ALARM); + intent.addFlags(FLAG_ACTIVITY_NEW_TASK); + this.context.sendBroadcast(intent); + }else { + Intent intent = new Intent(); + //显示提示窗口 + intent.setAction(DIALOG_ACTION); + intent.putExtra("takephoto", context.getResources().getString(R.string.sedentary_msg)); + context.sendBroadcast(intent); + } + } + +} + + diff --git a/app/src/main/java/com/enqualcomm/support/utils/DBHelper.java b/app/src/main/java/com/enqualcomm/support/utils/DBHelper.java index 3988a92b..7eb153da 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/DBHelper.java +++ b/app/src/main/java/com/enqualcomm/support/utils/DBHelper.java @@ -25,6 +25,7 @@ import com.enqualcomm.support.bean.Antioff; import com.enqualcomm.support.bean.Contact; import com.enqualcomm.support.bean.Content; import com.enqualcomm.support.bean.DeviceStatus; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.NoticeContent; import com.enqualcomm.support.bean.NotificationParam; import com.enqualcomm.support.bean.Silent; @@ -50,10 +51,14 @@ public class DBHelper { private static long lastUpdateTime; private Context context; private ContentResolver cr; - + private Handler mHandler;//=new Handler(EventLooperHandlerThread.makeLooper(DBHelper.class.getSimpleName())); +// private Handler mHandler=new Handler(); public DBHelper(ContentResolver var1, Context var2) { this.cr = var1; this.context = var2; + EventLooperHandlerThread eventLooperHandlerThread=new EventLooperHandlerThread(DBHelper.class.getSimpleName()); + eventLooperHandlerThread.start(); + mHandler=new Handler( eventLooperHandlerThread.looper); } private void addAllContact(ArrayList contactArray, ContentResolver resolver) { @@ -707,7 +712,7 @@ public class DBHelper { this.saveContactsImpl(contactArray, admin, care,call, partner, video,sos); lastUpdateTime = currenttime; } else { - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { DBHelper.this.saveContacts(contactArray, admin, care,call, partner, video,sos); @@ -869,7 +874,7 @@ public class DBHelper { this.upDateMonitorImpl(var1, var2); lastUpdateTime = var3; } else { - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { DBHelper.this.upDateMonitor(var1, var2); diff --git a/app/src/main/java/com/enqualcomm/support/utils/MissedCallContentObserver.java b/app/src/main/java/com/enqualcomm/support/utils/MissedCallContentObserver.java index baf1a0c4..212dd14e 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/MissedCallContentObserver.java +++ b/app/src/main/java/com/enqualcomm/support/utils/MissedCallContentObserver.java @@ -1,140 +1,141 @@ -package com.enqualcomm.support.utils; -import android.content.Context; -import android.content.Intent; -import android.database.ContentObserver; -import android.database.Cursor; -import android.os.Handler; -import android.os.Message; -import android.provider.CallLog.Calls; -import com.enqualcomm.support.Constants; -import com.enqualcomm.support.bean.Contact; -import com.enqualcomm.support.bean.Runtime; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class MissedCallContentObserver extends ContentObserver { - private static final int MISSED_CALL_MSG = 1; - private static final String[] PROJECT = new String[]{"name", "number", "type", "new", "date"}; - private Context mContext; - private Handler mHandler = new Handler() { - public void handleMessage(Message var1) { - int var2 = var1.what; - boolean var3 = true; - if (var2 == 1) { - MissedCallContentObserver.DataHolder var5 = (MissedCallContentObserver.DataHolder)var1.obj; - StringBuilder var4 = new StringBuilder(); - var4.append("you have a missed call, name : "); - var4.append(var5.contact.name); - var4.append(", number: "); - var4.append(var5.contact.number); - var4.append(", date: "); - var4.append(var5.date); - ICLogger.i(var4.toString()); - var2 = MissedCallContentObserver.this.mRuntime.getContextProxy().getTelephonyManager().getCallState(); - if (MissedCallContentObserver.this.mRuntime.getBatteryLow() || 1 == var2 || 2 == var2) { - var3 = false; - } - - if (Boolean.valueOf(var3)) { - Intent var6 = new Intent("com.enqualcomm.support.ACTION_MISSED_CALL_GET"); - var6.putExtra("contact", var5.contact); - var6.putExtra("date", var5.date); - MissedCallContentObserver.this.mContext.sendBroadcast(var6); - } - } - - } - }; - private long mMissedCallDate; - private Runtime mRuntime; - - public MissedCallContentObserver(Context var1, Runtime var2, Handler var3) { - super(var3); - this.mContext = var1; - this.mRuntime = var2; - } - - private boolean checkSameItem(long var1) { - boolean var3; - if (this.mMissedCallDate == var1) { - var3 = true; - } else { - var3 = false; - } - - return var3; - } - - public void onChange(boolean var1) { - Cursor var2 = this.mContext.getContentResolver().query(Calls.CONTENT_URI, PROJECT, (String)null, (String[])null, "date DESC"); - if (var2 != null) { - if (var2.moveToFirst()) { - switch(var2.getInt(var2.getColumnIndex("type"))) { - case 1: - ICLogger.i("incoming type"); - break; - case 2: - ICLogger.i("outgoing type"); - break; - case 3: - ICLogger.i("missed type"); - if (var2.getInt(var2.getColumnIndex("new")) == 1) { - String var3 = var2.getString(var2.getColumnIndex("number")); - var2.getString(var2.getColumnIndex("name")); - long var4 = var2.getLong(var2.getColumnIndex("date")); - if (!this.checkSameItem(var4)) { - ICLogger.i(" not the same missed!"); - this.mMissedCallDate = var4; - Date var6 = new Date(var4); - (new SimpleDateFormat("yyyy-MM-dd;HH:mm:ss")).format(var6); - Cursor var13 = this.mContext.getContentResolver().query(Constants.CONTACT_URI, (String[])null, "CATEGORY IN (1,2,3)", (String[])null, (String)null); - if (var13 != null) { - StringBuilder var7 = new StringBuilder(); - var7.append("cursor1.size = "); - var7.append(var13.getCount()); - ICLogger.i(var7.toString()); - - while(var13.moveToNext()) { - String var8 = var13.getString(3); - if (var8.contains(var3) || var3.contains(var8)) { - int var9 = var13.getInt(1); - String var10 = var13.getString(2); - String var14 = var13.getString(4); - String var11 = var13.getString(5); - StringBuilder var12 = new StringBuilder(); - var12.append("name="); - var12.append(var10); - var12.append("...number="); - var12.append(var8); - ICLogger.i(var12.toString()); - new Contact(var9, var10, var3, var14, var11); - break; - } - } - - var13.close(); - } else { - ICLogger.i("don't know who called"); - } - } else { - ICLogger.i(" The same missed call, ignore it!"); - } - } - } - } - - var2.close(); - } - - } - - private class DataHolder { - public Contact contact; - public String date; - - public DataHolder(Contact var2, String var3) { - this.contact = var2; - this.date = var3; - } - } +package com.enqualcomm.support.utils; +import android.content.Context; +import android.content.Intent; +import android.database.ContentObserver; +import android.database.Cursor; +import android.os.Handler; +import android.os.Message; +import android.provider.CallLog.Calls; +import com.enqualcomm.support.Constants; +import com.enqualcomm.support.bean.Contact; +import com.enqualcomm.support.bean.EventLooperHandlerThread; +import com.enqualcomm.support.bean.Runtime; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class MissedCallContentObserver extends ContentObserver { + private static final int MISSED_CALL_MSG = 1; + private static final String[] PROJECT = new String[]{"name", "number", "type", "new", "date"}; + private Context mContext; + private Handler mHandler = new Handler(EventLooperHandlerThread.makeLooper(MissedCallContentObserver.class.getSimpleName())) { + public void handleMessage(Message var1) { + int var2 = var1.what; + boolean var3 = true; + if (var2 == 1) { + MissedCallContentObserver.DataHolder var5 = (MissedCallContentObserver.DataHolder)var1.obj; + StringBuilder var4 = new StringBuilder(); + var4.append("you have a missed call, name : "); + var4.append(var5.contact.name); + var4.append(", number: "); + var4.append(var5.contact.number); + var4.append(", date: "); + var4.append(var5.date); + ICLogger.i(var4.toString()); + var2 = MissedCallContentObserver.this.mRuntime.getContextProxy().getTelephonyManager().getCallState(); + if (MissedCallContentObserver.this.mRuntime.getBatteryLow() || 1 == var2 || 2 == var2) { + var3 = false; + } + + if (Boolean.valueOf(var3)) { + Intent var6 = new Intent("com.enqualcomm.support.ACTION_MISSED_CALL_GET"); + var6.putExtra("contact", var5.contact); + var6.putExtra("date", var5.date); + MissedCallContentObserver.this.mContext.sendBroadcast(var6); + } + } + + } + }; + private long mMissedCallDate; + private Runtime mRuntime; + + public MissedCallContentObserver(Context var1, Runtime var2, Handler var3) { + super(var3); + this.mContext = var1; + this.mRuntime = var2; + } + + private boolean checkSameItem(long var1) { + boolean var3; + if (this.mMissedCallDate == var1) { + var3 = true; + } else { + var3 = false; + } + + return var3; + } + + public void onChange(boolean var1) { + Cursor var2 = this.mContext.getContentResolver().query(Calls.CONTENT_URI, PROJECT, (String)null, (String[])null, "date DESC"); + if (var2 != null) { + if (var2.moveToFirst()) { + switch(var2.getInt(var2.getColumnIndex("type"))) { + case 1: + ICLogger.i("incoming type"); + break; + case 2: + ICLogger.i("outgoing type"); + break; + case 3: + ICLogger.i("missed type"); + if (var2.getInt(var2.getColumnIndex("new")) == 1) { + String var3 = var2.getString(var2.getColumnIndex("number")); + var2.getString(var2.getColumnIndex("name")); + long var4 = var2.getLong(var2.getColumnIndex("date")); + if (!this.checkSameItem(var4)) { + ICLogger.i(" not the same missed!"); + this.mMissedCallDate = var4; + Date var6 = new Date(var4); + (new SimpleDateFormat("yyyy-MM-dd;HH:mm:ss")).format(var6); + Cursor var13 = this.mContext.getContentResolver().query(Constants.CONTACT_URI, (String[])null, "CATEGORY IN (1,2,3)", (String[])null, (String)null); + if (var13 != null) { + StringBuilder var7 = new StringBuilder(); + var7.append("cursor1.size = "); + var7.append(var13.getCount()); + ICLogger.i(var7.toString()); + + while(var13.moveToNext()) { + String var8 = var13.getString(3); + if (var8.contains(var3) || var3.contains(var8)) { + int var9 = var13.getInt(1); + String var10 = var13.getString(2); + String var14 = var13.getString(4); + String var11 = var13.getString(5); + StringBuilder var12 = new StringBuilder(); + var12.append("name="); + var12.append(var10); + var12.append("...number="); + var12.append(var8); + ICLogger.i(var12.toString()); + new Contact(var9, var10, var3, var14, var11); + break; + } + } + + var13.close(); + } else { + ICLogger.i("don't know who called"); + } + } else { + ICLogger.i(" The same missed call, ignore it!"); + } + } + } + } + + var2.close(); + } + + } + + private class DataHolder { + public Contact contact; + public String date; + + public DataHolder(Contact var2, String var3) { + this.contact = var2; + this.date = var3; + } + } } \ No newline at end of file diff --git a/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java b/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java index d4f939d7..07169df5 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java +++ b/app/src/main/java/com/enqualcomm/support/utils/NettyConnection.java @@ -1,329 +1,335 @@ -package com.enqualcomm.support.utils; - -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.SystemClock; -import android.util.Log; - - -import com.enqualcomm.support.Config; -import com.ic.protocols.protocolAPIHelper; -import com.enqualcomm.support.bean.StringMessage; -import com.enqualcomm.support.service.HeartRateManager; -import com.enqualcomm.support.CoreService; - -import java.nio.ByteBuffer; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import rx.android.schedulers.AndroidSchedulers; -import rx.schedulers.Schedulers; - -import static com.enqualcomm.support.utils.RxSocket.SocketStatus.CONNECTED; - -import com.enqualcomm.support.bean.Runtime; - -public class NettyConnection implements Connection { - private static long realtime_old; - private static final String TAG = NettyConnection.class.getSimpleName(); - - ExecutorService executorService = Executors.newSingleThreadExecutor(); - - private protocolAPIHelper API=null; - private ConnectionListener listener=null; - - private int timeout = 60; - - public NettyConnection(ConnectionListener paramConnectionListener,Runtime runtime) { - Log.i(TAG, "NettyConnection "); - this.listener = paramConnectionListener; - - if (API == null) API=new protocolAPIHelper(this,runtime ); - - initReadListener(); - init_connection_listener(); - } - - private void connectImpl(String host, int port) { - connectServer(host,port); - } - - public void close() { -// listener =null; -// RxSocket.getInstance().setConnectionListener(null); - this.disconnect(); - } - - public void connect(final String host, final int port) { - long l = SystemClock.elapsedRealtime(); - if (host.isEmpty()||host ==null){ - ICLogger.i("host name error "+host); - return ; - } - if (l - realtime_old < 3000L ) { - ICLogger.i("3秒内skip 重连!"); - return; - } - realtime_old = l; - ICLogger.i("connect1 "+host+":"+port); -// disconnect(); - this.executorService.execute(new Runnable() { - public void run() { - NettyConnection.this.connectImpl(host, port); - ICLogger.i("connect2"); - } - }); - } - - public void disconnect() { - - disconnectServer(); - } - - - private boolean connectServer(String serverip,int serverport){ - - //进行连接Socket:这里使用的是,在本地上开启了一个服务器。 - - RxSocket.getInstance().connectRx(serverip==null?"118.178.155.223":serverip,serverport) - .subscribe( - aBoolean -> { - log("RxSocket Connect "+aBoolean); - }, - throwable -> { - log("RxSocket Connect Error : "+throwable.getMessage()); - }, - () -> { - log("RxSocket Connect main"); - - } - ); - - - return true; - } - - public boolean disconnectServer(){ - - log("Call disconnectServer"); - //断开连接 - RxSocket.getInstance().disConnect() - .subscribe( - aBoolean -> { - log("RxSocket DisConnect "+aBoolean); - }, - throwable -> { - log("RxSocket DisConnect Error : "+throwable.getMessage()); - }, - () -> { - log("RxSocket DisConnect main"); - } - ); - - return true; - } - private void log(String msg) { - ICLogger.log(TAG,msg); - } - - - public boolean isServerConnected(){ - return (RxSocket.getInstance().getSocketStatus()== CONNECTED)?true:false; - } - - public boolean sendMsg(String cmd) { - - if( cmd==null || cmd.isEmpty()) - { - return false; - } - - - if (!isServerConnected()){ - - log("skiped"+cmd); - if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," skiped " + cmd); - return false; - }else{ - log("send "+cmd); - if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," sent " + cmd); - //向RxSocket写数据 - //示例数据:IWAP00867155030001063# - byte[] test = cmd.getBytes(); - ByteBuffer byteBuffer = ByteBuffer.wrap(test); - RxSocket.getInstance().write(byteBuffer) - .subscribe( - aBoolean -> { - log("RxSocket write " + aBoolean); - }, - throwable -> { - log("RxSocket write Error : " + throwable.getMessage()); - }, - () -> { - log("RxSocket write main "); - } - ); - - - } - - return true; - } - - public boolean sendMsg(String cmdtype,byte[] cmdArray) { - log(cmdtype); - return sendMsg(cmdArray); - - } - public boolean sendMsg(byte[] cmdArray) { - - if( cmdArray==null || cmdArray.length==0) - { - return false; - } - - - if (!isServerConnected()){ - - log("skipedBytes "+new String(cmdArray)); - if (Config.LOG_TOFILE)ICLogger.logToFile("APILog"," skiped " + new String(cmdArray)); - return false; - }else{ - log("sendBytes "+new String(cmdArray)); - if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," sentBytes " + 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 "); - } - ); - - - } - - return true; - } - public int getTimeout() { return this.timeout; } - - - public void DeliverCMDMessageToSystem(String cmd,String msg){ - if (this.listener!=null){ - String[] msgArr=new String[]{cmd,msg}; - StringMessage stringMessage=new StringMessage(msgArr); - stringMessage.refresh(msg); - this.listener.onReceive(stringMessage ); - } - } - - private void initReadListener(){ - //监听Socket的收包 -// RxSocket.getInstance().read() -// .subscribeOn(Schedulers.newThread()) -// .observeOn(AndroidSchedulers.mainThread()) -// .subscribe( -// bytes -> { -// //这里,应该去处理这个消息 -// String msg=new String(bytes); -// log("get Msg :"+msg+" (size)" + bytes.length); -// -// API.parserCmd(msg,bytes); -// -// }, -// throwable -> { -// log("get Msg throwable " +throwable); -// //出现错误恢复读取线程。 -// NettyConnection.this.initReadListener(); -// }, -// ()->{ -// log("get Msg ()"); -// } -// ); - RxSocket.getInstance().setSocketReadCallback(new RxSocket.SocketReadCallback() { - @Override - public void onRecvMsg(byte[] bytes) { - - Message msg=new Message(); - Bundle bdl=new Bundle(); - bdl.putByteArray("RecvData",bytes); - msg.what=100; - msg.setData(bdl); - mHandler.sendMessage(msg); - } - }); - - - } - - private Handler mHandler=new Handler(new Handler.Callback() { - @Override - public boolean handleMessage(Message message) { - - if (message.what == 100){ - byte[] bytes=message.getData().getByteArray("RecvData"); - String msg= new String(bytes); - - log("get Msg :"+msg+" (size) byteslen" + bytes.length +" strlen"+ msg.length()); - API.parserCmd("",bytes); - - } - return false; - } - }); - - private void init_connection_listener(){ - - //监听Socket的连接状态 - RxSocket.getInstance().socketStatusListener() - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(socketStatus -> { - log("socketStatusListener socketStatus:" + socketStatus.name()); - if (socketStatus.name().equals("CONNECTED")){ - if (this.listener!=null){ - this.listener.onConnectionOpen(); - } - }else if (socketStatus.name().equals("DIS_CONNECT") || socketStatus.name().equals("DIS_CONNECT_BY_SERVERSIDE")) { - if (this.listener!=null){ - this.listener.onConnectionClose(socketStatus.name()); - } - disconnectServer(); - } - }); - } - public void open() { - - - } - - public void send(StringMessage msg) { - - if(msg==null) { - ICLogger.i(" StringMessage is null skip send!"); - return ; - } - sendMsg(msg.isFromCache()); - ICLogger.logToFile("APILog","send "+msg.getIndex()+" "+msg.getDate()+msg.getTime()+" "+msg.cmd()+" "+msg.isFromCache()); - // ICLogger.i(paramStringMessage.isFromCache()); - - } - - public boolean sendBlocking(StringMessage paramStringMessage) { - ICLogger.i(paramStringMessage.isFromCache()); - sendMsg(paramStringMessage.isFromCache()); - return true; - } - - public void setTimeout(int paramInt) { this.timeout = paramInt; } - -} - +package com.enqualcomm.support.utils; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; +import android.util.Log; + + +import com.enqualcomm.support.Config; +import com.enqualcomm.support.adapter.BTHelper; +import com.enqualcomm.support.bean.EventLooperHandlerThread; +import com.enqualcomm.support.service.SilentManager; +import com.ic.protocols.protocolAPIHelper; +import com.enqualcomm.support.bean.StringMessage; +import com.enqualcomm.support.service.HeartRateManager; +import com.enqualcomm.support.CoreService; + +import java.nio.ByteBuffer; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import rx.android.schedulers.AndroidSchedulers; +import rx.schedulers.Schedulers; + +import static com.enqualcomm.support.utils.RxSocket.SocketStatus.CONNECTED; + +import com.enqualcomm.support.bean.Runtime; + +public class NettyConnection implements Connection { + private static long realtime_old; + private static final String TAG = NettyConnection.class.getSimpleName(); + + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + private protocolAPIHelper API=null; + private ConnectionListener listener=null; + + private int timeout = 60; + private Handler mHandler; + + public NettyConnection(ConnectionListener paramConnectionListener,Runtime runtime) { + Log.i(TAG, "NettyConnection "); + this.listener = paramConnectionListener; + + mHandler = new Handler(EventLooperHandlerThread.makeLooper(NettyConnection.class.getSimpleName()),new Handler.Callback() { + @Override + public boolean handleMessage(Message message) { + + if (message.what == 100){ + byte[] bytes=message.getData().getByteArray("RecvData"); + String msg= new String(bytes); + + log("get Msg :"+msg+" (size) byteslen" + bytes.length +" strlen"+ msg.length()); + API.parserCmd("",bytes); + + } + return false; + } + }); + + if (API == null) API=new protocolAPIHelper(this,runtime ); + + initReadListener(); + init_connection_listener(); + } + + private void connectImpl(String host, int port) { + connectServer(host,port); + } + + public void close() { +// listener =null; +// RxSocket.getInstance().setConnectionListener(null); + this.disconnect(); + } + + public void connect(final String host, final int port) { + long l = SystemClock.elapsedRealtime(); + if (host.isEmpty()||host ==null){ + ICLogger.i("host name error "+host); + return ; + } + if (l - realtime_old < 3000L ) { + ICLogger.i("3秒内skip 重连!"); + return; + } + realtime_old = l; + ICLogger.i("connect1 "+host+":"+port); +// disconnect(); + this.executorService.execute(new Runnable() { + public void run() { + NettyConnection.this.connectImpl(host, port); + ICLogger.i("connect2"); + } + }); + } + + public void disconnect() { + + disconnectServer(); + } + + + private boolean connectServer(String serverip,int serverport){ + + //进行连接Socket:这里使用的是,在本地上开启了一个服务器。 + + RxSocket.getInstance().connectRx(serverip==null?"118.178.155.223":serverip,serverport) + .subscribe( + aBoolean -> { + log("RxSocket Connect "+aBoolean); + }, + throwable -> { + log("RxSocket Connect Error : "+throwable.getMessage()); + }, + () -> { + log("RxSocket Connect main"); + + } + ); + + + return true; + } + + public boolean disconnectServer(){ + + log("Call disconnectServer"); + //断开连接 + RxSocket.getInstance().disConnect() + .subscribe( + aBoolean -> { + log("RxSocket DisConnect "+aBoolean); + }, + throwable -> { + log("RxSocket DisConnect Error : "+throwable.getMessage()); + }, + () -> { + log("RxSocket DisConnect main"); + } + ); + + return true; + } + private void log(String msg) { + ICLogger.log(TAG,msg); + } + + + public boolean isServerConnected(){ + return (RxSocket.getInstance().getSocketStatus()== CONNECTED)?true:false; + } + + public boolean sendMsg(String cmd) { + + if( cmd==null || cmd.isEmpty()) + { + return false; + } + + + if (!isServerConnected()){ + + log("skiped"+cmd); + if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," skiped " + cmd); + return false; + }else{ + log("send "+cmd); + if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," sent " + cmd); + //向RxSocket写数据 + //示例数据:IWAP00867155030001063# + byte[] test = cmd.getBytes(); + ByteBuffer byteBuffer = ByteBuffer.wrap(test); + RxSocket.getInstance().write(byteBuffer) + .subscribe( + aBoolean -> { + log("RxSocket write " + aBoolean); + }, + throwable -> { + log("RxSocket write Error : " + throwable.getMessage()); + }, + () -> { + log("RxSocket write main "); + } + ); + + + } + + return true; + } + + public boolean sendMsg(String cmdtype,byte[] cmdArray) { + log(cmdtype); + return sendMsg(cmdArray); + + } + public boolean sendMsg(byte[] cmdArray) { + + if( cmdArray==null || cmdArray.length==0) + { + return false; + } + + + if (!isServerConnected()){ + + log("skipedBytes "+new String(cmdArray)); + if (Config.LOG_TOFILE)ICLogger.logToFile("APILog"," skiped " + new String(cmdArray)); + return false; + }else{ + log("sendBytes "+new String(cmdArray)); + if (Config.LOG_TOFILE) ICLogger.logToFile("APILog"," sentBytes " + 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 "); + } + ); + + + } + + return true; + } + public int getTimeout() { return this.timeout; } + + + public void DeliverCMDMessageToSystem(String cmd,String msg){ + if (this.listener!=null){ + String[] msgArr=new String[]{cmd,msg}; + StringMessage stringMessage=new StringMessage(msgArr); + stringMessage.refresh(msg); + this.listener.onReceive(stringMessage ); + } + } + + private void initReadListener(){ + //监听Socket的收包 +// RxSocket.getInstance().read() +// .subscribeOn(Schedulers.newThread()) +// .observeOn(AndroidSchedulers.mainThread()) +// .subscribe( +// bytes -> { +// //这里,应该去处理这个消息 +// String msg=new String(bytes); +// log("get Msg :"+msg+" (size)" + bytes.length); +// +// API.parserCmd(msg,bytes); +// +// }, +// throwable -> { +// log("get Msg throwable " +throwable); +// //出现错误恢复读取线程。 +// NettyConnection.this.initReadListener(); +// }, +// ()->{ +// log("get Msg ()"); +// } +// ); + RxSocket.getInstance().setSocketReadCallback(new RxSocket.SocketReadCallback() { + @Override + public void onRecvMsg(byte[] bytes) { + + Message msg=new Message(); + Bundle bdl=new Bundle(); + bdl.putByteArray("RecvData",bytes); + msg.what=100; + msg.setData(bdl); + mHandler.sendMessage(msg); + } + }); + + + } + + + + private void init_connection_listener(){ + + //监听Socket的连接状态 + RxSocket.getInstance().socketStatusListener() + .subscribeOn(Schedulers.newThread()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(socketStatus -> { + log("socketStatusListener socketStatus:" + socketStatus.name()); + if (socketStatus.name().equals("CONNECTED")){ + if (this.listener!=null){ + this.listener.onConnectionOpen(); + } + }else if (socketStatus.name().equals("DIS_CONNECT") || socketStatus.name().equals("DIS_CONNECT_BY_SERVERSIDE")) { + if (this.listener!=null){ + this.listener.onConnectionClose(socketStatus.name()); + } + disconnectServer(); + } + }); + } + public void open() { + + + } + + public void send(StringMessage msg) { + + if(msg==null) { + ICLogger.i(" StringMessage is null skip send!"); + return ; + } + sendMsg(msg.isFromCache()); + ICLogger.logToFile("APILog","send "+msg.getIndex()+" "+msg.getDate()+msg.getTime()+" "+msg.cmd()+" "+msg.isFromCache()); + // ICLogger.i(paramStringMessage.isFromCache()); + + } + + public boolean sendBlocking(StringMessage paramStringMessage) { + ICLogger.i(paramStringMessage.isFromCache()); + sendMsg(paramStringMessage.isFromCache()); + return true; + } + + public void setTimeout(int paramInt) { this.timeout = paramInt; } + +} + diff --git a/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java b/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java index 844a67bb..2a0767cb 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java +++ b/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java @@ -1,544 +1,546 @@ -package com.enqualcomm.support.utils; - -import android.app.Notification; -import android.app.NotificationManager; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.media.RingtoneManager; -import android.net.Uri; -import android.os.Handler; -import android.os.Messenger; -import android.os.PowerManager; -import android.os.Vibrator; -import android.support.v4.app.NotificationCompat; -import android.view.Gravity; -import android.view.MotionEvent; -import android.view.View; -import android.view.WindowManager; - - -import com.enqualcomm.support.Config; -import com.enqualcomm.support.Constants; -import com.enqualcomm.support.CoreService; -import com.enqualcomm.support.LocationClient; -import com.enqualcomm.support.R; -import com.enqualcomm.support.bean.NotificationParam; -import com.enqualcomm.support.bean.Runtime; -import com.enqualcomm.support.bean.StringMessage; -import com.enqualcomm.support.bean.VoiceContent; -import com.enqualcomm.support.service.Deliver; -import com.ic.jni.ICJniUtils; -import com.enqualcomm.support.bean.Contact; -import com.enqualcomm.support.service.AudioService; -import com.enqualcomm.support.service.HeartRateManager; -import com.ic.protocols.protocolAPIHelper; - -import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; -import static android.media.RingtoneManager.TYPE_NOTIFICATION; -import static android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP; -import static android.os.PowerManager.SCREEN_DIM_WAKE_LOCK; -import static com.enqualcomm.support.Constants.ACTION_CLOSE_UNREAD_MSG; -import static com.enqualcomm.support.Constants.ACTION_HEATR_RATE_START; -import static com.enqualcomm.support.Constants.ACTION_MESSAGE_SENT; -import static com.enqualcomm.support.Constants.ACTION_PLAYTIME; -import static com.enqualcomm.support.Constants.ACTION_REMOTE_CAMERA; -import static com.enqualcomm.support.Constants.ACTION_SEND_EMEGENCY_LOCATION_START; -import static com.enqualcomm.support.Constants.ACTION_SEND_SOS_MSG; -import static com.enqualcomm.support.Constants.ACTION_SET_SIT_RANGE; -import static com.enqualcomm.support.Constants.ACTION_SHUTDOWN; -import static com.enqualcomm.support.Constants.ACTION_TEMP_RESULT; -import static com.enqualcomm.support.Constants.DIALOG_ACTION; -import static com.enqualcomm.support.Constants.KEY_MESSAGE_FROM; -import static com.enqualcomm.support.Constants.KEY_MESSAGE_TYPE; -import static com.enqualcomm.support.Constants.KEY_MESSAGE_URL; -import static com.enqualcomm.support.Constants.KEY_TEMP_BODY; -import static com.enqualcomm.support.Constants.KEY_TEMP_WRIST; -import static com.enqualcomm.support.Constants.RESUME_ACTION; - -import static com.enqualcomm.support.bean.Content.CONTACT_CATEGORY_GROUP; -import static com.enqualcomm.support.utils.TemperatureUtil.KEY_TEMP_BYPROTOCOL; -import static com.enqualcomm.support.utils.TemperatureUtil.KEY_TEMP_OUT; - - -public class ProcessReceiver extends BroadcastReceiver { - private static final int MICRO_CHAT = 2; - - private static int last_app_id; - - private static String last_message_name; - - private static CustomDialog mCustomDialog; - - private CustomNotification mCustomNotification; - - private CustomDialog.Builder mDialog; - - private CustomNotification.Builder mNotificationDialog; - - private NotificationManager mNotificationManager; - - private Vibrator vibrator; - - private float x1 = 0.0F; - - private float x2 = 0.0F; - - private float y1 = 0.0F; - - private float y2 = 0.0F; - - private void initMyDialog(final Context context, final Contact contact, int app_id,String msg,boolean needreply) { - String var4 = contact==null?"SMS":contact.name; - - if (this.mDialog == null) { - this.mDialog = new CustomDialog.Builder(context); - } - - StringBuilder var5 = new StringBuilder(); - var5.append("===mCustomDialog ") - .append(mCustomDialog) - .append(" , appid ").append(app_id); - - ICLogger.i(var5.toString()); - if (mCustomDialog != null && mCustomDialog.isShowing() && last_message_name != null && var4 != null && last_message_name.equals(var4) && last_app_id == app_id) { - mCustomDialog.dismiss(); - } - - last_message_name = var4; - last_app_id = app_id; - CustomDialog.Builder tmpDialog; - if (app_id == 1) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.setting_title)).setApp(1); - StringBuilder var6 = new StringBuilder(); - var6.append(context.getString(R.string.voiceMessage)); - var6.append(" "); - var6.append(var4); - var6.append(context.getString(R.string.voiceMessageEnd)); - mCustomDialog = tmpDialog.setMessage(var6.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1x, int var2x) { - var1x.dismiss(); - ComponentName var3 = new ComponentName("com.enqualcomm.imessage", "com.enqualcomm.imessage.ui.chat.ChatActivity_"); - Intent var5 = new Intent("android.intent.action.MAIN"); - var5.putExtra("ACTIVITY_TYPE", 2); - var5.putExtra("contact", contact); - var5.addCategory("android.intent.category.DEFAULT"); - var5.addFlags(FLAG_ACTIVITY_NEW_TASK); - var5.setComponent(var3); - VibrateUtil.getInstance(context).VibrateOn(false); - try { - context.startActivity(var5); - } catch (Exception e) { - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - - } - }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - } else if (app_id == 2) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.hht_misscall_call)).setApp(app_id); - StringBuilder var7 = new StringBuilder(); - var7.append(context.getString(R.string.hht_call_start)); - var7.append(var4); - var7.append(context.getString(R.string.hht_call_end)); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - }else if (app_id ==3){ - tmpDialog = this.mDialog.setTitle(context.getString(R.string.sms_title)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(context.getString(R.string.sms_notify)); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - ComponentName var3 = new ComponentName("com.zmapp.sms", "com.zmapp.sms.MainActivity"); - Intent var5 = new Intent("android.intent.action.MAIN"); - var5.addCategory("android.intent.category.DEFAULT"); - var5.addFlags(FLAG_ACTIVITY_NEW_TASK); - var5.setComponent(var3); - VibrateUtil.getInstance(context).VibrateOn(false); - try { - context.startActivity(var5); - } catch (Exception e) { - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - } - }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - }else if (app_id ==4) { - tmpDialog = this.mDialog.setTitle("WEB"+context.getString(R.string.sms_title)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(msg); - - if (needreply) { - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - if (CoreService.getInstance() != null) { - Runtime runtime = CoreService.getInstance().getRuntime(); - if (Config.custom_name.equals("YQ") || Config.custom_name.equals("YQ_EN")) { - runtime.setAlarmType(Runtime.AlarmType.ALARM_MSGREAD); - Config.setLastUnReadMessage(CoreService.getInstance(), ""); - Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(runtime)); - } else { - CoreService.getInstance().getConnection().send(protocolAPIHelper.getPushTxtReadFlagToSrvMSG(runtime)); - } - } - } - }).create(); - }else{ - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - } - }).create(); - } - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - } else if (app_id ==5) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.findDev)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(msg); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - stopmediaplayer(); - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - }else if (app_id ==6) { - tmpDialog = this.mDialog.setTitle(context.getString(R.string.notification_title)).setApp(1); - StringBuilder var7 = new StringBuilder(); - var7.append(msg); - mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface var1, int var2) { - var1.dismiss(); - VibrateUtil.getInstance(context).VibrateOn(false); - stopmediaplayer(); - - if(msg.contains("Take Photo")) { - String packagename = "com.eqc.camera"; - String activityName = "com.eqc.camera.TakePictureActivity"; - if (Util.installed(context, "com.ic.camera")) { - packagename = "com.ic.camera"; - activityName = "com.ic.camera.MainActivity"; - } - ComponentName var3 = new ComponentName(packagename, activityName); - Intent var5 = new Intent("android.intent.action.MAIN"); - var5.addCategory("android.intent.category.DEFAULT"); - var5.addFlags(FLAG_ACTIVITY_NEW_TASK); - var5.setComponent(var3); - try { - context.startActivity(var5); - } catch (Exception e) { - e.printStackTrace(); - ICLogger.e(e.getMessage(),e); - } - } - } - }).create(); - mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); - mCustomDialog.show(); - } - } - private void playFindDevVoice(Context context){ - - AudioService.getInstance().play(context.getAssets(), "Campus_Life.ogg"); - - } - private void stopmediaplayer(){ - AudioService.getInstance().stop(); - } - private void playNotificationVoice(Context paramContext) { - AudioService.getInstance().play(paramContext.getAssets(), "ring_msg.mp3"); - } - - private void playshutdownsound(Context paramContext) { - AudioService.getInstance().play(paramContext.getAssets(), "shutdownsound.mp3"); - } - - - private void screenOn(Context paramContext) { - final PowerManager.WakeLock wakelock = ((PowerManager)paramContext.getSystemService(Context.POWER_SERVICE)).newWakeLock(ACQUIRE_CAUSES_WAKEUP| SCREEN_DIM_WAKE_LOCK, ProcessReceiver.class.getSimpleName()); - wakelock.acquire(); - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - wakelock.release(); - } - },5000); - } - - @Override - public void onReceive(Context paramContext, Intent paramIntent) { - - boolean isSilence; - Contact contact; - String str = paramIntent.getAction(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("action=="); - stringBuilder.append(str); - ICLogger.i(stringBuilder.toString()); - - if (CoreService.getInstance()==null) - { - ICLogger.i("CoreService is null skip deal with this message! "+str); - paramContext.startService(new Intent(paramContext,CoreService.class));// protocol service - return ; - } - if (RESUME_ACTION.equals(str)) { - SharPreferenceUtil.setPrefBoolean(paramContext, "key_is_resume", paramIntent.getBooleanExtra("is_resume", false)); - return; - }else if (ACTION_MESSAGE_SENT.equals(str)) { - - String msgType=paramIntent.getStringExtra(KEY_MESSAGE_TYPE); - String msgFrom=paramIntent.getStringExtra(KEY_MESSAGE_FROM); - String msgUrl=paramIntent.getStringExtra(KEY_MESSAGE_URL); - ICLogger.i("receive msg to send type="+msgType+", msg from = "+msgFrom+", msgUrl"+msgUrl); - if (msgFrom==null) msgFrom="123"; - /** - * * 1 语音—— 1.监听语音 * 2.SOS语音 * 3.扩展 - * * 2 图片—— 1.签到图片 * 2.指令图片 * 3.设备图片 * 4.扩展 - */ - if (msgType.equals("voice")) - { - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,1,3); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - }else if (msgType.equals("pic")){ - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,2,3); - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) { - - //h88专用功能,拍照时检查体温心率 - if(Util.getSystemProperties("persist.sys.do_check_condition","false").equals("true")) { - //开启测温 - if(CoreService.getInstance().getRuntime().check_stat_do_temp_test()) - TemperatureUtil.DoTempTest(); - - Util.mSleep(5000); - //开启测量PPG - if(CoreService.getInstance().getRuntime().check_stat_do_ppg_test()) - HeartRateManager.triggerPPGtest(); - } - //开启发送图片 - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - } - } - }else if (ACTION_SHUTDOWN.equals(str)) { - - playshutdownsound(paramContext); - - Util.shutdown(); - return; - }else if (ACTION_PLAYTIME.equals(str)) { - LedUtil.setBlueLedOn(true); - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - LedUtil.setBlueLedOn(false); - } - },2000L); - return; - }else if (ACTION_REMOTE_CAMERA.equals(str)) { - if (paramIntent.hasExtra("remote_number")){ - //接收拍照命令,执行拍照 - String str1 = paramIntent.getStringExtra("remote_number"); - new Handler().post(new Runnable() { - @Override - public void run() { - (new CameraUtil(paramContext)).getPictur(str1); - } - }); - }else{ - //接收到拍照完毕命令,发送照片 - String msgFrom=paramIntent.getStringExtra("number"); - String msgUrl=paramIntent.getStringExtra("filepath"); - ICLogger.i("receive taken photo to send "+msgUrl); - //创建voiceConent并添加到数据 - final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,2,2); - - - // 把voiceContent拆解成1024的分包 - Util.parseToVoicePacketSent(voiceContent); - //trigger 分包发送 - if (CoreService.getInstance().getConnection()!=null) { - - //h88专用功能,拍照后检测体温和心率 - if(Util.getSystemProperties("persist.sys.do_check_condition","false").equals("true")) { - //开启测温 - if(CoreService.getInstance().getRuntime().check_stat_do_temp_test()) - TemperatureUtil.DoTempTest(); - - Util.mSleep(500); - //开启测量PPG - if(CoreService.getInstance().getRuntime().check_stat_do_ppg_test()) - HeartRateManager.triggerPPGtest(); - } - //开启发送照片 - CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); - } - - } - - - return; - - }else if (DIALOG_ACTION.equals(str)) { - if (paramIntent.hasExtra("contact")) { - contact = (Contact) paramIntent.getParcelableExtra("contact"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (contact != null && !isSilence) { - if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, contact, 1,"",false); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - } - - this.screenOn(paramContext); - } - }else if (paramIntent.hasExtra("sms")) { - String sms = paramIntent.getStringExtra("sms"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (sms != null && !isSilence) { - //if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, null, 3,sms,false); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - //} - - this.screenOn(paramContext); - } - }else if (paramIntent.hasExtra("pushtxt")) { - String sms = paramIntent.getStringExtra("pushtxt"); - boolean needreply=false; - if (paramIntent.hasExtra("needreply")){ - needreply= paramIntent.getBooleanExtra("needreply",false); - } - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (sms != null && !isSilence) { - if (!DeviceInfoUtil.isTopActivity(paramContext)) { - this.initMyDialog(paramContext, null, 4, sms,needreply); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - } - - this.screenOn(paramContext); - } - }else if (paramIntent.hasExtra("findDev")) { - String finddevtxt = paramIntent.getStringExtra("findDev"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (finddevtxt != null && !isSilence) { - this.initMyDialog(paramContext, null, 5,finddevtxt,false); - this.playFindDevVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - - this.screenOn(paramContext); - } - }else if (paramIntent.hasExtra("takephoto")) { - String takephoto = paramIntent.getStringExtra("takephoto"); - SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); - isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); - if (takephoto != null && !isSilence) { - - this.initMyDialog(paramContext, null, 6,takephoto,false); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - - this.screenOn(paramContext); - } - } - - }else if (ACTION_TEMP_RESULT.equals(str)) { - double wrist_temp = paramIntent.getDoubleExtra(KEY_TEMP_WRIST, 0.0f); - double body_temp = paramIntent.getDoubleExtra(KEY_TEMP_BODY, 0.0f); - double tempOut = paramIntent.getDoubleExtra(KEY_TEMP_OUT, 0.0f); - boolean byprotocol=paramIntent.getBooleanExtra(KEY_TEMP_BYPROTOCOL,false); - if(byprotocol==false) { - if (Config.disableWristTemp) { - //ic68 - body_temp=wrist_temp; - } - ICLogger.i("Received Temperature wrist "+wrist_temp+" body "+body_temp); - StringMessage temperatureMsg = protocolAPIHelper.getTemperatureMSG(wrist_temp, body_temp, tempOut, null); - if (temperatureMsg != null) { - ICLogger.i("temp 发送体温测量值 " + temperatureMsg.isFromCache()); - } - Deliver.sendLocationMSG(temperatureMsg); - }else{ - ICLogger.i("Skip protocol Temperature wrist "+wrist_temp+" body "+body_temp); - - } - }else if (ACTION_SET_SIT_RANGE.equals(str)) { - if (paramIntent.hasExtra( Constants.KEY_SIT_RANGE)){ - int sitrange=paramIntent.getIntExtra(Constants.KEY_SIT_RANGE,0); - Config.setKeepSitRangeInMinutes(paramContext,sitrange); - ICLogger.i("set KeepSitRange int "+sitrange+" minutes!"); - ICLogger.i("则重置 lastCheckSitTime 以及 lastSitCheckStepCount"); - Runtime.lastSitCheckStepCount=CoreService.getInstance().getRuntime().getTotalStepCount(); - Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3(); - } - } else { - //如果来电了,还有未读的消息,干脆关掉,防止影响接电话。 - if (mCustomDialog != null && mCustomDialog.isShowing()) { - mCustomDialog.dismiss(); - } - - if (this.mCustomNotification != null && this.mCustomNotification.isShowing()) { - this.mCustomNotification.dismiss(); - } - } - } - - public void sendStheartRateBroadcast(Context paramContext, String actionStr, int paramInt) { - Intent intent = new Intent(); - intent.setAction(actionStr); - intent.putExtra("stheartRateType", paramInt); - paramContext.sendBroadcast(intent); - } - public void sendSOSBroadcast(Context paramContext, String actionStr) { - Intent intent = new Intent(); - intent.setAction(actionStr); - paramContext.sendBroadcast(intent); - } - - -} +package com.enqualcomm.support.utils; + +import android.app.Notification; +import android.app.NotificationManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Handler; +import android.os.Messenger; +import android.os.PowerManager; +import android.os.Vibrator; +import android.support.v4.app.NotificationCompat; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.view.WindowManager; + + +import com.enqualcomm.support.Config; +import com.enqualcomm.support.Constants; +import com.enqualcomm.support.CoreService; +import com.enqualcomm.support.LocationClient; +import com.enqualcomm.support.R; +import com.enqualcomm.support.bean.EventLooperHandlerThread; +import com.enqualcomm.support.bean.NotificationParam; +import com.enqualcomm.support.bean.Runtime; +import com.enqualcomm.support.bean.StringMessage; +import com.enqualcomm.support.bean.VoiceContent; +import com.enqualcomm.support.service.Deliver; +import com.ic.jni.ICJniUtils; +import com.enqualcomm.support.bean.Contact; +import com.enqualcomm.support.service.AudioService; +import com.enqualcomm.support.service.HeartRateManager; +import com.ic.protocols.protocolAPIHelper; + +import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; +import static android.media.RingtoneManager.TYPE_NOTIFICATION; +import static android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP; +import static android.os.PowerManager.SCREEN_DIM_WAKE_LOCK; +import static com.enqualcomm.support.Constants.ACTION_CLOSE_UNREAD_MSG; +import static com.enqualcomm.support.Constants.ACTION_HEATR_RATE_START; +import static com.enqualcomm.support.Constants.ACTION_MESSAGE_SENT; +import static com.enqualcomm.support.Constants.ACTION_PLAYTIME; +import static com.enqualcomm.support.Constants.ACTION_REMOTE_CAMERA; +import static com.enqualcomm.support.Constants.ACTION_SEND_EMEGENCY_LOCATION_START; +import static com.enqualcomm.support.Constants.ACTION_SEND_SOS_MSG; +import static com.enqualcomm.support.Constants.ACTION_SET_SIT_RANGE; +import static com.enqualcomm.support.Constants.ACTION_SHUTDOWN; +import static com.enqualcomm.support.Constants.ACTION_TEMP_RESULT; +import static com.enqualcomm.support.Constants.DIALOG_ACTION; +import static com.enqualcomm.support.Constants.KEY_MESSAGE_FROM; +import static com.enqualcomm.support.Constants.KEY_MESSAGE_TYPE; +import static com.enqualcomm.support.Constants.KEY_MESSAGE_URL; +import static com.enqualcomm.support.Constants.KEY_TEMP_BODY; +import static com.enqualcomm.support.Constants.KEY_TEMP_WRIST; +import static com.enqualcomm.support.Constants.RESUME_ACTION; + +import static com.enqualcomm.support.bean.Content.CONTACT_CATEGORY_GROUP; +import static com.enqualcomm.support.utils.TemperatureUtil.KEY_TEMP_BYPROTOCOL; +import static com.enqualcomm.support.utils.TemperatureUtil.KEY_TEMP_OUT; + + +public class ProcessReceiver extends BroadcastReceiver { + private static final int MICRO_CHAT = 2; + + private static int last_app_id; + + private static String last_message_name; + + private static CustomDialog mCustomDialog; + + private CustomNotification mCustomNotification; + + private CustomDialog.Builder mDialog; + + private CustomNotification.Builder mNotificationDialog; + + private NotificationManager mNotificationManager; + + private Vibrator vibrator; + + private float x1 = 0.0F; + + private float x2 = 0.0F; + + private float y1 = 0.0F; + + private float y2 = 0.0F; + + private static Handler mHandler=new Handler(EventLooperHandlerThread.makeLooper(ProcessReceiver.class.getSimpleName())); + private void initMyDialog(final Context context, final Contact contact, int app_id,String msg,boolean needreply) { + String var4 = contact==null?"SMS":contact.name; + + if (this.mDialog == null) { + this.mDialog = new CustomDialog.Builder(context); + } + + StringBuilder var5 = new StringBuilder(); + var5.append("===mCustomDialog ") + .append(mCustomDialog) + .append(" , appid ").append(app_id); + + ICLogger.i(var5.toString()); + if (mCustomDialog != null && mCustomDialog.isShowing() && last_message_name != null && var4 != null && last_message_name.equals(var4) && last_app_id == app_id) { + mCustomDialog.dismiss(); + } + + last_message_name = var4; + last_app_id = app_id; + CustomDialog.Builder tmpDialog; + if (app_id == 1) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.setting_title)).setApp(1); + StringBuilder var6 = new StringBuilder(); + var6.append(context.getString(R.string.voiceMessage)); + var6.append(" "); + var6.append(var4); + var6.append(context.getString(R.string.voiceMessageEnd)); + mCustomDialog = tmpDialog.setMessage(var6.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1x, int var2x) { + var1x.dismiss(); + ComponentName var3 = new ComponentName("com.enqualcomm.imessage", "com.enqualcomm.imessage.ui.chat.ChatActivity_"); + Intent var5 = new Intent("android.intent.action.MAIN"); + var5.putExtra("ACTIVITY_TYPE", 2); + var5.putExtra("contact", contact); + var5.addCategory("android.intent.category.DEFAULT"); + var5.addFlags(FLAG_ACTIVITY_NEW_TASK); + var5.setComponent(var3); + VibrateUtil.getInstance(context).VibrateOn(false); + try { + context.startActivity(var5); + } catch (Exception e) { + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + + } + }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } else if (app_id == 2) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.hht_misscall_call)).setApp(app_id); + StringBuilder var7 = new StringBuilder(); + var7.append(context.getString(R.string.hht_call_start)); + var7.append(var4); + var7.append(context.getString(R.string.hht_call_end)); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + }else if (app_id ==3){ + tmpDialog = this.mDialog.setTitle(context.getString(R.string.sms_title)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(context.getString(R.string.sms_notify)); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + ComponentName var3 = new ComponentName("com.zmapp.sms", "com.zmapp.sms.MainActivity"); + Intent var5 = new Intent("android.intent.action.MAIN"); + var5.addCategory("android.intent.category.DEFAULT"); + var5.addFlags(FLAG_ACTIVITY_NEW_TASK); + var5.setComponent(var3); + VibrateUtil.getInstance(context).VibrateOn(false); + try { + context.startActivity(var5); + } catch (Exception e) { + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + } + }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + }else if (app_id ==4) { + tmpDialog = this.mDialog.setTitle("WEB"+context.getString(R.string.sms_title)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(msg); + + if (needreply) { + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + if (CoreService.getInstance() != null) { + Runtime runtime = CoreService.getInstance().getRuntime(); + if (Config.custom_name.equals("YQ") || Config.custom_name.equals("YQ_EN")) { + runtime.setAlarmType(Runtime.AlarmType.ALARM_MSGREAD); + Config.setLastUnReadMessage(CoreService.getInstance(), ""); + Deliver.sendLocationMSG(protocolAPIHelper.getWarningMSG(runtime)); + } else { + CoreService.getInstance().getConnection().send(protocolAPIHelper.getPushTxtReadFlagToSrvMSG(runtime)); + } + } + } + }).create(); + }else{ + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + } + }).create(); + } + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } else if (app_id ==5) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.findDev)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(msg); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + stopmediaplayer(); + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + }else if (app_id ==6) { + tmpDialog = this.mDialog.setTitle(context.getString(R.string.notification_title)).setApp(1); + StringBuilder var7 = new StringBuilder(); + var7.append(msg); + mCustomDialog = tmpDialog.setMessage(var7.toString()).setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface var1, int var2) { + var1.dismiss(); + VibrateUtil.getInstance(context).VibrateOn(false); + stopmediaplayer(); + + if(msg.contains("Take Photo")) { + String packagename = "com.eqc.camera"; + String activityName = "com.eqc.camera.TakePictureActivity"; + if (Util.installed(context, "com.ic.camera")) { + packagename = "com.ic.camera"; + activityName = "com.ic.camera.MainActivity"; + } + ComponentName var3 = new ComponentName(packagename, activityName); + Intent var5 = new Intent("android.intent.action.MAIN"); + var5.addCategory("android.intent.category.DEFAULT"); + var5.addFlags(FLAG_ACTIVITY_NEW_TASK); + var5.setComponent(var3); + try { + context.startActivity(var5); + } catch (Exception e) { + e.printStackTrace(); + ICLogger.e(e.getMessage(),e); + } + } + } + }).create(); + mCustomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); + mCustomDialog.show(); + } + } + private void playFindDevVoice(Context context){ + + AudioService.getInstance().play(context.getAssets(), "Campus_Life.ogg"); + + } + private void stopmediaplayer(){ + AudioService.getInstance().stop(); + } + private void playNotificationVoice(Context paramContext) { + AudioService.getInstance().play(paramContext.getAssets(), "ring_msg.mp3"); + } + + private void playshutdownsound(Context paramContext) { + AudioService.getInstance().play(paramContext.getAssets(), "shutdownsound.mp3"); + } + + + private void screenOn(Context paramContext) { + final PowerManager.WakeLock wakelock = ((PowerManager)paramContext.getSystemService(Context.POWER_SERVICE)).newWakeLock(ACQUIRE_CAUSES_WAKEUP| SCREEN_DIM_WAKE_LOCK, ProcessReceiver.class.getSimpleName()); + wakelock.acquire(); + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + wakelock.release(); + } + },5000); + } + + @Override + public void onReceive(Context paramContext, Intent paramIntent) { + + boolean isSilence; + Contact contact; + String str = paramIntent.getAction(); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("action=="); + stringBuilder.append(str); + ICLogger.i(stringBuilder.toString()); + + if (CoreService.getInstance()==null) + { + ICLogger.i("CoreService is null skip deal with this message! "+str); + paramContext.startService(new Intent(paramContext,CoreService.class));// protocol service + return ; + } + if (RESUME_ACTION.equals(str)) { + SharPreferenceUtil.setPrefBoolean(paramContext, "key_is_resume", paramIntent.getBooleanExtra("is_resume", false)); + return; + }else if (ACTION_MESSAGE_SENT.equals(str)) { + + String msgType=paramIntent.getStringExtra(KEY_MESSAGE_TYPE); + String msgFrom=paramIntent.getStringExtra(KEY_MESSAGE_FROM); + String msgUrl=paramIntent.getStringExtra(KEY_MESSAGE_URL); + ICLogger.i("receive msg to send type="+msgType+", msg from = "+msgFrom+", msgUrl"+msgUrl); + if (msgFrom==null) msgFrom="123"; + /** + * * 1 语音—— 1.监听语音 * 2.SOS语音 * 3.扩展 + * * 2 图片—— 1.签到图片 * 2.指令图片 * 3.设备图片 * 4.扩展 + */ + if (msgType.equals("voice")) + { + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,1,3); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection()!=null) + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); + }else if (msgType.equals("pic")){ + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,2,3); + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection()!=null) { + + //h88专用功能,拍照时检查体温心率 + if(Util.getSystemProperties("persist.sys.do_check_condition","false").equals("true")) { + //开启测温 + if(CoreService.getInstance().getRuntime().check_stat_do_temp_test()) + TemperatureUtil.DoTempTest(); + + Util.mSleep(5000); + //开启测量PPG + if(CoreService.getInstance().getRuntime().check_stat_do_ppg_test()) + HeartRateManager.triggerPPGtest(); + } + //开启发送图片 + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); + } + } + }else if (ACTION_SHUTDOWN.equals(str)) { + + playshutdownsound(paramContext); + + Util.shutdown(); + return; + }else if (ACTION_PLAYTIME.equals(str)) { + LedUtil.setBlueLedOn(true); + mHandler.postDelayed(new Runnable() { + @Override + public void run() { + LedUtil.setBlueLedOn(false); + } + },2000L); + return; + }else if (ACTION_REMOTE_CAMERA.equals(str)) { + if (paramIntent.hasExtra("remote_number")){ + //接收拍照命令,执行拍照 + String str1 = paramIntent.getStringExtra("remote_number"); + mHandler.post(new Runnable() { + @Override + public void run() { + (new CameraUtil(paramContext)).getPictur(str1); + } + }); + }else{ + //接收到拍照完毕命令,发送照片 + String msgFrom=paramIntent.getStringExtra("number"); + String msgUrl=paramIntent.getStringExtra("filepath"); + ICLogger.i("receive taken photo to send "+msgUrl); + //创建voiceConent并添加到数据 + final VoiceContent voiceContent = VoiceContent.placeHolderOut(CONTACT_CATEGORY_GROUP, msgFrom, msgUrl,2,2); + + + // 把voiceContent拆解成1024的分包 + Util.parseToVoicePacketSent(voiceContent); + //trigger 分包发送 + if (CoreService.getInstance().getConnection()!=null) { + + //h88专用功能,拍照后检测体温和心率 + if(Util.getSystemProperties("persist.sys.do_check_condition","false").equals("true")) { + //开启测温 + if(CoreService.getInstance().getRuntime().check_stat_do_temp_test()) + TemperatureUtil.DoTempTest(); + + Util.mSleep(500); + //开启测量PPG + if(CoreService.getInstance().getRuntime().check_stat_do_ppg_test()) + HeartRateManager.triggerPPGtest(); + } + //开启发送照片 + CoreService.getInstance().getConnection().DeliverCMDMessageToSystem("SentVoicePacket", ""); + } + + } + + + return; + + }else if (DIALOG_ACTION.equals(str)) { + if (paramIntent.hasExtra("contact")) { + contact = (Contact) paramIntent.getParcelableExtra("contact"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (contact != null && !isSilence) { + if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, contact, 1,"",false); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + } + + this.screenOn(paramContext); + } + }else if (paramIntent.hasExtra("sms")) { + String sms = paramIntent.getStringExtra("sms"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (sms != null && !isSilence) { + //if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, null, 3,sms,false); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + //} + + this.screenOn(paramContext); + } + }else if (paramIntent.hasExtra("pushtxt")) { + String sms = paramIntent.getStringExtra("pushtxt"); + boolean needreply=false; + if (paramIntent.hasExtra("needreply")){ + needreply= paramIntent.getBooleanExtra("needreply",false); + } + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (sms != null && !isSilence) { + if (!DeviceInfoUtil.isTopActivity(paramContext)) { + this.initMyDialog(paramContext, null, 4, sms,needreply); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + } + + this.screenOn(paramContext); + } + }else if (paramIntent.hasExtra("findDev")) { + String finddevtxt = paramIntent.getStringExtra("findDev"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (finddevtxt != null && !isSilence) { + this.initMyDialog(paramContext, null, 5,finddevtxt,false); + this.playFindDevVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + + this.screenOn(paramContext); + } + }else if (paramIntent.hasExtra("takephoto")) { + String takephoto = paramIntent.getStringExtra("takephoto"); + SharPreferenceUtil.getPrefBoolean(paramContext, "key_is_resume", false); + isSilence = SharPreferenceUtil.getPrefBoolean(paramContext, "KEY_ISSILENCE", false); + if (takephoto != null && !isSilence) { + + this.initMyDialog(paramContext, null, 6,takephoto,false); + this.playNotificationVoice(paramContext); + VibrateUtil.getInstance(paramContext).VibrateOn(true); + + this.screenOn(paramContext); + } + } + + }else if (ACTION_TEMP_RESULT.equals(str)) { + double wrist_temp = paramIntent.getDoubleExtra(KEY_TEMP_WRIST, 0.0f); + double body_temp = paramIntent.getDoubleExtra(KEY_TEMP_BODY, 0.0f); + double tempOut = paramIntent.getDoubleExtra(KEY_TEMP_OUT, 0.0f); + boolean byprotocol=paramIntent.getBooleanExtra(KEY_TEMP_BYPROTOCOL,false); + if(byprotocol==false) { + if (Config.disableWristTemp) { + //ic68 + body_temp=wrist_temp; + } + ICLogger.i("Received Temperature wrist "+wrist_temp+" body "+body_temp); + StringMessage temperatureMsg = protocolAPIHelper.getTemperatureMSG(wrist_temp, body_temp, tempOut, null); + if (temperatureMsg != null) { + ICLogger.i("temp 发送体温测量值 " + temperatureMsg.isFromCache()); + } + Deliver.sendLocationMSG(temperatureMsg); + }else{ + ICLogger.i("Skip protocol Temperature wrist "+wrist_temp+" body "+body_temp); + + } + }else if (ACTION_SET_SIT_RANGE.equals(str)) { + if (paramIntent.hasExtra( Constants.KEY_SIT_RANGE)){ + int sitrange=paramIntent.getIntExtra(Constants.KEY_SIT_RANGE,0); + Config.setKeepSitRangeInMinutes(paramContext,sitrange); + ICLogger.i("set KeepSitRange int "+sitrange+" minutes!"); + ICLogger.i("则重置 lastCheckSitTime 以及 lastSitCheckStepCount"); + Runtime.lastSitCheckStepCount=CoreService.getInstance().getRuntime().getTotalStepCount(); + Runtime.lastSitCheckTiimeyyyyMMddHHmmss=TimeUtil.getSystemTime3(); + } + } else { + //如果来电了,还有未读的消息,干脆关掉,防止影响接电话。 + if (mCustomDialog != null && mCustomDialog.isShowing()) { + mCustomDialog.dismiss(); + } + + if (this.mCustomNotification != null && this.mCustomNotification.isShowing()) { + this.mCustomNotification.dismiss(); + } + } + } + + public void sendStheartRateBroadcast(Context paramContext, String actionStr, int paramInt) { + Intent intent = new Intent(); + intent.setAction(actionStr); + intent.putExtra("stheartRateType", paramInt); + paramContext.sendBroadcast(intent); + } + public void sendSOSBroadcast(Context paramContext, String actionStr) { + Intent intent = new Intent(); + intent.setAction(actionStr); + paramContext.sendBroadcast(intent); + } + + +} diff --git a/app/src/main/java/com/ic/protocols/protocol_ic.java b/app/src/main/java/com/ic/protocols/protocol_ic.java index 8a1760ee..9de10555 100644 --- a/app/src/main/java/com/ic/protocols/protocol_ic.java +++ b/app/src/main/java/com/ic/protocols/protocol_ic.java @@ -14,6 +14,7 @@ import com.enqualcomm.support.R; import com.enqualcomm.support.bean.Alarm; import com.enqualcomm.support.bean.Contact; import com.enqualcomm.support.bean.Content; +import com.enqualcomm.support.bean.EventLooperHandlerThread; import com.enqualcomm.support.bean.ICLocation; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.bean.StringMessage; @@ -335,6 +336,7 @@ public class protocol_ic { } + private Handler mHandler=new Handler(EventLooperHandlerThread.makeLooper(protocol_ic.class.getSimpleName())); /**/ public static StringMessage genStringMessage(String cmdName, String msg){ @@ -1650,7 +1652,7 @@ public class protocol_ic { runtime.setNeedAntioff(false); runtime.setNeddReportCutoff(false); //1 分钟后重置 - new Handler().postDelayed(new Runnable() { + mHandler.postDelayed(new Runnable() { @Override public void run() { Util.doMasterClear(runtime.getContextProxy().context); @@ -2336,7 +2338,7 @@ public class protocol_ic { // intent.putExtra("remote_number", id); // context.startService(intent); // runtime.getContextProxy().context.sendBroadcast(intent); - new Handler().post(new Runnable() { + mHandler.post(new Runnable() { @Override public void run() { (new CameraUtil(context)).getPictur(id); diff --git a/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java b/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java index fcbc8516..14888c41 100644 --- a/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java +++ b/app/src/main/java/com/ic/protocols/protocol_mqtt_client.java @@ -1,223 +1,225 @@ -package com.ic.protocols; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.Handler; -import android.os.IBinder; -import android.os.Message; -import android.util.Log; - -import com.enqualcomm.support.Config; -import com.enqualcomm.support.utils.ICLogger; - -import se.wetcat.qatja.MQTTConstants; -import se.wetcat.qatja.android.MQTTConnectionConstants; -import se.wetcat.qatja.android.QatjaService; -import se.wetcat.qatja.messages.MQTTMessage; -import se.wetcat.qatja.messages.MQTTPublish; - -public class protocol_mqtt_client { - - private String TAG = protocol_mqtt_client.class.getSimpleName(); - private Handler mHandler = new Handler(new MqttCallback()); - QatjaService mClient = null; - private Context mContext; - private boolean isBound = false; - private boolean isBinding = false; - public static String topic_header=""; - - public void setSubscriptTopicHeader(String header){ - topic_header=header; - } - private class MqttCallback implements Handler.Callback { - @Override - public boolean handleMessage(Message msg) { - - ICLogger.i("MqttCallback handleMessage "+msg.what); - switch (msg.what) { - case MQTTConnectionConstants.STATE_CHANGE: - handleStateChange(msg); - break; - case 3: - handleReceivedMessage(msg); - break; - } - return true; - } - - } - MqttCallbackInterface mqttCallbackInterface=null; - public protocol_mqtt_client(Context context,MqttCallbackInterface _mqttCallbackInterface) { - - mqttCallbackInterface=_mqttCallbackInterface; - mContext = context; - } - - private void handleStateChange(Message msg) { - ICLogger.i(MQTTConnectionConstants.resolveStateName(msg.arg1)); - - switch (msg.arg1) { - case MQTTConnectionConstants.STATE_NONE: - if (mqttCallbackInterface!= null) - mqttCallbackInterface.onMqttDisconnected(); - break; - case MQTTConnectionConstants.STATE_CONNECTING: - break; - case MQTTConnectionConstants.STATE_CONNECTED: - if (mqttCallbackInterface!=null) - mqttCallbackInterface.onMqttConnected(); - break; - case MQTTConnectionConstants.STATE_CONNECTION_FAILED: - if (mqttCallbackInterface!=null) - mqttCallbackInterface.onMqttDisconnected(); - break; - default: - Log.e(TAG, "Unhandled MQTT state change"); - break; - } - } - - private void handleReceivedMessage(Message msg) { - MQTTPublish publish = (MQTTPublish) msg.obj; - -// if (isDebug()) { - Log.d(TAG, "handleReceivedMessage(${publish.topicName})" + publish.getTopicName() + " data " + new String(publish.getPayload())); -// } - - String cmdtype= publish.getTopicName().replace(topic_header,""); - if (Config.LOG_TOFILE)ICLogger.logToFile("APILog", "mqtt recv " + publish.getTopicName() +" "+ new String(publish.getPayload())); - if (mqttCallbackInterface!=null) - mqttCallbackInterface.handleMqttMessage(cmdtype, publish.getPayload()); - } - - private ServiceConnection mConnection = new ServiceConnection() { - @Override - public void onServiceConnected(ComponentName componentName, IBinder iBinder) { - mClient = ((QatjaService.QatjaBinder) iBinder).getService(); - - isBound = true; - isBinding = false; - ICLogger.i("OnBind"); - mClient.setHandler(mHandler); - - attemptConnectMqtt(); - } - - @Override - public void onServiceDisconnected(ComponentName componentName) { - isBound = false; - isBinding = false; - } - }; - - - public void Resume() { - attemptBindService(); - } - - public void Pause() { - try { - if(mClient!=null) mClient.disconnect(); - - mContext.unbindService(mConnection); - - isBinding = false; - isBound = false; - } catch (Exception ex) { - Log.e(TAG, "Couldn't unbind the service, this is probably fine considering the state changes in the app... can probably ignore this.", ex); - } - - - } - - public void attemptSubscribeToTopic(String topic) { - Log.d(TAG, "attemptSubscribeToTopic($topic)" + topic); - - - try { - mClient.subscribe(topic, MQTTConstants.AT_MOST_ONCE); - } catch (Exception ex) { - Log.e(TAG, ex.getMessage()); - } - - } - - public void disconnect() { - Pause(); - } - - public void connectservice() { - if (isBound) { -// attemptConnectMqtt(); - } else if (!isBound && !isBinding) { - attemptBindService(); - } - } - - private void attemptBindService() { -// if (isDebug()) { - Log.d(TAG, "attemptBindService() [isBound: $isBound, isBinding: $isBinding]"); -// } - if (!isBound && !isBinding) { - isBinding = true; - - Intent intent = new Intent(mContext, QatjaService.class); - mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - } - - } - private String mqttHost=""; - private String devid=""; - private int mqtt_port=8083; - private int mqtt_cycle_seconds=600; - public void configMqtt(String host,int port,int cycle_seconds,String idname){ - mqttHost=host; - devid=idname; - mqtt_port=port; - mqtt_cycle_seconds=cycle_seconds; - } - - - public void attemptConnectMqtt(){ - attemptConnectMqtt(mqttHost,mqtt_port,devid,mqtt_cycle_seconds); - } - public void attemptConnectMqtt(String host, int port,String identifier, int cycle_inSeconds) { - ICLogger.i("attemptConnectMqtt("+host+", "+port+" "+identifier+" "+cycle_inSeconds); - - if (!(MQTTConnectionConstants.STATE_CONNECTING == mClient.getState() || MQTTConnectionConstants.STATE_CONNECTED == mClient.getState())) { - try { - - ICLogger.i("attemptConnectMqtt"); - mClient.setHost(host); - mClient.setUsername(protocol_mqtt.username); - mClient.setPassword(protocol_mqtt.passwd); - mClient.setPort(port); - mClient.setIdentifier(identifier); - mClient.setKeepAlive(cycle_inSeconds); -// mClient.setKeepAlive(10); - mClient.setCleanSession(true); - mClient.connect(); - } catch (Exception ex) { - Log.e(TAG, ex.getMessage()); - } - } - } - - public void sendMessage(String cmdtype,String data){ -// ICLogger.logToFile("APILog",cmdtype+" "+data); - mClient.publish(cmdtype,data); - } - - public interface MqttCallbackInterface - { - void onMqttConnected() ; - - void onMqttDisconnected(); - - void handleMqttMessage(String cmdtype,byte[] msgdata); - void handleMqttMessage(String cmdtype,String msgdata); - - } -} +package com.ic.protocols; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.util.Log; + +import com.enqualcomm.support.Config; +import com.enqualcomm.support.bean.EventLooperHandlerThread; +import com.enqualcomm.support.utils.ICLogger; + +import se.wetcat.qatja.MQTTConstants; +import se.wetcat.qatja.android.MQTTConnectionConstants; +import se.wetcat.qatja.android.QatjaService; +import se.wetcat.qatja.messages.MQTTMessage; +import se.wetcat.qatja.messages.MQTTPublish; + +public class protocol_mqtt_client { + + private String TAG = protocol_mqtt_client.class.getSimpleName(); + private Handler mHandler ; + QatjaService mClient = null; + private Context mContext; + private boolean isBound = false; + private boolean isBinding = false; + public static String topic_header=""; + + public void setSubscriptTopicHeader(String header){ + topic_header=header; + } + private class MqttCallback implements Handler.Callback { + @Override + public boolean handleMessage(Message msg) { + + ICLogger.i("MqttCallback handleMessage "+msg.what); + switch (msg.what) { + case MQTTConnectionConstants.STATE_CHANGE: + handleStateChange(msg); + break; + case 3: + handleReceivedMessage(msg); + break; + } + return true; + } + + } + MqttCallbackInterface mqttCallbackInterface=null; + public protocol_mqtt_client(Context context,MqttCallbackInterface _mqttCallbackInterface) { + + mqttCallbackInterface=_mqttCallbackInterface; + mContext = context; + mHandler = new Handler(EventLooperHandlerThread.makeLooper(MqttCallback.class.getSimpleName()),new MqttCallback()); + } + + private void handleStateChange(Message msg) { + ICLogger.i(MQTTConnectionConstants.resolveStateName(msg.arg1)); + + switch (msg.arg1) { + case MQTTConnectionConstants.STATE_NONE: + if (mqttCallbackInterface!= null) + mqttCallbackInterface.onMqttDisconnected(); + break; + case MQTTConnectionConstants.STATE_CONNECTING: + break; + case MQTTConnectionConstants.STATE_CONNECTED: + if (mqttCallbackInterface!=null) + mqttCallbackInterface.onMqttConnected(); + break; + case MQTTConnectionConstants.STATE_CONNECTION_FAILED: + if (mqttCallbackInterface!=null) + mqttCallbackInterface.onMqttDisconnected(); + break; + default: + Log.e(TAG, "Unhandled MQTT state change"); + break; + } + } + + private void handleReceivedMessage(Message msg) { + MQTTPublish publish = (MQTTPublish) msg.obj; + +// if (isDebug()) { + Log.d(TAG, "handleReceivedMessage(${publish.topicName})" + publish.getTopicName() + " data " + new String(publish.getPayload())); +// } + + String cmdtype= publish.getTopicName().replace(topic_header,""); + if (Config.LOG_TOFILE)ICLogger.logToFile("APILog", "mqtt recv " + publish.getTopicName() +" "+ new String(publish.getPayload())); + if (mqttCallbackInterface!=null) + mqttCallbackInterface.handleMqttMessage(cmdtype, publish.getPayload()); + } + + private ServiceConnection mConnection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + mClient = ((QatjaService.QatjaBinder) iBinder).getService(); + + isBound = true; + isBinding = false; + ICLogger.i("OnBind"); + mClient.setHandler(mHandler); + + attemptConnectMqtt(); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + isBound = false; + isBinding = false; + } + }; + + + public void Resume() { + attemptBindService(); + } + + public void Pause() { + try { + if(mClient!=null) mClient.disconnect(); + + mContext.unbindService(mConnection); + + isBinding = false; + isBound = false; + } catch (Exception ex) { + Log.e(TAG, "Couldn't unbind the service, this is probably fine considering the state changes in the app... can probably ignore this.", ex); + } + + + } + + public void attemptSubscribeToTopic(String topic) { + Log.d(TAG, "attemptSubscribeToTopic($topic)" + topic); + + + try { + mClient.subscribe(topic, MQTTConstants.AT_MOST_ONCE); + } catch (Exception ex) { + Log.e(TAG, ex.getMessage()); + } + + } + + public void disconnect() { + Pause(); + } + + public void connectservice() { + if (isBound) { +// attemptConnectMqtt(); + } else if (!isBound && !isBinding) { + attemptBindService(); + } + } + + private void attemptBindService() { +// if (isDebug()) { + Log.d(TAG, "attemptBindService() [isBound: $isBound, isBinding: $isBinding]"); +// } + if (!isBound && !isBinding) { + isBinding = true; + + Intent intent = new Intent(mContext, QatjaService.class); + mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); + } + + } + private String mqttHost=""; + private String devid=""; + private int mqtt_port=8083; + private int mqtt_cycle_seconds=600; + public void configMqtt(String host,int port,int cycle_seconds,String idname){ + mqttHost=host; + devid=idname; + mqtt_port=port; + mqtt_cycle_seconds=cycle_seconds; + } + + + public void attemptConnectMqtt(){ + attemptConnectMqtt(mqttHost,mqtt_port,devid,mqtt_cycle_seconds); + } + public void attemptConnectMqtt(String host, int port,String identifier, int cycle_inSeconds) { + ICLogger.i("attemptConnectMqtt("+host+", "+port+" "+identifier+" "+cycle_inSeconds); + + if (!(MQTTConnectionConstants.STATE_CONNECTING == mClient.getState() || MQTTConnectionConstants.STATE_CONNECTED == mClient.getState())) { + try { + + ICLogger.i("attemptConnectMqtt"); + mClient.setHost(host); + mClient.setUsername(protocol_mqtt.username); + mClient.setPassword(protocol_mqtt.passwd); + mClient.setPort(port); + mClient.setIdentifier(identifier); + mClient.setKeepAlive(cycle_inSeconds); +// mClient.setKeepAlive(10); + mClient.setCleanSession(true); + mClient.connect(); + } catch (Exception ex) { + Log.e(TAG, ex.getMessage()); + } + } + } + + public void sendMessage(String cmdtype,String data){ +// ICLogger.logToFile("APILog",cmdtype+" "+data); + mClient.publish(cmdtype,data); + } + + public interface MqttCallbackInterface + { + void onMqttConnected() ; + + void onMqttDisconnected(); + + void handleMqttMessage(String cmdtype,byte[] msgdata); + void handleMqttMessage(String cmdtype,String msgdata); + + } +}