From: kfl_614 Date: Thu, 10 Dec 2020 08:45:16 +0000 (+0800) Subject: keep slient when message income in project L05 and L03. X-Git-Url: http://git.snicker.com.cn/Users/apple/Desktop/static/gitweb.css?a=commitdiff_plain;h=19dc2408eb443f9d191a7e5afd8f5942227351e7;p=protocol_srv.git keep slient when message income in project L05 and L03. --- diff --git a/app/build.gradle b/app/build.gradle index 140dfff2..5ca36f5e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -90,8 +90,8 @@ android { // } } dependencies { - compileOnly files ('libs/frameworks-full-debug.jar') - provided files ('libs/telephony_common-full-debug.jar') + compileOnly files('libs/frameworks-full-debug.jar') + provided files('libs/telephony_common-full-debug.jar') implementation 'com.android.support.constraint:constraint-layout:1.1.3' //compile fileTree(include: ['*.jar', '*.aar'], dir: 'libs') @@ -100,12 +100,12 @@ dependencies { }) implementation 'com.android.support:appcompat-v7:25.1.0' implementation 'com.github.ChestnutPlus:TestModules:v1.0.16' - testCompile 'junit:junit:4.12' + testImplementation 'junit:junit:4.12' implementation project(path: ':dNSCache') implementation 'com.android.support:recyclerview-v7:25.1.0' - compile files ('libs/android-logging-log4j-1.0.3.jar','libs/ftp4j-1.7.2.jar','libs/log4j-1.2.17.jar','libs/okio-2.4.3.jar' ) - compile files ('libs/mail.jar' ) - compile files ('libs/activation.jar','libs/additionnal.jar' ) + implementation files('libs/android-logging-log4j-1.0.3.jar', 'libs/ftp4j-1.7.2.jar', 'libs/log4j-1.2.17.jar', 'libs/okio-2.4.3.jar') + implementation files('libs/mail.jar') + implementation files('libs/activation.jar', 'libs/additionnal.jar') implementation 'se.wetcat.qatja:core:1.0.4' // implementation "androidx.recyclerview:recyclerview:1.1.0 @@ -135,10 +135,11 @@ def releaseTime() { return new Date().format("yyMMddHHmm", TimeZone.getTimeZone("GMT+08:00")) } + preBuild { doLast { - def imlFile = file( project.name + ".iml") + def imlFile = file(project.name + ".iml") println 'Change ' + project.name + '.iml order' try { def parsedXml = (new XmlParser()).parse(imlFile) diff --git a/app/release/ICSer_V517_2012101455_release.apk b/app/release/ICSer_V517_2012101455_release.apk new file mode 100644 index 00000000..f121b3dc Binary files /dev/null and b/app/release/ICSer_V517_2012101455_release.apk differ diff --git a/app/release/output.json b/app/release/output.json index d7513083..26a3d125 100644 --- a/app/release/output.json +++ b/app/release/output.json @@ -1 +1 @@ -[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":516,"versionName":"2009051621","enabled":true,"outputFile":"ICSer_V516_2009051621_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V516_2009051621_release.apk","properties":{}}] \ No newline at end of file +[{"outputType":{"type":"APK"},"apkData":{"type":"MAIN","splits":[],"versionCode":517,"versionName":"2012101455","enabled":true,"outputFile":"ICSer_V517_2012101455_release.apk","fullName":"release","baseName":"release"},"path":"ICSer_V517_2012101455_release.apk","properties":{}}] \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b3da421c..c5afcd33 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -98,11 +98,10 @@ android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:supportsRtl="true" - android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - > - - - + android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> + + + @@ -110,6 +109,7 @@ + @@ -122,7 +122,7 @@ - + @@ -165,9 +165,9 @@ - - - + + + diff --git a/app/src/main/java/com/enqualcomm/support/BootCompleteReceiver.java b/app/src/main/java/com/enqualcomm/support/BootCompleteReceiver.java index f43d40f9..a1356460 100644 --- a/app/src/main/java/com/enqualcomm/support/BootCompleteReceiver.java +++ b/app/src/main/java/com/enqualcomm/support/BootCompleteReceiver.java @@ -7,10 +7,10 @@ import android.content.Intent; import com.enqualcomm.support.utils.ICLogger; public class BootCompleteReceiver extends BroadcastReceiver { - public void onReceive(Context paramContext, Intent paramIntent) { - ICLogger.i("监听到开机广播"); - paramContext.startService(new Intent(paramContext, com.enqualcomm.support.CoreService.class)); - } + public void onReceive(Context paramContext, Intent paramIntent) { + ICLogger.i("监听到开机广播"); + paramContext.startService(new Intent(paramContext, CoreService.class)); + } } diff --git a/app/src/main/java/com/enqualcomm/support/MainActivity.java b/app/src/main/java/com/enqualcomm/support/MainActivity.java index f4b16d7e..6f310a3e 100644 --- a/app/src/main/java/com/enqualcomm/support/MainActivity.java +++ b/app/src/main/java/com/enqualcomm/support/MainActivity.java @@ -6,13 +6,10 @@ import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; +import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; -import android.os.StatFs; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; @@ -30,32 +27,26 @@ import java.io.FileOutputStream; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import chestnut.utils.RegexUtils; -import rx.Observable; -import rx.functions.Action1; - import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; public class MainActivity extends Activity { TextView tv; - private boolean showmessage=false; + private boolean showmessage = false; private ScheduledThreadPoolExecutor timer; - Handler handler=new Handler(new Handler.Callback() { + Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message message) { - - StringBuilder sb=new StringBuilder(); + StringBuilder sb = new StringBuilder(); try { - if (showmessage) { - if (CoreService.getInstance()!=null) + if (CoreService.getInstance() != null) sb.append(CoreService.getInstance().getServerAlive()); tv.setText(sb.toString()); } - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } @@ -63,21 +54,22 @@ public class MainActivity extends Activity { return false; } }); + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnConnect = (Button) findViewById(R.id.btnConnect); - tv = (TextView)findViewById(R.id.textView); + tv = (TextView) findViewById(R.id.textView); btnConnect.setOnClickListener(clickListener); - Button tbtn = (Button)findViewById(R.id.btn_tools); + Button tbtn = (Button) findViewById(R.id.btn_tools); tbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - Intent intent=new Intent(); + Intent intent = new Intent(); ComponentName var3 = new ComponentName("com.enqualcomm.support", "com.enqualcomm.support.toolActivity"); intent.addFlags(FLAG_ACTIVITY_NEW_TASK); intent.setComponent(var3); @@ -85,7 +77,7 @@ public class MainActivity extends Activity { } }); - // tesetSharedKey(); + // tesetSharedKey(); // SimSignalUtil.send_at_to_onoff_simcard(CoreService.getInstance().runtime)); @@ -114,28 +106,28 @@ public class MainActivity extends Activity { // ICLogger.i(" lat="+latitude+",lon="+longitude); - TextView tv_version=(TextView)findViewById(R.id.textViewVersion); - tv_version.setText(DeviceInfoUtil.getVersionCode(this)+"-"+DeviceInfoUtil.getVersionName(this)); + TextView tv_version = (TextView) findViewById(R.id.textViewVersion); + tv_version.setText(DeviceInfoUtil.getVersionCode(this) + "-" + DeviceInfoUtil.getVersionName(this)); // testpic(); } @Override - protected void onResume() { + protected void onResume() { super.onResume(); - timer=new ScheduledThreadPoolExecutor(10); + timer = new ScheduledThreadPoolExecutor(10); timer.scheduleAtFixedRate(new Runnable() { @Override public void run() { handler.sendEmptyMessage(0); } - }, 0, 2000,TimeUnit.MILLISECONDS); - showmessage=true; + }, 0, 2000, TimeUnit.MILLISECONDS); + showmessage = true; } @Override protected void onPause() { super.onPause(); - if (timer!=null) { + if (timer != null) { timer.shutdownNow(); // while(!timer.isTerminated()) // { @@ -149,57 +141,57 @@ public class MainActivity extends Activity { timer.purge(); timer = null; } - showmessage=false; + showmessage = false; } - public void testpic(){ + public void testpic() { - String str = null; - try { - if (Environment.getExternalStorageState().equals("mounted")) { + String str = null; + try { + if (Environment.getExternalStorageState().equals("mounted")) { // if ((new StatFs(Environment.getExternalStorageDirectory().toString())).getAvailableBytes() < paramArrayOfByte.length) - str = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(str); - stringBuilder.append("/TakePhoto_080835"); - stringBuilder.append(".jpg"); - str = stringBuilder.toString(); - Bitmap bitmap2 =BitmapFactory.decodeFile(str); + str = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(str); + stringBuilder.append("/TakePhoto_080835"); + stringBuilder.append(".jpg"); + str = stringBuilder.toString(); + Bitmap bitmap2 = BitmapFactory.decodeFile(str); // Bitmap bitmap2 = BitmapFactory.decodeByteArray(paramArrayOfByte, 0, paramArrayOfByte.length); // Bitmap bitmap1 = bitmap2; - Bitmap bitmap3 = bitmap2; - if ((this.getResources().getConfiguration()).orientation == 1) { + Bitmap bitmap3 = bitmap2; + if ((this.getResources().getConfiguration()).orientation == 1) { // Matrix matrix = new Matrix(); // matrix.reset(); - // matrix.postRotate(this.mOrientation); - // bitmap1 = Bitmap.createBitmap(bitmap2, 0, 0, bitmap2.getWidth(), bitmap2.getHeight(), matrix, true); - - } - bitmap3 = ImageUtil.drawTextToLeftTop(this,bitmap2, TimeUtil.getSystemTime(),24, Color.RED, 20, 20); - str = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); - stringBuilder = new StringBuilder(); - stringBuilder.append(str); - stringBuilder.append("/TakePhoto_0808352"); - stringBuilder.append(".jpg"); - str = stringBuilder.toString(); - File file = new File(str); - if (!file.exists()) - file.createNewFile(); - BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); - bitmap3.compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream); - bufferedOutputStream.flush(); - bufferedOutputStream.close(); - - ICLogger.i("Take Photo and Save to "+str); + // matrix.postRotate(this.mOrientation); + // bitmap1 = Bitmap.createBitmap(bitmap2, 0, 0, bitmap2.getWidth(), bitmap2.getHeight(), matrix, true); + } + bitmap3 = ImageUtil.drawTextToLeftTop(this, bitmap2, TimeUtil.getSystemTime(), 24, Color.RED, 20, 20); + str = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); + stringBuilder = new StringBuilder(); + stringBuilder.append(str); + stringBuilder.append("/TakePhoto_0808352"); + stringBuilder.append(".jpg"); + str = stringBuilder.toString(); + File file = new File(str); + if (!file.exists()) + file.createNewFile(); + BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); + bitmap3.compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream); + bufferedOutputStream.flush(); + bufferedOutputStream.close(); + + ICLogger.i("Take Photo and Save to " + str); + } - } catch (Exception e) { - e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); - } + } } @@ -210,9 +202,9 @@ public class MainActivity extends Activity { switch (view.getId()) { case R.id.btnConnect: //进行连接Socket:这里使用的是,在本地上开启了一个服务器。 - if (CoreService.getInstance()!=null) - Util.ShowToast(CoreService.getInstance().runtime,"Start ProtocolService!"); - startService(new Intent(MainActivity.this,CoreService.class));// protocol service + if (CoreService.getInstance() != null) + Util.ShowToast(CoreService.getInstance().runtime, "Start ProtocolService!"); + startService(new Intent(MainActivity.this, CoreService.class));// protocol service // Observable.timer(5000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { // @@ -236,13 +228,13 @@ public class MainActivity extends Activity { }; - public void tesetSharedKey(){ - Config.setSleepScore(this,344); - Config.setSleepDate(this,TimeUtil.getSystemTime3()); - Config.setKeepSitRangeInMinutes(this,3); - ICLogger.d("SHAREKEY_SETTING_SLEEP_SCORE_DATE "+ SharPreferenceUtil.getPrefStringPublic(this,Constants.SHAREKEY_SETTING_SLEEP_SCORE_DATE,"")); - ICLogger.d("SHAREKEY_SETTING_SLEEP_SCORE "+ SharPreferenceUtil.getPrefIntPublic(this,Constants.SHAREKEY_SETTING_SLEEP_SCORE,0)); - ICLogger.d("SHAREKEY_SETTING_SIT_ALARM_RANGE_IN_MINUTES "+ SharPreferenceUtil.getPrefIntPublic(this,Constants.SHAREKEY_SETTING_SIT_ALARM_RANGE_IN_MINUTES,0)); + public void tesetSharedKey() { + Config.setSleepScore(this, 344); + Config.setSleepDate(this, TimeUtil.getSystemTime3()); + Config.setKeepSitRangeInMinutes(this, 3); + ICLogger.d("SHAREKEY_SETTING_SLEEP_SCORE_DATE " + SharPreferenceUtil.getPrefStringPublic(this, Constants.SHAREKEY_SETTING_SLEEP_SCORE_DATE, "")); + ICLogger.d("SHAREKEY_SETTING_SLEEP_SCORE " + SharPreferenceUtil.getPrefIntPublic(this, Constants.SHAREKEY_SETTING_SLEEP_SCORE, 0)); + ICLogger.d("SHAREKEY_SETTING_SIT_ALARM_RANGE_IN_MINUTES " + SharPreferenceUtil.getPrefIntPublic(this, Constants.SHAREKEY_SETTING_SIT_ALARM_RANGE_IN_MINUTES, 0)); } } 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 4bb6997f..1b6e9edf 100644 --- a/app/src/main/java/com/enqualcomm/support/service/SilentManager.java +++ b/app/src/main/java/com/enqualcomm/support/service/SilentManager.java @@ -13,20 +13,17 @@ import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.telephony.PhoneStateListener; -import android.telephony.PreciseCallState; import android.telephony.TelephonyManager; import com.enqualcomm.support.Config; import com.enqualcomm.support.CoreService; 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.NoticeContent; import com.enqualcomm.support.bean.Runtime; import com.enqualcomm.support.bean.Silent; import com.enqualcomm.support.bean.StheartRate; - import com.enqualcomm.support.service.base.AbstractInvokeHandlerService; import com.enqualcomm.support.utils.AlarmHelper; import com.enqualcomm.support.utils.Connection; @@ -36,7 +33,6 @@ import com.enqualcomm.support.utils.ICLogger; import com.enqualcomm.support.utils.MissedCallContentObserver; import com.enqualcomm.support.utils.SharPreferenceUtil; import com.enqualcomm.support.utils.TimeUtil; -import com.enqualcomm.support.utils.Util; import java.util.ArrayList; import java.util.Calendar; @@ -47,832 +43,828 @@ import java.util.concurrent.TimeUnit; import rx.Observable; import rx.functions.Action1; -import static android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED; import static android.telephony.TelephonyManager.CALL_STATE_OFFHOOK; import static android.telephony.TelephonyManager.CALL_STATE_RINGING; import static com.enqualcomm.support.Constants.ACTION_CARE_ALARM; 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.SERVICE_CLS_NAME; import static com.enqualcomm.support.Constants.SERVICE_PKG_NAME; public class SilentManager extends AbstractInvokeHandlerService { - private static final long ONE_WEEK = 604800000L; - private static final long ONE_DAY = 86400000L; - - private ArrayList alarms; - private boolean haveHandSilence; - private boolean isCalling; - AlarmManager mAlarmManager; - private SilentManager.AlramReceiver mAlramReceiver; - Connection mConnection; - ContentObserver mContentObserver = new ContentObserver(new Handler()) { - public void onChange(boolean var1) { - ICLogger.i("静默有变化"); - SilentManager.this.silentList = SilentManager.this.querySilent(); - SilentManager.this.getSilentListStartAndEndTime(); - SilentManager.this.handleSilent(mRuntime, true); + private static final long ONE_WEEK = 604800000L; + private static final long ONE_DAY = 86400000L; + + private ArrayList alarms; + private boolean haveHandSilence; + private boolean isCalling; + AlarmManager mAlarmManager; + private SilentManager.AlramReceiver mAlramReceiver; + Connection mConnection; + ContentObserver mContentObserver = new ContentObserver(new Handler()) { + public void onChange(boolean var1) { + ICLogger.i("静默有变化"); + SilentManager.this.silentList = SilentManager.this.querySilent(); + SilentManager.this.getSilentListStartAndEndTime(); + SilentManager.this.handleSilent(mRuntime, true); + } + }; + private Context mContext; + private DBHelper mDbHelper; + private boolean mInSilent; + private String mInterval; + private boolean mIsNeedAntioff; + private boolean mIsStheartRate; + private MissedCallContentObserver mMissedCallContentObserver; + Runtime mRuntime; + private int mStheartRateInterval; + private int mTodayWeek; + private boolean mValue_isSilence; + + public static final int PRECISE_CALL_STATE_NOT_VALID = -1; + public static final int PRECISE_CALL_STATE_IDLE = 0; //空闲 + public static final int PRECISE_CALL_STATE_ACTIVE = 1; //正在通话 + public static final int PRECISE_CALL_STATE_HOLDING = 2; //通话挂起 + public static final int PRECISE_CALL_STATE_DIALING = 3; //拨号开始 + public static final int PRECISE_CALL_STATE_ALERTING = 4; //正在呼出 + public static final int PRECISE_CALL_STATE_INCOMING = 5; //对方来电 + public static final int PRECISE_CALL_STATE_WAITING = 6; //第三方来电等待 + public static final int PRECISE_CALL_STATE_DISCONNECTED = 7; //挂断完成 + public static final int PRECISE_CALL_STATE_DISCONNECTING = 8; //正在挂断 + + private static SilentManager mSilentManger = null; + + public static SilentManager getInstance() { + if (mSilentManger == null) + mSilentManger = new SilentManager(); + return mSilentManger; } - }; - private Context mContext; - private DBHelper mDbHelper; - private boolean mInSilent; - private String mInterval; - private boolean mIsNeedAntioff; - private boolean mIsStheartRate; - private MissedCallContentObserver mMissedCallContentObserver; - Runtime mRuntime; - private int mStheartRateInterval; - private int mTodayWeek; - private boolean mValue_isSilence; - - public static final int PRECISE_CALL_STATE_NOT_VALID = -1; - public static final int PRECISE_CALL_STATE_IDLE = 0; //空闲 - public static final int PRECISE_CALL_STATE_ACTIVE = 1; //正在通话 - public static final int PRECISE_CALL_STATE_HOLDING = 2; //通话挂起 - public static final int PRECISE_CALL_STATE_DIALING = 3; //拨号开始 - public static final int PRECISE_CALL_STATE_ALERTING = 4; //正在呼出 - public static final int PRECISE_CALL_STATE_INCOMING = 5; //对方来电 - public static final int PRECISE_CALL_STATE_WAITING = 6; //第三方来电等待 - public static final int PRECISE_CALL_STATE_DISCONNECTED = 7; //挂断完成 - public static final int PRECISE_CALL_STATE_DISCONNECTING = 8; //正在挂断 - - private static SilentManager mSilentManger=null; - - public static SilentManager getInstance(){ - if (mSilentManger==null) - mSilentManger=new SilentManager(); - return mSilentManger; - } - private PhoneStateListener phoneStateListener = new PhoneStateListener() { - public void onCallStateChanged(int state, String incomingNumber) { - super.onCallStateChanged(state, incomingNumber); - - ICLogger.i("========onCallStateChanged state "+state+", incomingNumber "+incomingNumber); - switch(state) { - case PRECISE_CALL_STATE_DISCONNECTING: //挂电话 - case PRECISE_CALL_STATE_DISCONNECTED: //挂电话 - isCalling = false; + + private PhoneStateListener phoneStateListener = new PhoneStateListener() { + public void onCallStateChanged(int state, String incomingNumber) { + super.onCallStateChanged(state, incomingNumber); + + ICLogger.i("========onCallStateChanged state " + state + ", incomingNumber " + incomingNumber); + switch (state) { + case PRECISE_CALL_STATE_DISCONNECTING: //挂电话 + case PRECISE_CALL_STATE_DISCONNECTED: //挂电话 + isCalling = false; // if (SilentManager.this.haveHandSilence) { // SilentManager.this.handSilence(SilentManager.this.mContext, SilentManager.this.mValue_isSilence); // } - if(ICAudioManager.needMute==true) - { + if (ICAudioManager.needMute == true) { // ICAudioManager.restoreVolumn(mContext); //2秒后恢复音量 - Observable.timer(2000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - ICAudioManager.restoreVolumn(mContext); //2秒后恢复音量 - ICAudioManager.needMute=false; - } - }); - - } - ICLogger.i("========Hung up!"); - break; - case PRECISE_CALL_STATE_INCOMING: //来电 - case PRECISE_CALL_STATE_ALERTING: - case PRECISE_CALL_STATE_DIALING: - isCalling = true; - Intent var3 = new Intent(); - var3.setAction(ACTION_CLOSE_UNREAD_MSG); - mContext.sendBroadcast(var3); - - ICLogger.i("========Ring!"); - if(ICAudioManager.needMute==true) - { - ICAudioManager.setVolumnMute(mContext); - Observable.timer(2000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - ICAudioManager.setVolumnMute(mContext); //2秒后恢复音量 - } - }); - - } - break; - case PRECISE_CALL_STATE_ACTIVE://接电话 - { - if (ICAudioManager.needMute == false){ - if (Config.custom_branch_name.equals("AK")) - ICAudioManager.setVoiceCallMaxVolumn(mContext); //设置最大音量 - } + Observable.timer(2000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { + public void call(Long param1Long) { + ICAudioManager.restoreVolumn(mContext); //2秒后恢复音量 + ICAudioManager.needMute = false; + } + }); + + } + ICLogger.i("========Hung up!"); + break; + case PRECISE_CALL_STATE_INCOMING: //来电 + case PRECISE_CALL_STATE_ALERTING: + case PRECISE_CALL_STATE_DIALING: + isCalling = true; + Intent var3 = new Intent(); + var3.setAction(ACTION_CLOSE_UNREAD_MSG); + mContext.sendBroadcast(var3); + + ICLogger.i("========Ring!"); + if (ICAudioManager.needMute == true) { + ICAudioManager.setVolumnMute(mContext); + Observable.timer(2000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { + public void call(Long param1Long) { + ICAudioManager.setVolumnMute(mContext); //2秒后恢复音量 + } + }); + + } + break; + case PRECISE_CALL_STATE_ACTIVE://接电话 + { + if (ICAudioManager.needMute == false) { + if (Config.custom_branch_name.equals("AK")) + ICAudioManager.setVoiceCallMaxVolumn(mContext); //设置最大音量 + } + } + case PRECISE_CALL_STATE_HOLDING://接电话 + case PRECISE_CALL_STATE_WAITING: + isCalling = true; + ICLogger.i("========Answer Call !"); + if (ICAudioManager.needMute == true) { + ICAudioManager.setVolumnMute(mContext); + Observable.timer(2000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { + public void call(Long param1Long) { + ICAudioManager.setVolumnMute(mContext); //2秒后恢复音量 + } + }); + } + + } + } - case PRECISE_CALL_STATE_HOLDING://接电话 - case PRECISE_CALL_STATE_WAITING: - isCalling = true; - ICLogger.i("========Answer Call !"); - if(ICAudioManager.needMute==true) - { - ICAudioManager.setVolumnMute(mContext); - Observable.timer(2000L, TimeUnit.MILLISECONDS).subscribe(new Action1() { - public void call(Long param1Long) { - ICAudioManager.setVolumnMute(mContext); //2秒后恢复音量 - } - }); - } - - } + }; + private ArrayList sAntioffList; + private ArrayList silentList; + private ArrayList stheartRateList; + private ArrayList voiceNotice; - } - }; - private ArrayList sAntioffList; - private ArrayList silentList; - private ArrayList stheartRateList; - private ArrayList voiceNotice; - - public SilentManager() { - } - - private void callback(Messenger var1, boolean var2) { - short var3; - if (var2) { - var3 = 600; - } else { - var3 = 700; + public SilentManager() { } - if (var1 != null) { - try { - var1.send(Message.obtain((Handler)null, var3)); - } catch (Exception var4) { - var4.printStackTrace(); - } - } + private void callback(Messenger var1, boolean var2) { + short var3; + if (var2) { + var3 = 600; + } else { + var3 = 700; + } - } + if (var1 != null) { + try { + var1.send(Message.obtain((Handler) null, var3)); + } catch (Exception var4) { + var4.printStackTrace(); + } + } - private void cancelAlarm(ArrayList var1) { - Iterator var2 = var1.iterator(); + } - while(var2.hasNext()) { - Alarm var3 = (Alarm)var2.next(); - String var10 = var3.time; - String var4 = var3.week; - String var5 = var3.ring; - String var11 = var3.name; - char[] var6 = var4.toCharArray(); - int var7 = var6.length; + private void cancelAlarm(ArrayList var1) { + Iterator var2 = var1.iterator(); + + while (var2.hasNext()) { + Alarm var3 = (Alarm) var2.next(); + String var10 = var3.time; + String var4 = var3.week; + String var5 = var3.ring; + String var11 = var3.name; + char[] var6 = var4.toCharArray(); + int var7 = var6.length; + + for (int var8 = 1; var8 < var7; ++var8) { + char var9 = var6[var8]; + this.mAlarmManager.cancel(this.getPendingIntent(var10, var4, var5, var11, var9 - 47)); + } + } - for(int var8 = 1; var8 < var7; ++var8) { - char var9 = var6[var8]; - this.mAlarmManager.cancel(this.getPendingIntent(var10, var4, var5, var11, var9 - 47)); - } } - } - - private void cancelNoticeAlarm(ArrayList var1) { - Iterator var2 = var1.iterator(); - - while(var2.hasNext()) { - NoticeContent var3 = (NoticeContent)var2.next(); - String var4 = var3.noticeTime; - String var9 = var3.noticeName; - String var5 = var3.noticeNumber; - String var6 = var3.noticeID; - String var7 = var3.noticeCategory; - String var8 = var3.noticeFrequency; - String var10 = var3.noticeContent; - this.mAlarmManager.cancel(this.getPendingIntent(var4, var9, var5, var6, var7, var8, var10)); - } + private void cancelNoticeAlarm(ArrayList var1) { + Iterator var2 = var1.iterator(); + + while (var2.hasNext()) { + NoticeContent var3 = (NoticeContent) var2.next(); + String var4 = var3.noticeTime; + String var9 = var3.noticeName; + String var5 = var3.noticeNumber; + String var6 = var3.noticeID; + String var7 = var3.noticeCategory; + String var8 = var3.noticeFrequency; + String var10 = var3.noticeContent; + this.mAlarmManager.cancel(this.getPendingIntent(var4, var9, var5, var6, var7, var8, var10)); + } - } - - private PendingIntent getPendingIntent(String var1, String var2, String var3, String var4, int var5) { - StringBuilder var6 = new StringBuilder("alarm:"); - var6.append(var1); - var6.append(","); - var6.append(var2); - var6.append(","); - var6.append(var3); - var6.append(","); - var6.append(var4); - var6.append(","); - var6.append(var5); - var2 = var6.toString(); - Intent var7 = new Intent(this.mContext, CoreService.class); - var7.setAction(ACTION_CARE_ALARM); - var7.setData(Uri.parse(var2)); - return PendingIntent.getService(this.mContext, 0, var7, PendingIntent.FLAG_UPDATE_CURRENT); - } - - private PendingIntent getPendingIntent(String var1, String var2, String var3, String var4, String var5, String var6, String var7) { - StringBuilder var8 = new StringBuilder("notice:"); - var8.append(var1); - var8.append(","); - var8.append(var2); - var8.append(","); - var8.append(var3); - var8.append(","); - var8.append(var4); - var8.append(","); - var8.append(var5); - var8.append(","); - var8.append(var6); - var8.append(","); - var8.append(var7); - var1 = var8.toString(); - Intent var9 = new Intent(this.mContext, CoreService.class); - var9.setAction("com.enqualcomm.support.ACTION_NOTICE_ALARM"); - var9.setData(Uri.parse(var1)); - return PendingIntent.getService(this.mContext, 0, var9, PendingIntent.FLAG_UPDATE_CURRENT); - } - - private void getSilentListStartAndEndTime() { - Calendar var1 = Calendar.getInstance(); - this.mTodayWeek = var1.get(Calendar.DAY_OF_WEEK); - - Silent var3; - for(Iterator var2 = this.silentList.iterator(); var2.hasNext(); var3.endTimeMillis = var1.getTimeInMillis()) { - var3 = (Silent)var2.next(); - var1.set(Calendar.SECOND, 0); - int var4 = Integer.parseInt(var3.start.substring(2, 4)); - int var5 = Integer.parseInt(var3.start.substring(5, 7)); - var1.set(Calendar.HOUR_OF_DAY, var4); - var1.set(Calendar.MINUTE, var5); - var3.startTimeMillis = var1.getTimeInMillis(); - var5 = Integer.parseInt(var3.end.substring(2, 4)); - var4 = Integer.parseInt(var3.end.substring(5, 7)); - var1.set(Calendar.HOUR_OF_DAY, var5); - var1.set(Calendar.MINUTE, var4); } - } - - private void getStartAndEndSantioffTime() { - Calendar var1 = Calendar.getInstance(); - this.mTodayWeek = var1.get(Calendar.DAY_OF_WEEK); - - Antioff var3; - for(Iterator var2 = this.sAntioffList.iterator(); var2.hasNext(); var3.endTimeMillis = var1.getTimeInMillis()) { - var3 = (Antioff)var2.next(); - var1.set(Calendar.SECOND, 0); - int var4 = Integer.parseInt(var3.start.substring(2, 4)); - int var5 = Integer.parseInt(var3.start.substring(5, 7)); - var1.set(Calendar.HOUR_OF_DAY, var4); - var1.set(Calendar.MINUTE, var5); - var3.startTimeMillis = var1.getTimeInMillis(); - var4 = Integer.parseInt(var3.end.substring(2, 4)); - var5 = Integer.parseInt(var3.end.substring(5, 7)); - var1.set(Calendar.HOUR_OF_DAY, var4); - var1.set(Calendar.MINUTE, var5); + private PendingIntent getPendingIntent(String var1, String var2, String var3, String var4, int var5) { + StringBuilder var6 = new StringBuilder("alarm:"); + var6.append(var1); + var6.append(","); + var6.append(var2); + var6.append(","); + var6.append(var3); + var6.append(","); + var6.append(var4); + var6.append(","); + var6.append(var5); + var2 = var6.toString(); + Intent var7 = new Intent(this.mContext, CoreService.class); + var7.setAction(ACTION_CARE_ALARM); + var7.setData(Uri.parse(var2)); + return PendingIntent.getService(this.mContext, 0, var7, PendingIntent.FLAG_UPDATE_CURRENT); } - } - - private void getStartAndEndStheartRateTime() { - Calendar var1 = Calendar.getInstance(); - this.mTodayWeek = var1.get(Calendar.DAY_OF_WEEK); - - StheartRate var3; - for(Iterator var2 = this.stheartRateList.iterator(); var2.hasNext(); var3.endTimeMillis = var1.getTimeInMillis()) { - var3 = (StheartRate)var2.next(); - var1.set(Calendar.SECOND, 0); - int var4 = Integer.parseInt(var3.start.substring(2, 4)); - int var5 = Integer.parseInt(var3.start.substring(5, 7)); - var1.set(Calendar.HOUR_OF_DAY, var4); - var1.set(Calendar.MINUTE, var5); - var3.startTimeMillis = var1.getTimeInMillis(); - var4 = Integer.parseInt(var3.end.substring(2, 4)); - var5 = Integer.parseInt(var3.end.substring(5, 7)); - var1.set(Calendar.HOUR_OF_DAY, var4); - var1.set(Calendar.MINUTE, var5); + private PendingIntent getPendingIntent(String var1, String var2, String var3, String var4, String var5, String var6, String var7) { + StringBuilder var8 = new StringBuilder("notice:"); + var8.append(var1); + var8.append(","); + var8.append(var2); + var8.append(","); + var8.append(var3); + var8.append(","); + var8.append(var4); + var8.append(","); + var8.append(var5); + var8.append(","); + var8.append(var6); + var8.append(","); + var8.append(var7); + var1 = var8.toString(); + Intent var9 = new Intent(this.mContext, CoreService.class); + var9.setAction("com.enqualcomm.support.ACTION_NOTICE_ALARM"); + var9.setData(Uri.parse(var1)); + return PendingIntent.getService(this.mContext, 0, var9, PendingIntent.FLAG_UPDATE_CURRENT); } - } - - private void handSilence(Context var1, boolean var2) { - this.mValue_isSilence = var2; - if (this.isCalling) { - this.haveHandSilence = true; - } else { - this.haveHandSilence = false; - SharPreferenceUtil.setPrefBoolean(var1, "KEY_ISSILENCE", var2); - Intent var3 = new Intent(); - var3.setAction("com.enqualcomm.support.ACTION_ISSILENCE2IMESSAGE"); - var3.putExtra("KEY_ISSILENCE", var2); - var1.sendBroadcast(var3); - ComponentName var4 = new ComponentName(SERVICE_PKG_NAME, SERVICE_CLS_NAME); - Intent var5 = (new Intent("com.enqualcomm.support.ACTION_VIDEO_END_CALL")).setComponent(var4); - this.mRuntime.getContextProxy().context.startService(var5); - } - } + private void getSilentListStartAndEndTime() { + Calendar var1 = Calendar.getInstance(); + this.mTodayWeek = var1.get(Calendar.DAY_OF_WEEK); + + Silent var3; + for (Iterator var2 = this.silentList.iterator(); var2.hasNext(); var3.endTimeMillis = var1.getTimeInMillis()) { + var3 = (Silent) var2.next(); + var1.set(Calendar.SECOND, 0); + int var4 = Integer.parseInt(var3.start.substring(2, 4)); + int var5 = Integer.parseInt(var3.start.substring(5, 7)); + var1.set(Calendar.HOUR_OF_DAY, var4); + var1.set(Calendar.MINUTE, var5); + var3.startTimeMillis = var1.getTimeInMillis(); + var5 = Integer.parseInt(var3.end.substring(2, 4)); + var4 = Integer.parseInt(var3.end.substring(5, 7)); + var1.set(Calendar.HOUR_OF_DAY, var5); + var1.set(Calendar.MINUTE, var4); + } - private void handleSilent(Runtime var1, boolean var2) { - int var3 = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); - if (var3 != this.mTodayWeek && (var3 != 1 || this.mTodayWeek != 8)) { - this.getSilentListStartAndEndTime(); - this.queryNotice(); } - boolean var4 = this.isSilentTime(); - StringBuilder var5 = new StringBuilder(); - var5.append("inSilent="); - var5.append(var4); - ICLogger.i(var5.toString()); - if (!this.mInSilent && var4) { - this.onSilentStateChange(true); - this.handSilence(this.mContext, true); - this.mDbHelper.upDateStatus("ON"); - } else if (this.mInSilent && !var4) { - this.onSilentStateChange(false); - this.mDbHelper.upDateStatus("OFF"); - this.handSilence(this.mContext, false); - } + private void getStartAndEndSantioffTime() { + Calendar var1 = Calendar.getInstance(); + this.mTodayWeek = var1.get(Calendar.DAY_OF_WEEK); + + Antioff var3; + for (Iterator var2 = this.sAntioffList.iterator(); var2.hasNext(); var3.endTimeMillis = var1.getTimeInMillis()) { + var3 = (Antioff) var2.next(); + var1.set(Calendar.SECOND, 0); + int var4 = Integer.parseInt(var3.start.substring(2, 4)); + int var5 = Integer.parseInt(var3.start.substring(5, 7)); + var1.set(Calendar.HOUR_OF_DAY, var4); + var1.set(Calendar.MINUTE, var5); + var3.startTimeMillis = var1.getTimeInMillis(); + var4 = Integer.parseInt(var3.end.substring(2, 4)); + var5 = Integer.parseInt(var3.end.substring(5, 7)); + var1.set(Calendar.HOUR_OF_DAY, var4); + var1.set(Calendar.MINUTE, var5); + } - this.mInSilent = var4; - this.getStartAndEndStheartRateTime(); - this.isStheartRateTime(var2); - } - - private boolean isIdle(Context context) { - int callstate = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getCallState(); - boolean isidle; - if (CALL_STATE_RINGING != callstate && CALL_STATE_OFFHOOK != callstate) { - isidle = true; - } else { - isidle = false; } - return isidle && !this.mInSilent && !this.mRuntime.getBatteryLow(); - } + private void getStartAndEndStheartRateTime() { + Calendar var1 = Calendar.getInstance(); + this.mTodayWeek = var1.get(Calendar.DAY_OF_WEEK); + + StheartRate var3; + for (Iterator var2 = this.stheartRateList.iterator(); var2.hasNext(); var3.endTimeMillis = var1.getTimeInMillis()) { + var3 = (StheartRate) var2.next(); + var1.set(Calendar.SECOND, 0); + int var4 = Integer.parseInt(var3.start.substring(2, 4)); + int var5 = Integer.parseInt(var3.start.substring(5, 7)); + var1.set(Calendar.HOUR_OF_DAY, var4); + var1.set(Calendar.MINUTE, var5); + var3.startTimeMillis = var1.getTimeInMillis(); + var4 = Integer.parseInt(var3.end.substring(2, 4)); + var5 = Integer.parseInt(var3.end.substring(5, 7)); + var1.set(Calendar.HOUR_OF_DAY, var4); + var1.set(Calendar.MINUTE, var5); + } - private boolean isAntioffTime(boolean var1) { - long var2 = System.currentTimeMillis(); - ArrayList var4 = this.sAntioffList; - int var5 = this.mTodayWeek; - var1 = true; - if (var5 == 1) { - this.mTodayWeek += 7; } - Iterator var12 = var4.iterator(); - - while(true) { - if (!var12.hasNext()) { - var1 = false; - break; - } - - Antioff var6 = (Antioff)var12.next(); - String var7 = var6.week; - StringBuilder var8 = new StringBuilder(); - var8.append(this.mTodayWeek - 1); - var8.append(""); - if (var7.contains(var8.toString())) { - long var9 = var6.startTimeMillis - var2; - int var11; - if (var9 < (long)(CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { - var11 = Integer.parseInt(var6.start.substring(2, 4)); - var5 = Integer.parseInt(var6.start.substring(5, 7)); - AlarmHelper.setTimeAlarm(this.mContext, var11, var5, "com.enqualcomm.support.OTHER_ALARM_START"); - var8 = new StringBuilder(); - var8.append("设置起始时间=hour"); - var8.append(var11); - var8.append("minute+"); - var8.append(var5); - ICLogger.i(var8.toString()); + private void handSilence(Context var1, boolean var2) { + this.mValue_isSilence = var2; + if (this.isCalling) { + this.haveHandSilence = true; + } else { + this.haveHandSilence = false; + SharPreferenceUtil.setPrefBoolean(var1, "KEY_ISSILENCE", var2); + Intent var3 = new Intent(); + var3.setAction("com.enqualcomm.support.ACTION_ISSILENCE2IMESSAGE"); + var3.putExtra("KEY_ISSILENCE", var2); + var1.sendBroadcast(var3); + ComponentName var4 = new ComponentName(SERVICE_PKG_NAME, SERVICE_CLS_NAME); + Intent var5 = (new Intent("com.enqualcomm.support.ACTION_VIDEO_END_CALL")).setComponent(var4); + this.mRuntime.getContextProxy().context.startService(var5); } + } - var9 = var6.endTimeMillis - var2; - if (var9 < (long)(CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { - var11 = Integer.parseInt(var6.end.substring(2, 4)); - var5 = Integer.parseInt(var6.end.substring(5, 7)); - AlarmHelper.setTimeAlarm(this.mContext, var11, var5, "com.enqualcomm.support.OTHER_ALARM_END"); - var8 = new StringBuilder(); - var8.append("设置结束时间=hour"); - var8.append(var11); - var8.append("minute+"); - var8.append(var5); - ICLogger.i(var8.toString()); + private void handleSilent(Runtime var1, boolean var2) { + int var3 = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); + if (var3 != this.mTodayWeek && (var3 != 1 || this.mTodayWeek != 8)) { + this.getSilentListStartAndEndTime(); + this.queryNotice(); } - if (var6.startTimeMillis <= var2 && var6.endTimeMillis > var2) { - break; + boolean var4 = this.isSilentTime(); + StringBuilder var5 = new StringBuilder(); + var5.append("inSilent="); + var5.append(var4); + ICLogger.i(var5.toString()); + if (!this.mInSilent && var4) { + this.onSilentStateChange(true); + this.handSilence(this.mContext, true); + this.mDbHelper.upDateStatus("ON"); + } else if (this.mInSilent && !var4) { + this.onSilentStateChange(false); + this.mDbHelper.upDateStatus("OFF"); + this.handSilence(this.mContext, false); } - } - } - this.mRuntime.setAntioffStatus(var1); - return var1; - } - - private boolean isSilentTime() { - long var1 = System.currentTimeMillis(); - ArrayList var3 = this.silentList; - int var4 = this.mTodayWeek; - boolean var5 = false; //默认不在silent时间段 - if (var4 == 1) { - this.mTodayWeek += 7; + this.mInSilent = var4; + this.getStartAndEndStheartRateTime(); + this.isStheartRateTime(var2); } - Iterator var6 = var3.iterator(); - - while(true) { - if (!var6.hasNext()) { - var5 = false; - break; - } - - Silent var12 = (Silent)var6.next(); - String var7 = var12.week; - StringBuilder var8 = new StringBuilder(); - var8.append(this.mTodayWeek - 1); - var8.append(""); - if (var7.contains(var8.toString())) { - long var9 = var12.startTimeMillis - var1; - int var11; - StringBuilder var13; - if (var9 < (long)(CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { - var11 = Integer.parseInt(var12.start.substring(2, 4)); - var4 = Integer.parseInt(var12.start.substring(5, 7)); - AlarmHelper.setTimeAlarm(this.mContext, var11, var4, "com.enqualcomm.support.OTHER_ALARM_START"); - var13 = new StringBuilder(); - var13.append("设置起始时间=hour"); - var13.append(var11); - var13.append("minute+"); - var13.append(var4); - ICLogger.i(var13.toString()); + private boolean isIdle(Context context) { + int callstate = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getCallState(); + boolean isidle; + if (CALL_STATE_RINGING != callstate && CALL_STATE_OFFHOOK != callstate) { + isidle = true; + } else { + isidle = false; } - var9 = var12.endTimeMillis - var1; - if (var9 < (long)(CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { - var11 = Integer.parseInt(var12.end.substring(2, 4)); - var4 = Integer.parseInt(var12.end.substring(5, 7)); - AlarmHelper.setTimeAlarm(this.mContext, var11, var4, "com.enqualcomm.support.OTHER_ALARM_END"); - var13 = new StringBuilder(); - var13.append("设置结束时间=hour"); - var13.append(var11); - var13.append("minute+"); - var13.append(var4); - ICLogger.i(var13.toString()); - } + return isidle && !this.mInSilent && !this.mRuntime.getBatteryLow(); + } - if (var12.startTimeMillis <= var1 && var12.endTimeMillis > var1) { - break; + private boolean isAntioffTime(boolean var1) { + long var2 = System.currentTimeMillis(); + ArrayList var4 = this.sAntioffList; + int var5 = this.mTodayWeek; + var1 = true; + if (var5 == 1) { + this.mTodayWeek += 7; } - } - } - return var5; - } + Iterator var12 = var4.iterator(); - private boolean isStheartRateTime(boolean var1) { - long var2 = System.currentTimeMillis(); - ArrayList var4 = this.stheartRateList; - if (this.mTodayWeek == 1) { - this.mTodayWeek += 7; - } + while (true) { + if (!var12.hasNext()) { + var1 = false; + break; + } - Iterator var12 = var4.iterator(); - - while(true) { - if (var12.hasNext()) { - StheartRate var5 = (StheartRate)var12.next(); - String var6 = var5.week; - StringBuilder var7 = new StringBuilder(); - var7.append(this.mTodayWeek - 1); - var7.append(""); - if (!var6.contains(var7.toString())) { - continue; + Antioff var6 = (Antioff) var12.next(); + String var7 = var6.week; + StringBuilder var8 = new StringBuilder(); + var8.append(this.mTodayWeek - 1); + var8.append(""); + if (var7.contains(var8.toString())) { + long var9 = var6.startTimeMillis - var2; + int var11; + if (var9 < (long) (CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { + var11 = Integer.parseInt(var6.start.substring(2, 4)); + var5 = Integer.parseInt(var6.start.substring(5, 7)); + AlarmHelper.setTimeAlarm(this.mContext, var11, var5, "com.enqualcomm.support.OTHER_ALARM_START"); + var8 = new StringBuilder(); + var8.append("设置起始时间=hour"); + var8.append(var11); + var8.append("minute+"); + var8.append(var5); + ICLogger.i(var8.toString()); + } + + var9 = var6.endTimeMillis - var2; + if (var9 < (long) (CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { + var11 = Integer.parseInt(var6.end.substring(2, 4)); + var5 = Integer.parseInt(var6.end.substring(5, 7)); + AlarmHelper.setTimeAlarm(this.mContext, var11, var5, "com.enqualcomm.support.OTHER_ALARM_END"); + var8 = new StringBuilder(); + var8.append("设置结束时间=hour"); + var8.append(var11); + var8.append("minute+"); + var8.append(var5); + ICLogger.i(var8.toString()); + } + + if (var6.startTimeMillis <= var2 && var6.endTimeMillis > var2) { + break; + } + } } - long var8 = var5.startTimeMillis - var2; - int var10; - int var11; - if (var8 < (long)(CoreService.alarmCycle * 60 * 1000) && var8 > 0L) { - var10 = Integer.parseInt(var5.start.substring(2, 4)); - var11 = Integer.parseInt(var5.start.substring(5, 7)); - AlarmHelper.setTimeAlarm(this.mContext, var10, var11, "com.enqualcomm.support.OTHER_HEARTRATE_ALARM_START"); + this.mRuntime.setAntioffStatus(var1); + return var1; + } + + private boolean isSilentTime() { + long var1 = System.currentTimeMillis(); + ArrayList var3 = this.silentList; + int var4 = this.mTodayWeek; + boolean var5 = false; //默认不在silent时间段 + if (var4 == 1) { + this.mTodayWeek += 7; } - var8 = var5.endTimeMillis - var2; - if (var8 < (long)(CoreService.alarmCycle * 60 * 1000) && var8 > 0L) { - var10 = Integer.parseInt(var5.end.substring(2, 4)); - var11 = Integer.parseInt(var5.end.substring(5, 7)); - AlarmHelper.setTimeAlarm(this.mContext, var10, var11, "com.enqualcomm.support.OTHER_HEARTRATE_ALARM_END"); + Iterator var6 = var3.iterator(); + + while (true) { + if (!var6.hasNext()) { + var5 = false; + break; + } + + Silent var12 = (Silent) var6.next(); + String var7 = var12.week; + StringBuilder var8 = new StringBuilder(); + var8.append(this.mTodayWeek - 1); + var8.append(""); + if (var7.contains(var8.toString())) { + long var9 = var12.startTimeMillis - var1; + int var11; + StringBuilder var13; + if (var9 < (long) (CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { + var11 = Integer.parseInt(var12.start.substring(2, 4)); + var4 = Integer.parseInt(var12.start.substring(5, 7)); + AlarmHelper.setTimeAlarm(this.mContext, var11, var4, "com.enqualcomm.support.OTHER_ALARM_START"); + var13 = new StringBuilder(); + var13.append("设置起始时间=hour"); + var13.append(var11); + var13.append("minute+"); + var13.append(var4); + ICLogger.i(var13.toString()); + } + + var9 = var12.endTimeMillis - var1; + if (var9 < (long) (CoreService.alarmCycle * 60 * 1000) && var9 > 0L) { + var11 = Integer.parseInt(var12.end.substring(2, 4)); + var4 = Integer.parseInt(var12.end.substring(5, 7)); + AlarmHelper.setTimeAlarm(this.mContext, var11, var4, "com.enqualcomm.support.OTHER_ALARM_END"); + var13 = new StringBuilder(); + var13.append("设置结束时间=hour"); + var13.append(var11); + var13.append("minute+"); + var13.append(var4); + ICLogger.i(var13.toString()); + } + + if (var12.startTimeMillis <= var1 && var12.endTimeMillis > var1) { + break; + } + } } - if (var5.startTimeMillis > var2 || var5.endTimeMillis <= var2) { - continue; + return var5; + } + + private boolean isStheartRateTime(boolean var1) { + long var2 = System.currentTimeMillis(); + ArrayList var4 = this.stheartRateList; + if (this.mTodayWeek == 1) { + this.mTodayWeek += 7; } - this.mInterval = var5.interval; - if (!var1) { + Iterator var12 = var4.iterator(); + + while (true) { + if (var12.hasNext()) { + StheartRate var5 = (StheartRate) var12.next(); + String var6 = var5.week; + StringBuilder var7 = new StringBuilder(); + var7.append(this.mTodayWeek - 1); + var7.append(""); + if (!var6.contains(var7.toString())) { + continue; + } + + long var8 = var5.startTimeMillis - var2; + int var10; + int var11; + if (var8 < (long) (CoreService.alarmCycle * 60 * 1000) && var8 > 0L) { + var10 = Integer.parseInt(var5.start.substring(2, 4)); + var11 = Integer.parseInt(var5.start.substring(5, 7)); + AlarmHelper.setTimeAlarm(this.mContext, var10, var11, "com.enqualcomm.support.OTHER_HEARTRATE_ALARM_START"); + } + + var8 = var5.endTimeMillis - var2; + if (var8 < (long) (CoreService.alarmCycle * 60 * 1000) && var8 > 0L) { + var10 = Integer.parseInt(var5.end.substring(2, 4)); + var11 = Integer.parseInt(var5.end.substring(5, 7)); + AlarmHelper.setTimeAlarm(this.mContext, var10, var11, "com.enqualcomm.support.OTHER_HEARTRATE_ALARM_END"); + } + + if (var5.startTimeMillis > var2 || var5.endTimeMillis <= var2) { + continue; + } + + this.mInterval = var5.interval; + if (!var1) { // AlarmHelper.setRealTimeAlarm(this.mContext, Integer.parseInt(this.mInterval), ACTION_HEATR_RATE_START); // this.mRuntime.getContextProxy().sendStheartRateBroadcast(ACTION_HEATR_RATE_START, 0); - } + } - var1 = true; - break; - } + var1 = true; + break; + } - var1 = false; - break; + var1 = false; + break; + } + + return var1; } - return var1; - } + private void onSilentStateChange(boolean var1) { + if (this.alarms != null) { + if (var1) { + this.cancelAlarm(this.alarms); + } else { + this.setNewAlarm(this.alarms); + } + } - private void onSilentStateChange(boolean var1) { - if (this.alarms != null) { - if (var1) { - this.cancelAlarm(this.alarms); - } else { - this.setNewAlarm(this.alarms); - } - } + if (this.voiceNotice != null) { + if (var1) { + this.cancelNoticeAlarm(this.voiceNotice); + } else { + this.setNewNoticeAlarm(this.voiceNotice); + } + } - if (this.voiceNotice != null) { - if (var1) { - this.cancelNoticeAlarm(this.voiceNotice); - } else { - this.setNewNoticeAlarm(this.voiceNotice); - } } - } + private ArrayList queryAlarm() { + ArrayList var1 = this.mDbHelper.queryAlarm(); + if (!this.mInSilent) { + if (this.alarms != null) { + this.cancelAlarm(this.alarms); + } - private ArrayList queryAlarm() { - ArrayList var1 = this.mDbHelper.queryAlarm(); - if (!this.mInSilent) { - if (this.alarms != null) { - this.cancelAlarm(this.alarms); - } + this.setNewAlarm(var1); + } - this.setNewAlarm(var1); + return var1; } - return var1; - } + private ArrayList queryAntioff() { + return this.mDbHelper.queryAntioff(true); + } - private ArrayList queryAntioff() { - return this.mDbHelper.queryAntioff(true); - } + private ArrayList queryNotice() { + String var1 = TimeUtil.getSystemTime4(); + ArrayList var2 = this.mDbHelper.queryNotice(var1); + if (!this.mInSilent) { + if (this.voiceNotice != null) { + this.cancelNoticeAlarm(this.voiceNotice); + } - private ArrayList queryNotice() { - String var1 = TimeUtil.getSystemTime4(); - ArrayList var2 = this.mDbHelper.queryNotice(var1); - if (!this.mInSilent) { - if (this.voiceNotice != null) { - this.cancelNoticeAlarm(this.voiceNotice); - } + this.setNewNoticeAlarm(var2); + } - this.setNewNoticeAlarm(var2); + return var2; } - return var2; - } - - private ArrayList querySilent() { - return this.mDbHelper.querySilence(true); - } - - private ArrayList queryStheartRate() { - return this.mDbHelper.queryStheartRate(true); - } - - private void setNewAlarm(ArrayList alarmArrayList) { - Calendar calendar = Calendar.getInstance(); - calendar.set(Calendar.SECOND, 0); - long currentTime = System.currentTimeMillis(); - Iterator itAlarm = alarmArrayList.iterator(); - - - while (itAlarm.hasNext()){ - Alarm alarm = (Alarm)itAlarm.next(); - if ("ON".equals(alarm.status)) { - int hour = Integer.parseInt(alarm.time.substring(2, 4)); - int minute = Integer.parseInt(alarm.time.substring(5, 7)); - calendar.set(Calendar.HOUR_OF_DAY, hour); - calendar.set(Calendar.MINUTE, minute); - - char[] weeklist = alarm.week.toCharArray(); - int weeklistlen = weeklist.length; - ICLogger.i("repeat = "+alarm.week+", list size = "+weeklistlen); - if (weeklistlen>1) { - //如果week大于0 则证明有循环,没有循环就证明只是一次的闹铃。 - for (int i = 1; i < weeklistlen; i++) { - - long tmpTimeInMillis; - int dayofweek = weeklist[i] - 47; - calendar.set(Calendar.DAY_OF_WEEK, dayofweek); - tmpTimeInMillis = calendar.getTimeInMillis(); - if (tmpTimeInMillis <= currentTime) { - tmpTimeInMillis += ONE_WEEK; - } - Date date = new Date(tmpTimeInMillis); - ICLogger.i("set date "+date.toLocaleString()); - PendingIntent pendingIntent = this.getPendingIntent(alarm.time, alarm.week, alarm.ring, alarm.name, dayofweek); - AlarmHelper.setAlarm(this.mAlarmManager, tmpTimeInMillis, pendingIntent); - } - }else{ - //只是一次的闹铃 - long tmpTimeInMillis; + private ArrayList querySilent() { + return this.mDbHelper.querySilence(true); + } + + private ArrayList queryStheartRate() { + return this.mDbHelper.queryStheartRate(true); + } + + private void setNewAlarm(ArrayList alarmArrayList) { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.SECOND, 0); + long currentTime = System.currentTimeMillis(); + Iterator itAlarm = alarmArrayList.iterator(); + + + while (itAlarm.hasNext()) { + Alarm alarm = (Alarm) itAlarm.next(); + if ("ON".equals(alarm.status)) { + int hour = Integer.parseInt(alarm.time.substring(2, 4)); + int minute = Integer.parseInt(alarm.time.substring(5, 7)); + calendar.set(Calendar.HOUR_OF_DAY, hour); + calendar.set(Calendar.MINUTE, minute); + + char[] weeklist = alarm.week.toCharArray(); + int weeklistlen = weeklist.length; + ICLogger.i("repeat = " + alarm.week + ", list size = " + weeklistlen); + if (weeklistlen > 1) { + //如果week大于0 则证明有循环,没有循环就证明只是一次的闹铃。 + for (int i = 1; i < weeklistlen; i++) { + + long tmpTimeInMillis; + int dayofweek = weeklist[i] - 47; + calendar.set(Calendar.DAY_OF_WEEK, dayofweek); + tmpTimeInMillis = calendar.getTimeInMillis(); + if (tmpTimeInMillis <= currentTime) { + tmpTimeInMillis += ONE_WEEK; + } + Date date = new Date(tmpTimeInMillis); + ICLogger.i("set date " + date.toLocaleString()); + PendingIntent pendingIntent = this.getPendingIntent(alarm.time, alarm.week, alarm.ring, alarm.name, dayofweek); + AlarmHelper.setAlarm(this.mAlarmManager, tmpTimeInMillis, pendingIntent); + } + } else { + //只是一次的闹铃 + long tmpTimeInMillis; // int dayofweek = weeklist[i] - 47; // calendar.set(Calendar.DAY_OF_WEEK, dayofweek); // tmpTimeInMillis = calendar.getTimeInMillis(); - Date date = new Date(System.currentTimeMillis()); - ICLogger.i("date "+date.toLocaleString()); - Calendar c = Calendar.getInstance(); - c.setTime(date); - int wek = c.get(Calendar.DAY_OF_WEEK); - calendar.set(Calendar.DAY_OF_WEEK, wek); - tmpTimeInMillis = calendar.getTimeInMillis(); - if (tmpTimeInMillis <= currentTime) { - tmpTimeInMillis += ONE_DAY; - } - date = new Date(tmpTimeInMillis); - c = Calendar.getInstance(); - c.setTime(date); - wek = c.get(Calendar.DAY_OF_WEEK); - - ICLogger.i("set date "+date.toLocaleString()); + Date date = new Date(System.currentTimeMillis()); + ICLogger.i("date " + date.toLocaleString()); + Calendar c = Calendar.getInstance(); + c.setTime(date); + int wek = c.get(Calendar.DAY_OF_WEEK); + calendar.set(Calendar.DAY_OF_WEEK, wek); + tmpTimeInMillis = calendar.getTimeInMillis(); + if (tmpTimeInMillis <= currentTime) { + tmpTimeInMillis += ONE_DAY; + } + date = new Date(tmpTimeInMillis); + c = Calendar.getInstance(); + c.setTime(date); + wek = c.get(Calendar.DAY_OF_WEEK); + + ICLogger.i("set date " + date.toLocaleString()); + + PendingIntent pendingIntent = this.getPendingIntent(alarm.time, alarm.week, alarm.ring, alarm.name, wek); + AlarmHelper.setAlarmOnce(this.mAlarmManager, tmpTimeInMillis, pendingIntent); + } - PendingIntent pendingIntent = this.getPendingIntent(alarm.time, alarm.week, alarm.ring, alarm.name, wek); - AlarmHelper.setAlarmOnce(this.mAlarmManager, tmpTimeInMillis, pendingIntent); + } } - - } } - } - - private void setNewNoticeAlarm(ArrayList var1) { - Iterator var19 = var1.iterator(); - - while(var19.hasNext()) { - NoticeContent var2 = (NoticeContent)var19.next(); - String var3 = var2.noticeTime; - String var4 = var2.noticeName; - String var5 = var2.noticeNumber; - String var6 = var2.noticeID; - String var7 = var2.noticeCategory; - String var8 = var2.noticeFrequency; - String var9 = var2.noticeContent; - Calendar var10 = Calendar.getInstance(); - long var11 = System.currentTimeMillis(); - var10.set(Calendar.SECOND, 0); - if (var3 != null) { - String var13 = var3.substring(0, 4); - String var20 = var3.substring(4, 6); - String var14 = var3.substring(6, 8); - String var15 = var3.substring(8, 10); - String var16 = var3.substring(10, 12); - var10.set(Calendar.YEAR, Integer.parseInt(var13)); - var10.set(Calendar.MONTH, Integer.parseInt(var20) - 1); - var10.set(Calendar.DATE, Integer.parseInt(var14)); - var10.set(Calendar.HOUR_OF_DAY, Integer.parseInt(var15)); - var10.set(Calendar.MINUTE, Integer.parseInt(var16)); - long var17 = var10.getTimeInMillis(); - if (var17 >= var11) { - PendingIntent var21 = this.getPendingIntent(var3, var4, var5, var6, var7, var8, var9); - AlarmHelper.setAlarm(this.mAlarmManager, var17, var21); + + private void setNewNoticeAlarm(ArrayList var1) { + Iterator var19 = var1.iterator(); + + while (var19.hasNext()) { + NoticeContent var2 = (NoticeContent) var19.next(); + String var3 = var2.noticeTime; + String var4 = var2.noticeName; + String var5 = var2.noticeNumber; + String var6 = var2.noticeID; + String var7 = var2.noticeCategory; + String var8 = var2.noticeFrequency; + String var9 = var2.noticeContent; + Calendar var10 = Calendar.getInstance(); + long var11 = System.currentTimeMillis(); + var10.set(Calendar.SECOND, 0); + if (var3 != null) { + String var13 = var3.substring(0, 4); + String var20 = var3.substring(4, 6); + String var14 = var3.substring(6, 8); + String var15 = var3.substring(8, 10); + String var16 = var3.substring(10, 12); + var10.set(Calendar.YEAR, Integer.parseInt(var13)); + var10.set(Calendar.MONTH, Integer.parseInt(var20) - 1); + var10.set(Calendar.DATE, Integer.parseInt(var14)); + var10.set(Calendar.HOUR_OF_DAY, Integer.parseInt(var15)); + var10.set(Calendar.MINUTE, Integer.parseInt(var16)); + long var17 = var10.getTimeInMillis(); + if (var17 >= var11) { + PendingIntent var21 = this.getPendingIntent(var3, var4, var5, var6, var7, var8, var9); + AlarmHelper.setAlarm(this.mAlarmManager, var17, var21); + } + } } - } + } - } - - public void onAlarmClock(Connection var1, Runtime var2) { - this.handleSilent(var2, true); - } - - public void onAttach(Connection var1, Runtime var2) { - this.mRuntime = var2; - this.mConnection = var1; - this.mContext = var2.getContextProxy().context; - this.mAlarmManager = (AlarmManager)this.mContext.getSystemService(Context.ALARM_SERVICE); - this.mDbHelper = var2.getDbHelper(); - this.silentList = this.querySilent(); - this.getSilentListStartAndEndTime(); - this.mInSilent = this.isSilentTime(); - DBHelper var3 = this.mDbHelper; - String var4; - if (this.mInSilent) { - var4 = "ON"; - } else { - var4 = "OFF"; + public void onAlarmClock(Connection var1, Runtime var2) { + this.handleSilent(var2, true); } - var3.upDateorInsertDeviceStatus(var4); - this.handSilence(this.mContext, this.mInSilent); - this.stheartRateList = this.queryStheartRate(); - this.getStartAndEndStheartRateTime(); - this.mIsStheartRate = this.isStheartRateTime(false); - this.alarms = this.queryAlarm(); - this.voiceNotice = this.queryNotice(); - var2.getContextProxy().context.getContentResolver().registerContentObserver(ICContentProvider.SILENT_URI, false, this.mContentObserver); - this.mAlramReceiver = new SilentManager.AlramReceiver(); - IntentFilter var5 = new IntentFilter(); - var5.addAction("com.enqualcomm.support.ACTION_NOTICE_ALARM_CHANGE"); - var5.addAction("com.enqualcomm.support.ACTION_ALARM_ALARM_CHANGE"); - var5.addAction("com.enqualcomm.support.STHEART_RATE_ALARM_CHANGE"); - var5.addAction("com.eqc.heartrate.action.RESULT"); - this.mContext.registerReceiver(this.mAlramReceiver, var5); - var2.getContextProxy().getTelephonyManager().listen(this.phoneStateListener, 32); - } - - public void onDetach(Connection var1, Runtime var2) { - var2.getContextProxy().context.getContentResolver().unregisterContentObserver(this.mContentObserver); - this.mContext.unregisterReceiver(this.mAlramReceiver); - } - - @Override - public boolean onUserRequest(Intent var1, Connection var2, Runtime var3) { - String action = var1.getAction(); - if (ACTION_CARE_ALARM.equals(action)) { - String alarmTime = var1.getDataString(); //alarm:ST00.43,W,CON,闹铃,2 - String currentTime = TimeUtil.getSystemTime(); - alarmTime.substring(6).split("\\."); - int alarmTime_minutes = Integer.parseInt(alarmTime.substring(6).split("\\.")[1].substring(0, 2)); - int alarmTime_hour = Integer.parseInt(alarmTime.substring(6).split("\\.")[0].substring(2)); - String[] currentTimeArray = currentTime.split(";")[1].split(":"); - int currentTime_hour = Integer.parseInt(currentTimeArray[0]); - int currentTime_minutes = Integer.parseInt(currentTimeArray[1]); - ICLogger.i("alarm time["+alarmTime_hour+":"+alarmTime_minutes+"], current time["+currentTime_hour+":"+currentTime_minutes+"]"); - if (alarmTime_hour != currentTime_hour || alarmTime_minutes != currentTime_minutes) { - return false; - } - - if (this.isIdle(this.mContext)) { - try { - Intent intent = new Intent("com.enqualcomm.icare.ALARM", Uri.parse(alarmTime)); - intent.putExtra("closeAlarm", 0); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.mContext.startActivity(intent); - } catch (Exception var9) { - var9.printStackTrace(); + public void onAttach(Connection var1, Runtime var2) { + this.mRuntime = var2; + this.mConnection = var1; + this.mContext = var2.getContextProxy().context; + this.mAlarmManager = (AlarmManager) this.mContext.getSystemService(Context.ALARM_SERVICE); + this.mDbHelper = var2.getDbHelper(); + this.silentList = this.querySilent(); + this.getSilentListStartAndEndTime(); + this.mInSilent = this.isSilentTime(); + DBHelper var3 = this.mDbHelper; + String var4; + if (this.mInSilent) { + var4 = "ON"; + } else { + var4 = "OFF"; } - } - } else if ("com.enqualcomm.support.ACTION_NOTICE_ALARM".equals(action)) { - String alarmTime = var1.getDataString(); - if (this.isIdle(this.mContext)) { - try { - var1 = new Intent("com.enqualcomm.icare.NOTICE", Uri.parse(alarmTime)); - var1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.mContext.startActivity(var1); - } catch (Exception var8) { - var8.printStackTrace(); - } - } - } else { - ICLogger.i("静默闹钟来了"); - boolean var4; - if (!"com.eqc.heartrate.action.SILENT_START".equals(action) && !"com.enqualcomm.support.OTHER_HEARTRATE_ALARM_START".equals(action)) { - var4 = false; - } else { - var4 = true; - } - - this.handleSilent(var3, var4 ^ true); + + var3.upDateorInsertDeviceStatus(var4); + this.handSilence(this.mContext, this.mInSilent); + this.stheartRateList = this.queryStheartRate(); + this.getStartAndEndStheartRateTime(); + this.mIsStheartRate = this.isStheartRateTime(false); + this.alarms = this.queryAlarm(); + this.voiceNotice = this.queryNotice(); + var2.getContextProxy().context.getContentResolver().registerContentObserver(ICContentProvider.SILENT_URI, false, this.mContentObserver); + this.mAlramReceiver = new SilentManager.AlramReceiver(); + IntentFilter var5 = new IntentFilter(); + var5.addAction("com.enqualcomm.support.ACTION_NOTICE_ALARM_CHANGE"); + var5.addAction("com.enqualcomm.support.ACTION_ALARM_ALARM_CHANGE"); + var5.addAction("com.enqualcomm.support.STHEART_RATE_ALARM_CHANGE"); + var5.addAction("com.eqc.heartrate.action.RESULT"); + this.mContext.registerReceiver(this.mAlramReceiver, var5); + var2.getContextProxy().getTelephonyManager().listen(this.phoneStateListener, 32); } - return false; - } + public void onDetach(Connection var1, Runtime var2) { + var2.getContextProxy().context.getContentResolver().unregisterContentObserver(this.mContentObserver); + this.mContext.unregisterReceiver(this.mAlramReceiver); + } - @Override - public boolean onUserRequest(Message paramMessage, Connection paramConnection, Runtime paramRuntime) { - return false; - } + @Override + public boolean onUserRequest(Intent var1, Connection var2, Runtime var3) { + String action = var1.getAction(); + if (ACTION_CARE_ALARM.equals(action)) { + String alarmTime = var1.getDataString(); //alarm:ST00.43,W,CON,闹铃,2 + String currentTime = TimeUtil.getSystemTime(); + alarmTime.substring(6).split("\\."); + int alarmTime_minutes = Integer.parseInt(alarmTime.substring(6).split("\\.")[1].substring(0, 2)); + int alarmTime_hour = Integer.parseInt(alarmTime.substring(6).split("\\.")[0].substring(2)); + String[] currentTimeArray = currentTime.split(";")[1].split(":"); + int currentTime_hour = Integer.parseInt(currentTimeArray[0]); + int currentTime_minutes = Integer.parseInt(currentTimeArray[1]); + ICLogger.i("alarm time[" + alarmTime_hour + ":" + alarmTime_minutes + "], current time[" + currentTime_hour + ":" + currentTime_minutes + "]"); + if (alarmTime_hour != currentTime_hour || alarmTime_minutes != currentTime_minutes) { + return false; + } + + if (this.isIdle(this.mContext)) { + try { + Intent intent = new Intent("com.enqualcomm.icare.ALARM", Uri.parse(alarmTime)); + intent.putExtra("closeAlarm", 0); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + this.mContext.startActivity(intent); + } catch (Exception var9) { + var9.printStackTrace(); + } + } + } else if ("com.enqualcomm.support.ACTION_NOTICE_ALARM".equals(action)) { + String alarmTime = var1.getDataString(); + if (this.isIdle(this.mContext)) { + try { + var1 = new Intent("com.enqualcomm.icare.NOTICE", Uri.parse(alarmTime)); + var1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + this.mContext.startActivity(var1); + } catch (Exception var8) { + var8.printStackTrace(); + } + } + } else { + ICLogger.i("静默闹钟来了"); + boolean var4; + if (!"com.eqc.heartrate.action.SILENT_START".equals(action) && !"com.enqualcomm.support.OTHER_HEARTRATE_ALARM_START".equals(action)) { + var4 = false; + } else { + var4 = true; + } - class AlramReceiver extends BroadcastReceiver { - AlramReceiver() { + this.handleSilent(var3, var4 ^ true); + } + + return false; + } + + @Override + public boolean onUserRequest(Message paramMessage, Connection paramConnection, Runtime paramRuntime) { + return false; } - public void onReceive(Context var1, Intent var2) { - String var6 = var2.getAction(); - StringBuilder var3 = new StringBuilder(); - var3.append("action = "); - var3.append(var6); - ICLogger.i(var3.toString()); - if ("com.enqualcomm.support.ACTION_NOTICE_ALARM_CHANGE".equals(var6)) { - SilentManager.this.voiceNotice = SilentManager.this.queryNotice(); - } else if ("com.enqualcomm.support.ACTION_ALARM_ALARM_CHANGE".equals(var6)) { - SilentManager.this.alarms = SilentManager.this.queryAlarm(); - } else if ("com.enqualcomm.support.STHEART_RATE_ALARM_CHANGE".equals(var6)) { - SilentManager.this.stheartRateList = SilentManager.this.queryStheartRate(); - SilentManager.this.getStartAndEndStheartRateTime(); - SilentManager.this.isStheartRateTime(false); - } else if ("com.eqc.heartrate.action.RESULT".equals(var6)) { - var6 = var2.getStringExtra("time"); - int var4 = var2.getIntExtra("value", 0); - int var5 = var2.getIntExtra("type", 0); - StringBuilder var7 = new StringBuilder(); - var7.append("("); - var7.append(var6); - var7.append("@"); - var7.append(var4); - var7.append("@"); - var7.append(var5); - var7.append(")"); - var6 = var7.toString(); + class AlramReceiver extends BroadcastReceiver { + AlramReceiver() { + } + + public void onReceive(Context var1, Intent var2) { + String var6 = var2.getAction(); + StringBuilder var3 = new StringBuilder(); + var3.append("action = "); + var3.append(var6); + ICLogger.i(var3.toString()); + if ("com.enqualcomm.support.ACTION_NOTICE_ALARM_CHANGE".equals(var6)) { + SilentManager.this.voiceNotice = SilentManager.this.queryNotice(); + } else if ("com.enqualcomm.support.ACTION_ALARM_ALARM_CHANGE".equals(var6)) { + SilentManager.this.alarms = SilentManager.this.queryAlarm(); + } else if ("com.enqualcomm.support.STHEART_RATE_ALARM_CHANGE".equals(var6)) { + SilentManager.this.stheartRateList = SilentManager.this.queryStheartRate(); + SilentManager.this.getStartAndEndStheartRateTime(); + SilentManager.this.isStheartRateTime(false); + } else if ("com.eqc.heartrate.action.RESULT".equals(var6)) { + var6 = var2.getStringExtra("time"); + int var4 = var2.getIntExtra("value", 0); + int var5 = var2.getIntExtra("type", 0); + StringBuilder var7 = new StringBuilder(); + var7.append("("); + var7.append(var6); + var7.append("@"); + var7.append(var4); + var7.append("@"); + var7.append(var5); + var7.append(")"); + var6 = var7.toString(); // SilentManager.this.mConnection.send(API.H60(SilentManager.this.mRuntime, var6)); - } else if ("com.enqualcomm.support.ACTION_ANTIOFF_ALARM_CHANGE".equals(var6)) { - SilentManager.this.sAntioffList = SilentManager.this.queryAntioff(); - SilentManager.this.getStartAndEndSantioffTime(); - SilentManager.this.mIsNeedAntioff = SilentManager.this.isAntioffTime(false); - } + } else if ("com.enqualcomm.support.ACTION_ANTIOFF_ALARM_CHANGE".equals(var6)) { + SilentManager.this.sAntioffList = SilentManager.this.queryAntioff(); + SilentManager.this.getStartAndEndSantioffTime(); + SilentManager.this.mIsNeedAntioff = SilentManager.this.isAntioffTime(false); + } + } } - } } \ No newline at end of file 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 9fc3ac6c..8d3b4e21 100644 --- a/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java +++ b/app/src/main/java/com/enqualcomm/support/utils/ProcessReceiver.java @@ -1,58 +1,33 @@ 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.Contact; import com.enqualcomm.support.bean.Runtime; 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.enqualcomm.support.service.Deliver; import com.ic.protocols.protocolAPIHelper; -import java.util.concurrent.TimeUnit; - -import rx.Observable; -import rx.Subscriber; -import rx.functions.Action1; -import rx.schedulers.Schedulers; - 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; @@ -63,7 +38,6 @@ 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; @@ -358,13 +332,12 @@ public class ProcessReceiver extends BroadcastReceiver { 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); - this.playNotificationVoice(paramContext); - VibrateUtil.getInstance(paramContext).VibrateOn(true); - } - - this.screenOn(paramContext); + //if (!DeviceInfoUtil.isTopActivity(paramContext)) { + //his.initMyDialog(paramContext, null, 3, sms); + //this.playNotificationVoice(paramContext); + //VibrateUtil.getInstance(paramContext).VibrateOn(true); + //} + //this.screenOn(paramContext); } } else if (paramIntent.hasExtra("pushtxt")) { String sms = paramIntent.getStringExtra("pushtxt"); 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 8f4c96a0..84997fed 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 @@ -9,46 +9,42 @@ import android.os.IBinder; import android.os.Message; import android.util.Log; -import java.io.IOException; - import se.wetcat.qatja.MQTTConstants; -import se.wetcat.qatja.MQTTException; 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 String TAG = protocol_mqtt_client.class.getSimpleName(); private Handler mHandler = new Handler(new MqttCallback()); - QatjaService mClient=null; + QatjaService mClient = null; private Context mContext; private boolean isBound = false; private boolean isBinding = false; private class MqttCallback implements Handler.Callback { @Override - public boolean handleMessage(Message msg) - { + public boolean handleMessage(Message msg) { - switch (msg.what) { - case MQTTConnectionConstants.STATE_CHANGE: - handleStateChange(msg); + switch (msg.what) { + case MQTTConnectionConstants.STATE_CHANGE: + handleStateChange(msg); + break; + case 3: + handleReceivedMessage(msg); break; - case 3: - handleReceivedMessage(msg); - break; - } - return true; } + return true; + } } - public protocol_mqtt_client(Context context ) { + public protocol_mqtt_client(Context context) { - mContext=context; + mContext = context; } + private void handleStateChange(Message msg) { Log.e(TAG, MQTTConnectionConstants.resolveStateName(msg.arg1)); @@ -67,22 +63,22 @@ public class protocol_mqtt_client { break; default: Log.e(TAG, "Unhandled MQTT state change"); - break; + break; } } private void handleReceivedMessage(Message msg) { - MQTTPublish publish = (MQTTPublish)msg.obj; + MQTTPublish publish = (MQTTPublish) msg.obj; // if (isDebug()) { - Log.d(TAG, "handleReceivedMessage(${publish.topicName})"+publish.getTopicName()+" data "+new String(publish.getPayload())); + Log.d(TAG, "handleReceivedMessage(${publish.topicName})" + publish.getTopicName() + " data " + new String(publish.getPayload())); // } } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { - mClient = ((QatjaService.QatjaBinder)iBinder).getService(); + mClient = ((QatjaService.QatjaBinder) iBinder).getService(); isBound = true; isBinding = false; @@ -98,7 +94,7 @@ public class protocol_mqtt_client { }; - public void Resume() { + public void Resume() { attemptBindService(); } @@ -110,7 +106,7 @@ public class protocol_mqtt_client { isBinding = false; isBound = false; - } catch ( IllegalArgumentException ex) { + } catch (IllegalArgumentException 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); } @@ -118,14 +114,14 @@ public class protocol_mqtt_client { } public void attemptSubscribeToTopic(String topic) { - Log.d(TAG, "attemptSubscribeToTopic($topic)"+topic); + Log.d(TAG, "attemptSubscribeToTopic($topic)" + topic); - try { - mClient.subscribe(topic, MQTTConstants.AT_MOST_ONCE); - } catch (Exception ex) { - Log.e(TAG, ex.getMessage()); - } + try { + mClient.subscribe(topic, MQTTConstants.AT_MOST_ONCE); + } catch (Exception ex) { + Log.e(TAG, ex.getMessage()); + } } @@ -143,7 +139,7 @@ public class protocol_mqtt_client { private void attemptBindService() { // if (isDebug()) { - Log.d(TAG, "attemptBindService() [isBound: $isBound, isBinding: $isBinding]"); + Log.d(TAG, "attemptBindService() [isBound: $isBound, isBinding: $isBinding]"); // } if (!isBound && !isBinding) { isBinding = true; @@ -154,16 +150,15 @@ public class protocol_mqtt_client { } - public void attemptConnectMqtt(String host,String identifier, int cycle_inSeconds) { + public void attemptConnectMqtt(String host, String identifier, int cycle_inSeconds) { Log.d(TAG, "attemptConnectMqtt($host, $identifier)"); - if (!(MQTTConnectionConstants.STATE_CONNECTING== mClient.getState() || MQTTConnectionConstants.STATE_CONNECTED == mClient.getState())) - { + if (!(MQTTConnectionConstants.STATE_CONNECTING == mClient.getState() || MQTTConnectionConstants.STATE_CONNECTED == mClient.getState())) { try { mClient.setHost(host); mClient.setPort(1883); mClient.setIdentifier(identifier); - mClient.setKeepAlive(cycle_inSeconds*1000); + mClient.setKeepAlive(cycle_inSeconds * 1000); mClient.setCleanSession(true); mClient.connect(); @@ -174,18 +169,19 @@ public class protocol_mqtt_client { } void onMqttConnected() { - Log.i(TAG,"onMqttConnected"); + Log.i(TAG, "onMqttConnected"); attemptSubscribeToTopic("WBG100/v1/1/+"); } + void onMqttDisconnected() { - Log.i(TAG,"onMqttDisconnected"); + Log.i(TAG, "onMqttDisconnected"); } - public void sendMessage(String topic,String data){ + public void sendMessage(String topic, String data) { - mClient.publish(topic,data); + mClient.publish(topic, data); } } diff --git a/app/src/main/java/se/wetcat/qatja/android/QatjaService.java b/app/src/main/java/se/wetcat/qatja/android/QatjaService.java index d6aa41dd..2e946223 100644 --- a/app/src/main/java/se/wetcat/qatja/android/QatjaService.java +++ b/app/src/main/java/se/wetcat/qatja/android/QatjaService.java @@ -99,389 +99,389 @@ import static se.wetcat.qatja.android.MQTTConnectionConstants.STATE_NONE; */ public class QatjaService extends Service { - private static final boolean DEBUG = true; - - private static final String TAG = QatjaService.class.getSimpleName(); - - /** - * Current state of the connection - */ - private volatile int mState = STATE_NONE; - - /** - * How long to wait before a reconnect attempt is made - */ - private long mReconnectDelay = 5000; - - /** - * Thread to handle setup of connections - */ - private ConnectThread mConnectThread; - - /** - * Thread to handle communication when connection is established. - */ - private ConnectedThread mConnectedThread; - - /** - * Keepalive timer - */ - private int KEEP_ALIVE_TIMER = 3000; - - /** - * Handler used to queue PINGRESP messages, will be automatically queued when sending a message, - * or when connecting. - */ - private Handler mKeepaliveHandler; - - /** - * - */ - private Handler mHandler = null; - - /** - * The local binder object - */ - private final QatjaBinder mBinder = new QatjaBinder(); - - /** - * The default is the localhost (emulator link to - */ - private String host = "47.106.237.76"; - - /** - * The default is no SSL, turning this on before connect will enforce an SSL connection attempt. - */ - private SSLSocketFactory socketFactory = null; - - private int port = 1883; - - /* - For some reason used in interop test suites... only reason it's included here. - */ - private String protocolName = null; - - /** - * Unique identifier for this client - */ - private String clientIdentifier; - - /* - * TODO: These should be removed from here in future release, no reason to store them here, right? - */ - private String mUsername, mPassword; - - private boolean cleanSession = true; - - private boolean willFlag; - private String willTopic; - private String willMessage; - private HashSet subscribedTopics; - - // PING VARIABLES - private volatile long lastPingResp = 0L; - private volatile long lastSentMessage = 0L; - - private MQTTIdentifierHelper mMqttIdentifierHelper; - - private boolean doAutomaticReconnect = false; - private Handler reconnectHandler = new Handler(); - private Runnable recoonectRunnable = new Runnable() { - @Override - public void run() { - if (mState != STATE_CONNECTING && mState != STATE_CONNECTED) { - connect(); - } + private static final boolean DEBUG = true; + + private static final String TAG = QatjaService.class.getSimpleName(); + + /** + * Current state of the connection + */ + private volatile int mState = STATE_NONE; + + /** + * How long to wait before a reconnect attempt is made + */ + private long mReconnectDelay = 5000; + + /** + * Thread to handle setup of connections + */ + private ConnectThread mConnectThread; + + /** + * Thread to handle communication when connection is established. + */ + private ConnectedThread mConnectedThread; + + /** + * Keepalive timer + */ + private int KEEP_ALIVE_TIMER = 3000; + + /** + * Handler used to queue PINGRESP messages, will be automatically queued when sending a message, + * or when connecting. + */ + private Handler mKeepaliveHandler; + + /** + * + */ + private Handler mHandler = null; + + /** + * The local binder object + */ + private final QatjaBinder mBinder = new QatjaBinder(); + + /** + * The default is the localhost (emulator link to + */ + private String host = "47.106.237.76"; + + /** + * The default is no SSL, turning this on before connect will enforce an SSL connection attempt. + */ + private SSLSocketFactory socketFactory = null; + + private int port = 1883; + + /* + For some reason used in interop test suites... only reason it's included here. + */ + private String protocolName = null; + + /** + * Unique identifier for this client + */ + private String clientIdentifier; + + /* + * TODO: These should be removed from here in future release, no reason to store them here, right? + */ + private String mUsername, mPassword; + + private boolean cleanSession = true; + + private boolean willFlag; + private String willTopic; + private String willMessage; + private HashSet subscribedTopics; + + // PING VARIABLES + private volatile long lastPingResp = 0L; + private volatile long lastSentMessage = 0L; + + private MQTTIdentifierHelper mMqttIdentifierHelper; + + private boolean doAutomaticReconnect = false; + private Handler reconnectHandler = new Handler(); + private Runnable recoonectRunnable = new Runnable() { + @Override + public void run() { + if (mState != STATE_CONNECTING && mState != STATE_CONNECTED) { + connect(); + } + } + }; + + private StateListener mStateListener = null; + + public interface StateListener { + void onStateChanged(int newState); + } + + public void setStateListener(StateListener stateListener) { + mStateListener = stateListener; + + if (mStateListener != null) { + mStateListener.onStateChanged(mState); + } } - }; - private StateListener mStateListener = null; + @Override + public void onCreate() { + super.onCreate(); - public interface StateListener { - void onStateChanged(int newState); - } + if (DEBUG) + Log.d(TAG, "onCreate"); - public void setStateListener(StateListener stateListener) { - mStateListener = stateListener; + subscribedTopics = new HashSet<>(); + + mMqttIdentifierHelper = new MQTTIdentifierHelper(); - if (mStateListener != null) { - mStateListener.onStateChanged(mState); } - } - @Override - public void onCreate() { - super.onCreate(); + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (DEBUG) + Log.d(TAG, "onStartCommand"); - if (DEBUG) - Log.d(TAG, "onCreate"); + // Start a sticky service, the system will try to recreate this service if killed. - subscribedTopics = new HashSet<>(); + return START_STICKY; + } - mMqttIdentifierHelper = new MQTTIdentifierHelper(); + @Override + public void onDestroy() { + cleanUp(); - } + setState(STATE_NONE); - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - if (DEBUG) - Log.d(TAG, "onStartCommand"); + if (DEBUG) + Log.d(TAG, "onDestroy"); - // Start a sticky service, the system will try to recreate this service if killed. + super.onDestroy(); + } - return START_STICKY; - } + @Override + public IBinder onBind(Intent intent) { + if (DEBUG) + Log.d(TAG, "onBind"); - @Override - public void onDestroy() { - cleanUp(); + return mBinder; + } - setState(STATE_NONE); + /** + * @author andreas + */ + public class QatjaBinder extends Binder { + public QatjaService getService() { + return QatjaService.this; + } + } - if (DEBUG) - Log.d(TAG, "onDestroy"); + /** + * Set Handler that receives all service state messages and mqtt messages + * + * @param handler The listener + */ + public void setHandler(Handler handler) { + mHandler = handler; + } - super.onDestroy(); - } + /** + * Send a CONNECT message to the server. + */ + private void connect(String clientIdentifier) { - @Override - public IBinder onBind(Intent intent) { - if (DEBUG) - Log.d(TAG, "onBind"); + MQTTConnect connect; + if (!TextUtils.isEmpty(mUsername) && !TextUtils.isEmpty(mPassword)) { + connect = MQTTConnect.newInstance(clientIdentifier, mUsername, mPassword); + } else { + connect = MQTTConnect.newInstance(clientIdentifier); + } - return mBinder; - } + connect.setCleanSession(cleanSession); + connect.setKeepAlive(60); + connect.setWillFlag(willFlag); + if (willFlag) { + connect.setWillTopic(willTopic); + connect.setWillMessage(willMessage); + } + + if (protocolName != null) + connect.setProtocolName(protocolName); - /** - * @author andreas - */ - public class QatjaBinder extends Binder { - public QatjaService getService() { - return QatjaService.this; + sendMessage(connect, false); } - } - - /** - * Set Handler that receives all service state messages and mqtt messages - * - * @param handler The listener - */ - public void setHandler(Handler handler) { - mHandler = handler; - } - - /** - * Send a CONNECT message to the server. - */ - private void connect(String clientIdentifier) { - - MQTTConnect connect; - if (!TextUtils.isEmpty(mUsername) && !TextUtils.isEmpty(mPassword)) { - connect = MQTTConnect.newInstance(clientIdentifier, mUsername, mPassword); - } else { - connect = MQTTConnect.newInstance(clientIdentifier); + + /** + * Publish a message (String) to a specified topic. + * + * @param topic Topic to publish to + * @param message Message to publish + */ + public void publish(String topic, String message) { + publish(topic, message.getBytes()); } - connect.setCleanSession(cleanSession); - connect.setKeepAlive(60); - connect.setWillFlag(willFlag); - if (willFlag) { - connect.setWillTopic(willTopic); - connect.setWillMessage(willMessage); + /** + * Publish a payload (byte[]) to a specified topic. + * + * @param topic Topic to publish to + * @param payload Message to publish + */ + public void publish(String topic, byte[] payload) { + publish(topic, payload, AT_MOST_ONCE); } - if (protocolName != null) - connect.setProtocolName(protocolName); - - sendMessage(connect, false); - } - - /** - * Publish a message (String) to a specified topic. - * - * @param topic Topic to publish to - * @param message Message to publish - */ - public void publish(String topic, String message) { - publish(topic, message.getBytes()); - } - - /** - * Publish a payload (byte[]) to a specified topic. - * - * @param topic Topic to publish to - * @param payload Message to publish - */ - public void publish(String topic, byte[] payload) { - publish(topic, payload, AT_MOST_ONCE); - } - - /** - * Publish a message to a specified topic. - * - * @param topic Topic to publish to - * @param message Message to publish - * @param qos Quality of service to publish as - */ - public void publish(String topic, String message, byte qos) { - publish(topic, message.getBytes(), qos); - } - - /** - * Publish a message (byte[]) to a specified topic. - * - * @param topic the topic - * @param payload the message - * @param qos the desired quality of service - */ - public void publish(String topic, byte[] payload, byte qos) { - MQTTPublish publish = MQTTPublish.newInstance(topic, payload, qos, mMqttIdentifierHelper.getIdentifier()); - sendMessage(publish); - } - - /** - * Publish a retained message to a specified topic. - * - * @param topic the topic - * @param message the message - * @param qos the desired quality of service - */ - public void publishRetain(String topic, String message, byte qos) { - publishRetain(topic, message.getBytes(), qos); - } - - /** - * Publish a retained message to a specified topic. - * - * @param topic the topic - * @param payload the message to publish - * @param qos the desired quality of service - */ - public void publishRetain(String topic, byte[] payload, byte qos) { - MQTTPublish publish = MQTTPublish.newInstance(topic, payload, qos); - publish.setRetain(true); - sendMessage(publish); - } - - /** - * Subscribe to a topic with Quality of Service (QoS) level - * {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE} - * - * @param topic Topic to subscribe to - */ - public void subscribe(String topic) { - String[] topics = {topic}; - subscribe(topics); - } - - /** - * Subscribe to multiple topics with quality of service - * {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE} - * - * @param topics Topics to subscribe to - */ - public void subscribe(String[] topics) { - byte[] qoss = new byte[topics.length]; - for (int i = 0; i < qoss.length; i++) - qoss[i] = AT_MOST_ONCE; - subscribe(topics, qoss); - } - - /** - * Subscribe to a topic - * - * @param topic Topic to subscribe to - * @param qos Quality of service, can be {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE}, - * {@link se.wetcat.qatja.MQTTConstants#AT_LEAST_ONCE}, or - * {@link se.wetcat.qatja.MQTTConstants#EXACTLY_ONCE}. - */ - public void subscribe(String topic, byte qos) { - String[] topics = {topic}; - byte[] qoss = {qos}; - subscribe(topics, qoss); - } - - /** - * Subscribe to multiple topics - * - * @param topics Topic to subscribe to - * @param qoss Quality of service, can be {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE}, - * {@link se.wetcat.qatja.MQTTConstants#AT_LEAST_ONCE}, or - * {@link se.wetcat.qatja.MQTTConstants#EXACTLY_ONCE}. - */ - public void subscribe(String[] topics, byte[] qoss) { - // Ensure the subscribedTopics isn't null - if (subscribedTopics == null) - subscribedTopics = new HashSet<>(); - - for(int i = 0; i < topics.length; i++) { - HashSet newTopics = new HashSet<>(); - - if(!subscribedTopics.contains(topics[i])) { - newTopics.add(topics[i]); - } - topics = newTopics.toArray(new String[0]); + /** + * Publish a message to a specified topic. + * + * @param topic Topic to publish to + * @param message Message to publish + * @param qos Quality of service to publish as + */ + public void publish(String topic, String message, byte qos) { + publish(topic, message.getBytes(), qos); } - if(topics.length == 0) { - return; + /** + * Publish a message (byte[]) to a specified topic. + * + * @param topic the topic + * @param payload the message + * @param qos the desired quality of service + */ + public void publish(String topic, byte[] payload, byte qos) { + MQTTPublish publish = MQTTPublish.newInstance(topic, payload, qos, mMqttIdentifierHelper.getIdentifier()); + sendMessage(publish); } - int id = mMqttIdentifierHelper.getIdentifier(); - - MQTTSubscribe subscribe = MQTTSubscribe.newInstance(topics, qoss, id); - sendMessage(subscribe); - - subscribedTopics.addAll(Arrays.asList(topics)); - - mMqttIdentifierHelper.addSentPackage(subscribe); - } - - // public synchronized void start() { - // if (DEBUG) - // Log.d(TAG, "start"); - // - // // Cancel any thread attempting to make a connection - // if (mConnectThread != null) { - // mConnectThread.cancel(); - // mConnectThread = null; - // } - // - // // Cancel any thread currently running a connection - // if (mConnectedThread != null) { - // mConnectedThread.cancel(); - // mConnectedThread = null; - // } - // - // setState(STATE_NONE); - // - // // if (host != null) - // // connect(host, port); - // } - - public synchronized void sendMessage(MQTTMessage msg) { - sendMessage(msg, true); - } - - public synchronized void sendMessage(MQTTMessage msg, boolean mustBeConnected) { - if (DEBUG) - Log.d(TAG, "Sending message: " + MQTTHelper.decodePackageName(msg)); - - if (mustBeConnected) { - if (getState() == STATE_CONNECTED) { - new WriterTask().execute(msg); - } else { - if (DEBUG) - Log.d(TAG, "Need to be connected to send " + MQTTHelper.decodePackageName(msg)); + /** + * Publish a retained message to a specified topic. + * + * @param topic the topic + * @param message the message + * @param qos the desired quality of service + */ + public void publishRetain(String topic, String message, byte qos) { + publishRetain(topic, message.getBytes(), qos); + } - // If we lost the connection, and reconnect is set, let's try to reconnect now! - if (doAutomaticReconnect) - reconnect(); - } - } else { - new WriterTask().execute(msg); + /** + * Publish a retained message to a specified topic. + * + * @param topic the topic + * @param payload the message to publish + * @param qos the desired quality of service + */ + public void publishRetain(String topic, byte[] payload, byte qos) { + MQTTPublish publish = MQTTPublish.newInstance(topic, payload, qos); + publish.setRetain(true); + sendMessage(publish); } + /** + * Subscribe to a topic with Quality of Service (QoS) level + * {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE} + * + * @param topic Topic to subscribe to + */ + public void subscribe(String topic) { + String[] topics = {topic}; + subscribe(topics); + } + + /** + * Subscribe to multiple topics with quality of service + * {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE} + * + * @param topics Topics to subscribe to + */ + public void subscribe(String[] topics) { + byte[] qoss = new byte[topics.length]; + for (int i = 0; i < qoss.length; i++) + qoss[i] = AT_MOST_ONCE; + subscribe(topics, qoss); + } + + /** + * Subscribe to a topic + * + * @param topic Topic to subscribe to + * @param qos Quality of service, can be {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE}, + * {@link se.wetcat.qatja.MQTTConstants#AT_LEAST_ONCE}, or + * {@link se.wetcat.qatja.MQTTConstants#EXACTLY_ONCE}. + */ + public void subscribe(String topic, byte qos) { + String[] topics = {topic}; + byte[] qoss = {qos}; + subscribe(topics, qoss); + } + + /** + * Subscribe to multiple topics + * + * @param topics Topic to subscribe to + * @param qoss Quality of service, can be {@link se.wetcat.qatja.MQTTConstants#AT_MOST_ONCE}, + * {@link se.wetcat.qatja.MQTTConstants#AT_LEAST_ONCE}, or + * {@link se.wetcat.qatja.MQTTConstants#EXACTLY_ONCE}. + */ + public void subscribe(String[] topics, byte[] qoss) { + // Ensure the subscribedTopics isn't null + if (subscribedTopics == null) + subscribedTopics = new HashSet<>(); + + for (int i = 0; i < topics.length; i++) { + HashSet newTopics = new HashSet<>(); + + if (!subscribedTopics.contains(topics[i])) { + newTopics.add(topics[i]); + } + topics = newTopics.toArray(new String[0]); + } + + if (topics.length == 0) { + return; + } + + int id = mMqttIdentifierHelper.getIdentifier(); + + MQTTSubscribe subscribe = MQTTSubscribe.newInstance(topics, qoss, id); + sendMessage(subscribe); + + subscribedTopics.addAll(Arrays.asList(topics)); + + mMqttIdentifierHelper.addSentPackage(subscribe); + } + + // public synchronized void start() { + // if (DEBUG) + // Log.d(TAG, "start"); + // + // // Cancel any thread attempting to make a connection + // if (mConnectThread != null) { + // mConnectThread.cancel(); + // mConnectThread = null; + // } + // + // // Cancel any thread currently running a connection + // if (mConnectedThread != null) { + // mConnectedThread.cancel(); + // mConnectedThread = null; + // } + // + // setState(STATE_NONE); + // + // // if (host != null) + // // connect(host, port); + // } + + public synchronized void sendMessage(MQTTMessage msg) { + sendMessage(msg, true); + } + + public synchronized void sendMessage(MQTTMessage msg, boolean mustBeConnected) { + if (DEBUG) + Log.d(TAG, "Sending message: " + MQTTHelper.decodePackageName(msg)); + + if (mustBeConnected) { + if (getState() == STATE_CONNECTED) { + new WriterTask().execute(msg); + } else { + if (DEBUG) + Log.d(TAG, "Need to be connected to send " + MQTTHelper.decodePackageName(msg)); + + // If we lost the connection, and reconnect is set, let's try to reconnect now! + if (doAutomaticReconnect) + reconnect(); + } + } else { + new WriterTask().execute(msg); + } + // if (mustBeConnected) { // if (getState() == STATE_CONNECTED) { @@ -513,761 +513,767 @@ public class QatjaService extends Service { // Log.e(TAG, "FAiled to send message " + MQTTHelper.decodePackageName(msg.getType()), e); // } // } - } - - public String[] getSubscribedTopics() { - if(subscribedTopics == null) { - return new String[]{}; } - return subscribedTopics.toArray(new String[0]); - } - - public void setSSLSocketFactory(SSLSocketFactory socketFactory) { - this.socketFactory = socketFactory; - } - - /** - * Set MQTT broker host, can be either a domain name or an ip address - * - * @param host the host - */ - public void setHost(String host) { - this.host = host; - } - - /** - * Set MQTT broker port - * - * @param port - */ - public void setPort(int port) { - this.port = port; - } - - /** - * Set client identifier - * - * @param clientIdentifier the identifier - */ - public void setIdentifier(String clientIdentifier) { - this.clientIdentifier = clientIdentifier; - } - - public void setUsername(String username) { this.mUsername = username; } - - public void setPassword(String password) { this.mPassword = password; } - - public void setProtocolName(String protocolName) { - this.protocolName = protocolName; - } - - /** - * Set clean session - * - * @param clean_session - */ - public void setCleanSession(boolean clean_session) { - this.cleanSession = clean_session; - } - - /** - * Set will - * - * @param topic the will topic - * @param message the will message - */ - public void setWill(String topic, String message) { - if (topic == null || message == null) { - willFlag = false; - } else { - willTopic = topic; - willMessage = message; - willFlag = true; - } - } - - /** - * Set automatic reconnect - * - * @param reconnect - */ - public void setReconnect(boolean reconnect) { - doAutomaticReconnect = reconnect; - } - - public void setReconnectDelay(long millis) { - mReconnectDelay = millis; - } - - /** - * Attempt to reconnect after {@link #mReconnectDelay} milliseconds - */ - public void reconnect() { - reconnectHandler.postDelayed(recoonectRunnable, mReconnectDelay); - } - - /** - * Attempt to reconnect after delay - * - * @param milliseconds the delay - */ - public void reconnect(long milliseconds) { - reconnectHandler.postDelayed(recoonectRunnable, milliseconds); - } - - /** - * This runnable will take care of sending a ping request, it will be automatically cancelled and - * rescheduled if another message was sent to the broker (as defined in MQTT spec 3.1.1 we're not - * required to send ping as long as another message has been sent within the specified period. - */ - private Runnable mPingSender = new Runnable() { - @Override - public void run() { - sendMessage(MQTTPingreq.newInstance()); - // Make sure to auto-queue the runnable again when the message has been sent. - mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + public String[] getSubscribedTopics() { + if (subscribedTopics == null) { + return new String[]{}; + } + return subscribedTopics.toArray(new String[0]); } - }; - - /** - * Start a connection attempt - */ - public synchronized void connect() { - if (DEBUG) - Log.d(TAG, "connect to: " + host); - - cleanUp(); - // Start the thread to connect with the given device - try { - mConnectThread = new ConnectThread(host, port); - mConnectThread.start(); + public void setSSLSocketFactory(SSLSocketFactory socketFactory) { + this.socketFactory = socketFactory; + } - setState(STATE_CONNECTING); - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); + /** + * Set MQTT broker host, can be either a domain name or an ip address + * + * @param host the host + */ + public void setHost(String host) { + this.host = host; + } - setState(STATE_CONNECTION_FAILED); + /** + * Set MQTT broker port + * + * @param port + */ + public void setPort(int port) { + this.port = port; } - } - - public synchronized void connect(boolean newSocket) { - if (DEBUG) - Log.d(TAG, "connect to: " + host); - if (newSocket) { - // Cancel any future ping requests - if (mKeepaliveHandler != null) { - mKeepaliveHandler.removeCallbacks(mPingSender); - mKeepaliveHandler = null; - } - - // Cancel any thread attempting to make a connection - if (getState() == STATE_CONNECTING) { - if (mConnectThread != null) { - mConnectThread.cancel(); - mConnectThread = null; - } - } - // Cancel any thread currently running a connection - if (mConnectedThread != null) { - mConnectedThread.cancel(); - mConnectedThread = null; - } + /** + * Set client identifier + * + * @param clientIdentifier the identifier + */ + public void setIdentifier(String clientIdentifier) { + this.clientIdentifier = clientIdentifier; + } - if(subscribedTopics != null) { - subscribedTopics.clear(); - } + public void setUsername(String username) { + this.mUsername = username; + } - // Start the thread to connect with the given device - try { - mConnectThread = new ConnectThread(host, port); - mConnectThread.start(); + public void setPassword(String password) { + this.mPassword = password; + } - setState(STATE_CONNECTING); - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); + public void setProtocolName(String protocolName) { + this.protocolName = protocolName; + } - setState(STATE_CONNECTION_FAILED); - } - } else { - setState(STATE_CONNECTING); + /** + * Set clean session + * + * @param clean_session + */ + public void setCleanSession(boolean clean_session) { + this.cleanSession = clean_session; + } - connect(clientIdentifier); + /** + * Set will + * + * @param topic the will topic + * @param message the will message + */ + public void setWill(String topic, String message) { + if (topic == null || message == null) { + willFlag = false; + } else { + willTopic = topic; + willMessage = message; + willFlag = true; + } } - } - - /** - * Service connected - * - * @param socket the connected socket - */ - private synchronized void connected(Socket socket) { - if (DEBUG) - Log.d(TAG, "connected, Socket Type:"); - - // Cancel any future ping requests - if (mKeepaliveHandler != null) { - mKeepaliveHandler.removeCallbacks(mPingSender); - mKeepaliveHandler = null; + + /** + * Set automatic reconnect + * + * @param reconnect + */ + public void setReconnect(boolean reconnect) { + doAutomaticReconnect = reconnect; } - // Cancel the thread that completed the connection - if (mConnectThread != null) { - mConnectThread.cancel(); - mConnectThread = null; + public void setReconnectDelay(long millis) { + mReconnectDelay = millis; } - // Cancel any thread currently running a connection - if (mConnectedThread != null) { - mConnectedThread.cancel(); - mConnectedThread = null; + /** + * Attempt to reconnect after {@link #mReconnectDelay} milliseconds + */ + public void reconnect() { + reconnectHandler.postDelayed(recoonectRunnable, mReconnectDelay); } - if(subscribedTopics != null) { - subscribedTopics.clear(); + /** + * Attempt to reconnect after delay + * + * @param milliseconds the delay + */ + public void reconnect(long milliseconds) { + reconnectHandler.postDelayed(recoonectRunnable, milliseconds); } - // Start the thread to manage the connection and perform transmissions - mConnectedThread = new ConnectedThread(socket); - mConnectedThread.start(); + /** + * This runnable will take care of sending a ping request, it will be automatically cancelled and + * rescheduled if another message was sent to the broker (as defined in MQTT spec 3.1.1 we're not + * required to send ping as long as another message has been sent within the specified period. + */ + private Runnable mPingSender = new Runnable() { + @Override + public void run() { + sendMessage(MQTTPingreq.newInstance()); - // Start the PINGREQ handler - mKeepaliveHandler = new Handler(getMainLooper()); - mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + // Make sure to auto-queue the runnable again when the message has been sent. + mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + } + }; - Log.d(TAG, "Sending connect message"); + /** + * Start a connection attempt + */ + public synchronized void connect() { + if (DEBUG) + Log.d(TAG, "connect to: " + host); - // Send the connect message - connect(clientIdentifier); + cleanUp(); - // setState(STATE_CONNECTED); - } + // Start the thread to connect with the given device + try { + mConnectThread = new ConnectThread(host, port); + mConnectThread.start(); - /** - * Indicate that the connection attempt failed and notify the UI Activity. - */ - private void connectionFailed(Exception e) { - if (DEBUG) - Log.d(TAG, "connectionFailed", e); + setState(STATE_CONNECTING); + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); - if(subscribedTopics != null) { - subscribedTopics.clear(); + setState(STATE_CONNECTION_FAILED); + } } - if (doAutomaticReconnect) - reconnect(); - - setState(STATE_CONNECTION_FAILED); - } + public synchronized void connect(boolean newSocket) { + if (DEBUG) + Log.d(TAG, "connect to: " + host); + if (newSocket) { + // Cancel any future ping requests + if (mKeepaliveHandler != null) { + mKeepaliveHandler.removeCallbacks(mPingSender); + mKeepaliveHandler = null; + } - /** - * Indicate that the connection was lost and notify the UI Activity. - */ - private void connectionLost() { - if (DEBUG) - Log.d(TAG, "connectionLost"); + // Cancel any thread attempting to make a connection + if (getState() == STATE_CONNECTING) { + if (mConnectThread != null) { + mConnectThread.cancel(); + mConnectThread = null; + } + } - cleanUp(); + // Cancel any thread currently running a connection + if (mConnectedThread != null) { + mConnectedThread.cancel(); + mConnectedThread = null; + } - setState(STATE_NONE); + if (subscribedTopics != null) { + subscribedTopics.clear(); + } - if (doAutomaticReconnect) - reconnect(); - } + // Start the thread to connect with the given device + try { + mConnectThread = new ConnectThread(host, port); + mConnectThread.start(); - /** - * Disconnect the MQTT service - */ - public void disconnect() { - if (mState == STATE_CONNECTED) { - sendMessage(MQTTDisconnect.newInstance()); - } - } - - /** - * Clean up the connection handling. - */ - private void cleanUp() { - if (DEBUG) { - Log.d(TAG, "cleanUp()"); - } + setState(STATE_CONNECTING); + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); - // Cancel any future ping requests - try { - if (mKeepaliveHandler != null) { - mKeepaliveHandler.removeCallbacks(mPingSender); - mKeepaliveHandler = null; - } - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); - } + setState(STATE_CONNECTION_FAILED); + } + } else { + setState(STATE_CONNECTING); - // Cancel the thread that completed the connection - if (mConnectThread != null) { - mConnectThread.cancel(); - mConnectThread = null; + connect(clientIdentifier); + } } - // Cancel any thread currently running a connection - if (mConnectedThread != null) { - mConnectedThread.cancel(); - mConnectedThread = null; - } + /** + * Service connected + * + * @param socket the connected socket + */ + private synchronized void connected(Socket socket) { + if (DEBUG) + Log.d(TAG, "connected, Socket Type:"); - try { - if (subscribedTopics != null) { - subscribedTopics.clear(); - } - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); - } - } + // Cancel any future ping requests + if (mKeepaliveHandler != null) { + mKeepaliveHandler.removeCallbacks(mPingSender); + mKeepaliveHandler = null; + } - /** - * Set the connection state - * - * @param state the state - */ - private synchronized void setState(int state) { - if (DEBUG) - Log.d(TAG, "setState() " + mState + " -> " + state); + // Cancel the thread that completed the connection + if (mConnectThread != null) { + mConnectThread.cancel(); + mConnectThread = null; + } - if (mState != state) { - mState = state; + // Cancel any thread currently running a connection + if (mConnectedThread != null) { + mConnectedThread.cancel(); + mConnectedThread = null; + } - if (mHandler != null) { - if (mStateListener != null) { - mStateListener.onStateChanged(state); + if (subscribedTopics != null) { + subscribedTopics.clear(); } - // Give the new state to the Handler so the UI Activity can - // update - mHandler.obtainMessage(STATE_CHANGE, state, -1).sendToTarget(); - } + // Start the thread to manage the connection and perform transmissions + mConnectedThread = new ConnectedThread(socket); + mConnectedThread.start(); + + // Start the PINGREQ handler + mKeepaliveHandler = new Handler(getMainLooper()); + mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + + Log.d(TAG, "Sending connect message"); + + // Send the connect message + connect(clientIdentifier); + + // setState(STATE_CONNECTED); } - } - - /** - * Get the connection state - * - * @return the state - */ - public synchronized int getState() { - return mState; - } - - /** - * Set keep alive timer in milliseconds - * - * @param milliseconds the time - */ - public void setKeepAlive(int milliseconds) { - KEEP_ALIVE_TIMER = milliseconds; - } - - /** - * Make sure to resend packages that haven't been successfully sent. - */ - private synchronized void resendPackages() { - for (MQTTMessage msg : mMqttIdentifierHelper.getSentPackages().values()) { - if (msg instanceof MQTTPublish) { - ((MQTTPublish) msg).setDup(); - } - sendMessage(msg); + + /** + * Indicate that the connection attempt failed and notify the UI Activity. + */ + private void connectionFailed(Exception e) { + if (DEBUG) + Log.d(TAG, "connectionFailed", e); + + if (subscribedTopics != null) { + subscribedTopics.clear(); + } + + if (doAutomaticReconnect) + reconnect(); + + setState(STATE_CONNECTION_FAILED); } - for (MQTTMessage msg : mMqttIdentifierHelper.getReceivedPackages().values()) { - if (msg instanceof MQTTPublish) { - ((MQTTPublish) msg).setDup(); - } - sendMessage(msg); + /** + * Indicate that the connection was lost and notify the UI Activity. + */ + private void connectionLost() { + if (DEBUG) + Log.d(TAG, "connectionLost"); + + cleanUp(); + + setState(STATE_NONE); + + if (doAutomaticReconnect) + reconnect(); } - } - private synchronized void handlePubmesage(MQTTPuback msg) { - - Log.d(TAG, "Success handlePubmesage to " + new String(msg.getPayload())); - } - /** - * Manages subscription messages - * - * @param msg the message to handle - */ - private synchronized void handleSubscriptions(MQTTMessage msg) { - if (msg instanceof MQTTSuback) { - MQTTSuback suback = (MQTTSuback) msg; - - MQTTSubscribe subscribe = (MQTTSubscribe) mMqttIdentifierHelper.getSentPackages().get(suback.getPackageIdentifier()); - - String[] topicFilters = subscribe.getTopicFilters(); - byte[] qoss = suback.getPayload(); - for (int i = 0; i < qoss.length; i++) { - switch (qoss[i]) { - case SUBSCRIBE_SUCCESS_AT_MOST_ONCE: - case SUBSCRIBE_SUCCESS_AT_LEAST_ONCE: - case SUBSCRIBE_SUCCESS_EXACTLY_ONCE: - Log.d(TAG, "Success subscribing to " + topicFilters[i]); - break; - - case SUBSCRIBE_FAILURE: - Log.d(TAG, "Failed subscribing to " + topicFilters[i]); - break; + + /** + * Disconnect the MQTT service + */ + public void disconnect() { + if (mState == STATE_CONNECTED) { + sendMessage(MQTTDisconnect.newInstance()); } - } - } else if (msg instanceof MQTTUnsuback) { - MQTTUnsuback unsuback = (MQTTUnsuback) msg; - - MQTTUnsubscribe unsubscribe = (MQTTUnsubscribe) mMqttIdentifierHelper.getSentPackages().get(unsuback.getPackageIdentifier()); - String[] topicFilters = unsubscribe.getTopicFilters(); - for (int i = 0; i < topicFilters.length; i++) { - Log.d(TAG, "Success unsubscribing to " + topicFilters[i]); - } } - mHandler.obtainMessage(msg.getType(), -1, -1, msg).sendToTarget(); - } + /** + * Clean up the connection handling. + */ + private void cleanUp() { + if (DEBUG) { + Log.d(TAG, "cleanUp()"); + } + + // Cancel any future ping requests + try { + if (mKeepaliveHandler != null) { + mKeepaliveHandler.removeCallbacks(mPingSender); + mKeepaliveHandler = null; + } + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); + } + + // Cancel the thread that completed the connection + if (mConnectThread != null) { + mConnectThread.cancel(); + mConnectThread = null; + } - private class ConnectThread extends Thread { - private static final String TAG = "ConnectThread"; + // Cancel any thread currently running a connection + if (mConnectedThread != null) { + mConnectedThread.cancel(); + mConnectedThread = null; + } - private final Socket mmSocket; + try { + if (subscribedTopics != null) { + subscribedTopics.clear(); + } + } catch (Exception e) { + Log.e(TAG, e.getMessage(), e); + } + } /** - * Timeout of connection attempts (ms) + * Set the connection state + * + * @param state the state */ - private int timeout = 3000; + private synchronized void setState(int state) { + if (DEBUG) + Log.d(TAG, "setState() " + mState + " -> " + state); - private InetSocketAddress remoteAddr; + if (mState != state) { + mState = state; - ConnectThread(String host, int port) throws IOException { - if (DEBUG) - Log.d(TAG, "CREATE mConnectThread "); + if (mHandler != null) { + if (mStateListener != null) { + mStateListener.onStateChanged(state); + } - if (socketFactory != null) { - mmSocket = socketFactory.createSocket(); - } else { - mmSocket = new Socket(); - } + // Give the new state to the Handler so the UI Activity can + // update + mHandler.obtainMessage(STATE_CHANGE, state, -1).sendToTarget(); + } + } } - public void run() { - if (DEBUG) - Log.d(TAG, "BEGIN mConnectThread"); + /** + * Get the connection state + * + * @return the state + */ + public synchronized int getState() { + return mState; + } - setName("ConnectThread"); + /** + * Set keep alive timer in milliseconds + * + * @param milliseconds the time + */ + public void setKeepAlive(int milliseconds) { + KEEP_ALIVE_TIMER = milliseconds; + } - remoteAddr = new InetSocketAddress(host, port); + /** + * Make sure to resend packages that haven't been successfully sent. + */ + private synchronized void resendPackages() { + for (MQTTMessage msg : mMqttIdentifierHelper.getSentPackages().values()) { + if (msg instanceof MQTTPublish) { + ((MQTTPublish) msg).setDup(); + } + sendMessage(msg); + } - // Make a connection to the Socket - try { - // This is a blocking call and will only return on a successful connection or an exception - mmSocket.connect(remoteAddr, timeout); - } catch (IOException e) { - // Close the socket - try { - mmSocket.close(); - } catch (IOException e2) { - Log.e(TAG, - "unable to close() socket during connection failure", - e2); + for (MQTTMessage msg : mMqttIdentifierHelper.getReceivedPackages().values()) { + if (msg instanceof MQTTPublish) { + ((MQTTPublish) msg).setDup(); + } + sendMessage(msg); } - connectionFailed(e); - return; - } + } - // Reset the ConnectThread because we're done - synchronized (this) { - mConnectThread = null; - } + private synchronized void handlePubmesage(MQTTPuback msg) { - // Start the connected thread - connected(mmSocket); + Log.d(TAG, "Success handlePubmesage to " + new String(msg.getPayload())); } - public void cancel() { - try { - mmSocket.close(); - } catch (IOException e) { - Log.e(TAG, "close() of connect socket failed", e); - } - } - } - - /** - * This thread runs during a connection with a remote device. It handles all incoming and outgoing - * transmissions. - */ - private class ConnectedThread extends Thread { - private final Socket mmSocket; - private final InputStream mmInStream; - private final OutputStream mmOutStream; - - public ConnectedThread(Socket socket) { - if (DEBUG) - Log.d(TAG, "CREATE mConnectedThread"); - - mmSocket = socket; - InputStream tmpIn = null; - OutputStream tmpOut = null; - - // Get the Socket input and output streams - try { - tmpIn = socket.getInputStream(); - tmpOut = socket.getOutputStream(); - } catch (IOException e) { - Log.e(TAG, "temp sockets not created", e); - } - - mmInStream = tmpIn; - mmOutStream = tmpOut; - - if (DEBUG) - Log.d(TAG, "BEGIN mConnectedThread"); + /** + * Manages subscription messages + * + * @param msg the message to handle + */ + private synchronized void handleSubscriptions(MQTTMessage msg) { + if (msg instanceof MQTTSuback) { + MQTTSuback suback = (MQTTSuback) msg; + + MQTTSubscribe subscribe = (MQTTSubscribe) mMqttIdentifierHelper.getSentPackages().get(suback.getPackageIdentifier()); + + String[] topicFilters = subscribe.getTopicFilters(); + byte[] qoss = suback.getPayload(); + for (int i = 0; i < qoss.length; i++) { + switch (qoss[i]) { + case SUBSCRIBE_SUCCESS_AT_MOST_ONCE: + case SUBSCRIBE_SUCCESS_AT_LEAST_ONCE: + case SUBSCRIBE_SUCCESS_EXACTLY_ONCE: + Log.d(TAG, "Success subscribing to " + topicFilters[i]); + break; + + case SUBSCRIBE_FAILURE: + Log.d(TAG, "Failed subscribing to " + topicFilters[i]); + break; + } + } + } else if (msg instanceof MQTTUnsuback) { + MQTTUnsuback unsuback = (MQTTUnsuback) msg; + + MQTTUnsubscribe unsubscribe = (MQTTUnsubscribe) mMqttIdentifierHelper.getSentPackages().get(unsuback.getPackageIdentifier()); + String[] topicFilters = unsubscribe.getTopicFilters(); + for (int i = 0; i < topicFilters.length; i++) { + Log.d(TAG, "Success unsubscribing to " + topicFilters[i]); + } + } + + mHandler.obtainMessage(msg.getType(), -1, -1, msg).sendToTarget(); } - public void run() { - int len; - byte[] buffer = new byte[16384]; + private class ConnectThread extends Thread { + private static final String TAG = "ConnectThread"; - // Keep listening to the InputStream while connected - while (!isInterrupted()) { - try { - // Read from the InputStream - len = mmInStream.read(buffer); - - if (mHandler != null) - - if (len > 0) { - byte type = MQTTHelper.decodeType(buffer); - - if (DEBUG) - Log.d(TAG, "Received " + MQTTHelper.decodePackageName(type)); - - // Handle automatic responses here - switch (type) { - case CONNECT: - // Client should never receive CONNECT message - break; - - case CONNACK: - MQTTConnack connack = MQTTConnack.fromBuffer(buffer); - - switch (connack.getReturnCode()) { - case CONNECTION_ACCEPTED: - if (DEBUG) - Log.d(TAG, "Connected"); - setState(STATE_CONNECTED); - break; - - case CONNECTION_REFUSED_VERSION: - if (DEBUG) - Log.d(TAG, "Failed to connect, unaccebtable protocol version"); - setState(STATE_CONNECTION_FAILED); - break; - - case CONNECTION_REFUSED_IDENTIFIER: - if (DEBUG) - Log.d(TAG, "Failed to connect, identifier rejected"); - setState(STATE_CONNECTION_FAILED); - break; - - case CONNECTION_REFUSED_SERVER: - if (DEBUG) - Log.d(TAG, "Failed to connect, server unavailable"); - setState(STATE_CONNECTION_FAILED); - break; - - case CONNECTION_REFUSED_USER: - if (DEBUG) - Log.d(TAG, "Failed to connect, bad username or password"); - setState(STATE_CONNECTION_FAILED); - break; - - case CONNECTION_REFUSED_AUTH: - if (DEBUG) - Log.d(TAG, "Failed to connect, not authorized"); - setState(STATE_CONNECTION_FAILED); - break; - } - break; - - case PUBLISH: - MQTTPublish publish = MQTTPublish.fromBuffer(buffer); - switch (publish.getQoS()) { - case AT_MOST_ONCE: - // Do nothing - break; - - case AT_LEAST_ONCE: - // Send PUBACK - MQTTPuback puback_ = MQTTPuback.newInstance(publish.getPackageIdentifier()); - sendMessage(puback_); - break; - - case EXACTLY_ONCE: - // Send PUBREC and store message - MQTTPubrec pubrec_ = MQTTPubrec.newInstance(publish.getPackageIdentifier()); - mMqttIdentifierHelper.addReceivedPackage(pubrec_); - sendMessage(pubrec_); - - mMqttIdentifierHelper.addSentPackage(pubrec_); - break; - } - mHandler.obtainMessage(PUBLISH, mState, -1, publish).sendToTarget(); - break; - - case PUBACK: - MQTTPuback puback = MQTTPuback.fromBuffer(buffer); - mMqttIdentifierHelper.removeSentPackage(puback); - handlePubmesage(puback); - break; - - case PUBREC: - MQTTPubrec pubrec = MQTTPubrec.fromBuffer(buffer); - int packageIdentifier = pubrec.getPackageIdentifier(); - mMqttIdentifierHelper.removeSentPackage(pubrec); - - MQTTPubrel pubrel_ = MQTTPubrel.newInstance(packageIdentifier); - sendMessage(pubrel_); - break; - - case PUBREL: - MQTTPubrel pubrel = MQTTPubrel.fromBuffer(buffer); - mMqttIdentifierHelper.removeReceivedPackage(pubrel); - - MQTTPubcomp pubcomp_ = MQTTPubcomp.newInstance(pubrel.getPackageIdentifier()); - sendMessage(pubcomp_); - break; - - case PUBCOMP: - MQTTPubcomp pubcomp = MQTTPubcomp.fromBuffer(buffer); - mMqttIdentifierHelper.removeReceivedPackage(pubcomp); - break; - - case SUBSCRIBE: - // Client doesn't receive this message - break; - - case SUBACK: - MQTTSuback suback = MQTTSuback.fromBuffer(buffer); - handleSubscriptions(suback); - break; - - case UNSUBSCRIBE: - // Client doesn't receive this message - break; - - case UNSUBACK: - MQTTUnsuback unsuback = MQTTUnsuback.fromBuffer(buffer); - handleSubscriptions(unsuback); - mMqttIdentifierHelper.removeSentPackage(unsuback); - break; - - case PINGREQ: - // Client doesn't receive this message - break; - - case PINGRESP: - lastPingResp = System.currentTimeMillis(); - break; - - case DISCONNECT: - // Client doesn't receive this message - break; - } + private final Socket mmSocket; + + /** + * Timeout of connection attempts (ms) + */ + private int timeout = 3000; + + private InetSocketAddress remoteAddr; + + ConnectThread(String host, int port) throws IOException { + if (DEBUG) + Log.d(TAG, "CREATE mConnectThread "); + + if (socketFactory != null) { + mmSocket = socketFactory.createSocket(); + } else { + mmSocket = new Socket(); } + } - } catch (IOException e) { - if (DEBUG) - Log.e(TAG, "disconnected (this is fine, expected almost)", e); + public void run() { + if (DEBUG) + Log.d(TAG, "BEGIN mConnectThread"); + + setName("ConnectThread"); + + remoteAddr = new InetSocketAddress(host, port); + + // Make a connection to the Socket + try { + // This is a blocking call and will only return on a successful connection or an exception + mmSocket.connect(remoteAddr, timeout); + } catch (IOException e) { + // Close the socket + try { + mmSocket.close(); + } catch (IOException e2) { + Log.e(TAG, + "unable to close() socket during connection failure", + e2); + } + connectionFailed(e); + return; + } - connectionLost(); + // Reset the ConnectThread because we're done + synchronized (this) { + mConnectThread = null; + } - break; + // Start the connected thread + connected(mmSocket); + } + + public void cancel() { + try { + mmSocket.close(); + } catch (IOException e) { + Log.e(TAG, "close() of connect socket failed", e); + } } - } } /** - * Write to the connected OutStream. - * - * @param buffer The bytes to write + * This thread runs during a connection with a remote device. It handles all incoming and outgoing + * transmissions. */ - public synchronized void write(byte[] buffer) { - try { - mmOutStream.write(buffer); - } catch (IOException e) { - Log.e(TAG, "Exception during write", e); - - // Just notify the client that the connection was lost! - connectionLost(); - } - } + private class ConnectedThread extends Thread { + private final Socket mmSocket; + private final InputStream mmInStream; + private final OutputStream mmOutStream; + + public ConnectedThread(Socket socket) { + if (DEBUG) + Log.d(TAG, "CREATE mConnectedThread"); + + mmSocket = socket; + InputStream tmpIn = null; + OutputStream tmpOut = null; + + // Get the Socket input and output streams + try { + tmpIn = socket.getInputStream(); + tmpOut = socket.getOutputStream(); + } catch (IOException e) { + Log.e(TAG, "temp sockets not created", e); + } - void cancel() { - new DisconnectTask().execute(mmInStream, mmOutStream, mmSocket); - } - } + mmInStream = tmpIn; + mmOutStream = tmpOut; - private static class DisconnectTask extends AsyncTask { - @Override - protected Void doInBackground(Closeable... closeables) { - if (DEBUG) { - Log.d(TAG, "[DisconnectTask] Closing streams and socket."); - } + if (DEBUG) + Log.d(TAG, "BEGIN mConnectedThread"); + } - for (Closeable closeable : closeables) { - try { - closeable.close(); - } catch (IOException e) { - Log.e(TAG, e.getMessage(), e); + public void run() { + int len; + byte[] buffer = new byte[16384]; + + // Keep listening to the InputStream while connected + while (!isInterrupted()) { + try { + // Read from the InputStream + len = mmInStream.read(buffer); + + if (mHandler != null) + + if (len > 0) { + byte type = MQTTHelper.decodeType(buffer); + + if (DEBUG) + Log.d(TAG, "Received " + MQTTHelper.decodePackageName(type)); + + // Handle automatic responses here + switch (type) { + case CONNECT: + // Client should never receive CONNECT message + break; + + case CONNACK: + MQTTConnack connack = MQTTConnack.fromBuffer(buffer); + + switch (connack.getReturnCode()) { + case CONNECTION_ACCEPTED: + if (DEBUG) + Log.d(TAG, "Connected"); + setState(STATE_CONNECTED); + break; + + case CONNECTION_REFUSED_VERSION: + if (DEBUG) + Log.d(TAG, "Failed to connect, unaccebtable protocol version"); + setState(STATE_CONNECTION_FAILED); + break; + + case CONNECTION_REFUSED_IDENTIFIER: + if (DEBUG) + Log.d(TAG, "Failed to connect, identifier rejected"); + setState(STATE_CONNECTION_FAILED); + break; + + case CONNECTION_REFUSED_SERVER: + if (DEBUG) + Log.d(TAG, "Failed to connect, server unavailable"); + setState(STATE_CONNECTION_FAILED); + break; + + case CONNECTION_REFUSED_USER: + if (DEBUG) + Log.d(TAG, "Failed to connect, bad username or password"); + setState(STATE_CONNECTION_FAILED); + break; + + case CONNECTION_REFUSED_AUTH: + if (DEBUG) + Log.d(TAG, "Failed to connect, not authorized"); + setState(STATE_CONNECTION_FAILED); + break; + } + break; + + case PUBLISH: + MQTTPublish publish = MQTTPublish.fromBuffer(buffer); + switch (publish.getQoS()) { + case AT_MOST_ONCE: + // Do nothing + break; + + case AT_LEAST_ONCE: + // Send PUBACK + MQTTPuback puback_ = MQTTPuback.newInstance(publish.getPackageIdentifier()); + sendMessage(puback_); + break; + + case EXACTLY_ONCE: + // Send PUBREC and store message + MQTTPubrec pubrec_ = MQTTPubrec.newInstance(publish.getPackageIdentifier()); + mMqttIdentifierHelper.addReceivedPackage(pubrec_); + sendMessage(pubrec_); + + mMqttIdentifierHelper.addSentPackage(pubrec_); + break; + } + mHandler.obtainMessage(PUBLISH, mState, -1, publish).sendToTarget(); + break; + + case PUBACK: + MQTTPuback puback = MQTTPuback.fromBuffer(buffer); + mMqttIdentifierHelper.removeSentPackage(puback); + handlePubmesage(puback); + break; + + case PUBREC: + MQTTPubrec pubrec = MQTTPubrec.fromBuffer(buffer); + int packageIdentifier = pubrec.getPackageIdentifier(); + mMqttIdentifierHelper.removeSentPackage(pubrec); + + MQTTPubrel pubrel_ = MQTTPubrel.newInstance(packageIdentifier); + sendMessage(pubrel_); + break; + + case PUBREL: + MQTTPubrel pubrel = MQTTPubrel.fromBuffer(buffer); + mMqttIdentifierHelper.removeReceivedPackage(pubrel); + + MQTTPubcomp pubcomp_ = MQTTPubcomp.newInstance(pubrel.getPackageIdentifier()); + sendMessage(pubcomp_); + break; + + case PUBCOMP: + MQTTPubcomp pubcomp = MQTTPubcomp.fromBuffer(buffer); + mMqttIdentifierHelper.removeReceivedPackage(pubcomp); + break; + + case SUBSCRIBE: + // Client doesn't receive this message + break; + + case SUBACK: + MQTTSuback suback = MQTTSuback.fromBuffer(buffer); + handleSubscriptions(suback); + break; + + case UNSUBSCRIBE: + // Client doesn't receive this message + break; + + case UNSUBACK: + MQTTUnsuback unsuback = MQTTUnsuback.fromBuffer(buffer); + handleSubscriptions(unsuback); + mMqttIdentifierHelper.removeSentPackage(unsuback); + break; + + case PINGREQ: + // Client doesn't receive this message + break; + + case PINGRESP: + lastPingResp = System.currentTimeMillis(); + break; + + case DISCONNECT: + // Client doesn't receive this message + break; + } + } + + } catch (IOException e) { + if (DEBUG) + Log.e(TAG, "disconnected (this is fine, expected almost)", e); + + connectionLost(); + + break; + } + } } - } - return null; + /** + * Write to the connected OutStream. + * + * @param buffer The bytes to write + */ + public synchronized void write(byte[] buffer) { + try { + mmOutStream.write(buffer); + } catch (IOException e) { + Log.e(TAG, "Exception during write", e); + + // Just notify the client that the connection was lost! + connectionLost(); + } + } + + void cancel() { + new DisconnectTask().execute(mmInStream, mmOutStream, mmSocket); + } } - } - private class WriterTask extends AsyncTask { + private static class DisconnectTask extends AsyncTask { + @Override + protected Void doInBackground(Closeable... closeables) { + if (DEBUG) { + Log.d(TAG, "[DisconnectTask] Closing streams and socket."); + } - @Override - protected MQTTMessage doInBackground(MQTTMessage... params) { - if (params.length == 0) - return null; - - try { - mConnectedThread.write(params[0].get()); - return params[0]; - } catch (MQTTException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (NullPointerException e) { - e.printStackTrace(); - } - - return null; + for (Closeable closeable : closeables) { + try { + closeable.close(); + } catch (IOException e) { + Log.e(TAG, e.getMessage(), e); + } + } + + return null; + } } - @Override - protected void onPostExecute(MQTTMessage sent) { - super.onPostExecute(sent); + private class WriterTask extends AsyncTask { + + @Override + protected MQTTMessage doInBackground(MQTTMessage... params) { + if (params.length == 0) + return null; + + try { + mConnectedThread.write(params[0].get()); + return params[0]; + } catch (MQTTException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (NullPointerException e) { + e.printStackTrace(); + } - if (!isCancelled()) { - if (sent != null) { - lastSentMessage = System.currentTimeMillis(); + return null; + } - try { - if (mKeepaliveHandler != null) { - mKeepaliveHandler.removeCallbacks(mPingSender); - mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + @Override + protected void onPostExecute(MQTTMessage sent) { + super.onPostExecute(sent); + + if (!isCancelled()) { + if (sent != null) { + lastSentMessage = System.currentTimeMillis(); + + try { + if (mKeepaliveHandler != null) { + mKeepaliveHandler.removeCallbacks(mPingSender); + mKeepaliveHandler.postDelayed(mPingSender, KEEP_ALIVE_TIMER); + } + } catch (Exception ex) { + Log.e(TAG, ex.getMessage(), ex); + } + } } - } catch (Exception ex) { - Log.e(TAG, ex.getMessage(), ex); - } } - } } - } } diff --git a/app/version_code.properties b/app/version_code.properties index 35c16324..04a726ec 100644 --- a/app/version_code.properties +++ b/app/version_code.properties @@ -1,2 +1,2 @@ -#Sat Sep 05 16:21:32 CST 2020 -VERSION_CODE=516 +#Thu Dec 10 14:55:18 CST 2020 +VERSION_CODE=517