package com.safemobile.safedispatch; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.text.Editable; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.safemobile.adapters.LanguageSpinnerAdapter; import com.safemobile.interfaces.ITCPListener; import com.safemobile.interfaces.TCPEvent; import com.safemobile.lib.AppParams; import com.safemobile.lib.AppParams.ActivityResult; import com.safemobile.lib.Contact; import com.safemobile.lib.LoginMSG; import com.safemobile.lib.Radio; import com.safemobile.lib.SM; import com.safemobile.lib.TCPmsg; import com.safemobile.lib.User; import com.safemobile.lib.radio.Channel; import com.safemobile.lib.radio.Emerg; import com.safemobile.lib.radio.IncCall; import com.safemobile.lib.radio.RadioStatus; import com.safemobile.libpad.PadRecording; import com.safemobile.libpad.PadTextMessage; import com.safemobile.services.TCPService; import com.safemobile.services.TCPService.TCPBinder; import com.safemobile.services.TCPhandler; import com.safemobile.services.TCPmsgParser; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; public class SDMobileActivity extends Activity { /* Visual Elements */ private Button btLogin; private EditText etPassword; private EditText etUsername; private CheckBox checkBoxSaveDefault; private RelativeLayout layoutTCP; private LinearLayout llUsername; private LinearLayout llPassword; private ImageView imageLanguage; /* Preferences */ private SharedPreferences.Editor editor; /* Misc */ private String[] languages = {"English", "German", "Turkish", "Romanian", "Russian", "Spanish"}; private Context context; private Activity activity; private Dialog loadingDialog; /* Handler for callbacks to the UI thread */ private final Handler uiHandler = new Handler(Looper.getMainLooper()); /* TCP */ protected TCPhandler tcp; protected TCPmsgParser tcpParser; protected ITCPListener itcpListener; protected Timer timerLogin;//timer to check connection!!! /** * TCP Service */ private TCPService myService; private boolean isBound = false; /* User details */ protected int userID;// ID of logged in user private Boolean prevTCPState = false; /* Constants */ private static final String DATABASE_LANGUAGE = "en"; // database language : en, de, tr, ro or empty private static final String LANGUAGE = "language"; private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private static final String LOGIN = "login"; private static final String DEFAULT = "default"; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SM.Debug("##### onCREATE ##### with LANGUAGE " + AppParams.LANGUAGETMP); AppParams.theme = AppParams.Theme.SAFEDISPATCH; if (AppParams.theme == AppParams.Theme.SAFENET) this.setTheme(R.style.Theme_Safenet); else if (AppParams.theme == AppParams.Theme.VISION) this.setTheme(R.style.Theme_Vision); else if (AppParams.theme == AppParams.Theme.HYTERA) this.setTheme(R.style.Theme_Hytera); else this.setTheme(R.style.AppTheme); // get Context context = this; activity = this; // get settings loadSettings(); // if package is demo set DEMO to true AppParams.DEMO = (context.getPackageName().contains("demo")); if (savedInstanceState != null && savedInstanceState.getString(LANGUAGE) != null) // set language which will be used for displaying UI AppParams.LANGUAGETMP = savedInstanceState.getString(LANGUAGE); else AppParams.LANGUAGETMP = AppParams.LANGUAGE; Locale locale = new Locale(AppParams.LANGUAGETMP); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); languages = new String[]{getString(R.string.en), getString(R.string.de), getString(R.string.tr), getString(R.string.ro), getString(R.string.ru), getString(R.string.es)}; setContentView(R.layout.login_h); // do not dim the display getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // hide keyboard when opening app getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); checkBoxSaveDefault = (CheckBox) findViewById(R.id.checkBoxSaveDefault); // if username and password not equal N/A => save as default was checked if (!AppParams.USERNAME.equals("n/a") && !AppParams.PASSWORD.equals("n/a")) checkBoxSaveDefault.setChecked(true); ImageView imageLoading = (ImageView) findViewById(R.id.imageLoading); imageLoading.setBackgroundResource(R.drawable.loading); imageLanguage = (ImageView) findViewById(R.id.imageLanguage); // change spinner icon and selected language according to tmpLanguage switch (AppParams.LANGUAGETMP) { case "en": imageLanguage.setImageResource(R.drawable.en); break; case "de": imageLanguage.setImageResource(R.drawable.de); break; case "tr": imageLanguage.setImageResource(R.drawable.tr); break; case "ro": imageLanguage.setImageResource(R.drawable.ro); break; case "es": imageLanguage.setImageResource(R.drawable.es); break; case "ru": imageLanguage.setImageResource(R.drawable.ru); break; default: throw new IllegalStateException("Unexpected value: " + AppParams.LANGUAGETMP); } imageLanguage.setOnClickListener(LanguageListener); etUsername = (EditText) findViewById(R.id.etUsername); etPassword = (EditText) findViewById(R.id.etPassword); btLogin = (Button) findViewById(R.id.btLogin); btLogin.setOnClickListener(arg0 -> { if (AppParams.DEMO) startTabActivity(0); else { if (etPassword.getText().toString().length() < 1 || etUsername.getText().toString().length() < 1) showInfoDialog(getResources().getString(R.string.password)); else { // if save username and password // reset username and password saveSettings(checkBoxSaveDefault.isChecked()); // save settings if (!loadingDialog.isShowing()) loadingDialog.show(); // TODO get users list new connectTask().execute(LOGIN); } } }); ImageView imageSettings = (ImageView) findViewById(R.id.imageSettings); imageSettings.setOnClickListener(changeIPListener); // reset values before changing language if (savedInstanceState != null && savedInstanceState.getString(USERNAME) != null) { etUsername.setText(savedInstanceState.getString(USERNAME)); etPassword.setText(savedInstanceState.getString(PASSWORD)); checkBoxSaveDefault.setChecked(savedInstanceState.getBoolean("checked")); } else { // set values stored in Shared Preferences etUsername.setText(AppParams.USERNAME.equalsIgnoreCase("n/a") ? "" : AppParams.USERNAME); etPassword.setText(AppParams.PASSWORD.equalsIgnoreCase("n/a") ? "" : AppParams.PASSWORD); } layoutTCP = (RelativeLayout) findViewById(R.id.layoutTCP); llUsername = (LinearLayout) findViewById(R.id.llUsername); llPassword = (LinearLayout) findViewById(R.id.llPassword); // enable ui after the language is changed and tcp connection is on if (tcp != null && tcp.isConnectionUP) { layoutTCP.setVisibility(View.INVISIBLE); enableUI(true); } // enable UI if application is demo else if (AppParams.DEMO) { enableUI(true); layoutTCP.setVisibility(View.INVISIBLE); } else enableUI(false); if (!AppParams.DEMO) { /** Create Service and bind on it */ getApplicationContext().bindService(new Intent(this, TCPService.class), serviceConnection, Context.BIND_AUTO_CREATE); } createLoadingDialog(getString(R.string.checkingUser)); timerLogin = new Timer(); timerLogin.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // request to trigger the event because the first time when // it was triggered, the listener wasn't created if (tcp != null) { tcp.triggerTCPConnectionStateEvent(); } } }, 1000, 500); } /* Enable and disable UI elements */ private void enableUI(boolean isEnabled) { checkBoxSaveDefault.setEnabled(isEnabled); btLogin.setEnabled(isEnabled); etPassword.setEnabled(isEnabled); etUsername.setEnabled(isEnabled); // change username and password layout background to gray or white if (isEnabled) { llUsername.setBackgroundResource(R.drawable.textboxx); llPassword.setBackgroundResource(R.drawable.textboxx); } else { llUsername.setBackgroundResource(R.drawable.textboxx); llPassword.setBackgroundResource(R.drawable.textboxx); } } @Override public void onBackPressed() { if (loadingDialog.isShowing()) cancelLoadingDialog(); else { // show dialog that allows to select the close of the app AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.exit)) .setCancelable(false) .setPositiveButton(getString(R.string.yes), (dialog, id) -> whenBackPressed()) .setNegativeButton(getString(R.string.no), (dialog, id) -> dialog.cancel()); AlertDialog alert = builder.create(); alert.show(); } } /* Callback for connecting/disconnecting from the service that controls TCP Connections */ ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Toast.makeText(context, getString(R.string.serviceDisconnected), Toast.LENGTH_SHORT).show(); isBound = false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { TCPBinder binder = (TCPBinder) service; myService = binder.getService(); isBound = true; } }; @Override public void onStop() { super.onStop(); SM.Debug("##### onSTOP #####"); // Unbind from the service if (isBound) { getApplicationContext().unbindService(serviceConnection); isBound = false; } } @Override public void onStart() { super.onStart(); SM.Debug("##### onSTART #####"); if (AppParams.DEMO) { etPassword.setText("demo"); etUsername.setText("demo"); } if (loadingDialog != null) loadingDialog.cancel(); // get Users only if IP and PORT are completed if (tcp == null && !AppParams.IP.equals("n/a") && !AppParams.PORT.equals("n/a") && !AppParams.DEMO) { new Thread(() -> { try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } uiHandler.post(initTCPRUN); }).start(); } } @Override // this will be called when the user selects logout or exit public void onActivityResult(int requestCode, int resultCode, Intent intent) { final String TAG = "### RESULT ###"; if (requestCode == 0 && resultCode == RESULT_OK) { ActivityResult result = (ActivityResult) intent.getSerializableExtra("result"); if (result == ActivityResult.logout) { SM.Debug(TAG, "LOGOUT"); updateUIwithTCPStatus(true); } else if (result == ActivityResult.restart) { // check tcp status and set UI if (myService != null) tcp = myService.getTCPConnection(); SM.Debug(TAG, "RESTART"); /* authenticate again if tcp is ok */ Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { uiHandler.post(() -> { if (tcp != null && tcp.isConnectionUP) { if (!loadingDialog.isShowing()) loadingDialog.show(); enableUI(true); layoutTCP.setVisibility(View.INVISIBLE); new connectTask().execute(LOGIN); } }); } }, 1000); } else if (result == ActivityResult.tcpDown) { SM.Debug(TAG, "TCP DOWN"); updateUIwithTCPStatus(false); } else if (result == ActivityResult.exit) { SM.Debug(TAG, "EXIT"); whenBackPressed(); } } resetAppLists(); } private void resetAppLists() { SM.Exception("################ RESET ##############"); AppParams.listContacts.clear(); AppParams.listRecordings.clear(); AppParams.hashTextMessagesByRadioID.clear(); AppParams.listZones.clear(); AppParams.crtAckedTextMessage = new PadTextMessage(); AppParams.crtChannel = new Channel(); AppParams.crtContact = new Contact(); AppParams.crtEmergencyState = new Emerg(); AppParams.crtIncCall = new IncCall(); AppParams.crtRadio = new Radio(); AppParams.crtRadioStatus = new RadioStatus(); AppParams.crtReceivedTextMessage = new PadTextMessage(); AppParams.crtRecording = new PadRecording(); AppParams.crtSentTextMessage = new PadTextMessage(); } private OnClickListener changeIPListener = new OnClickListener() { @Override public void onClick(View v) { // show dialog LinearLayout ll = new LinearLayout(context); ll.setOrientation(LinearLayout.HORIZONTAL); final EditText input = new EditText(activity); input.setSelectAllOnFocus(true); input.setText(AppParams.IP); input.setMinWidth(190); input.setHint(getString(R.string.hintIP)); input.setGravity(Gravity.CENTER); ll.addView(input, 0); final TextView tv = new TextView(context); tv.setText(":"); tv.setTextColor(Color.WHITE); ll.addView(tv, 1); final EditText inputPort = new EditText(activity); inputPort.setSelectAllOnFocus(true); inputPort.setText(AppParams.PORT); inputPort.setHint(getString(R.string.hintPort)); inputPort.setMinWidth(90); inputPort.setInputType(InputType.TYPE_CLASS_NUMBER); inputPort.setGravity(Gravity.CENTER); ll.addView(inputPort, 2); ll.setGravity(Gravity.CENTER); new AlertDialog.Builder(activity) .setTitle(getString(R.string.appServerIP)) .setMessage(getString(R.string.enterIPPort)) .setView(ll) .setPositiveButton(getString(R.string.ok), (dialog, whichButton) -> { Editable value = input.getText(); Editable valuePort = inputPort.getText(); try { if (Integer.parseInt(valuePort.toString()) > 0 && Integer.parseInt(valuePort.toString()) < 65535) saveIPandRestartTCP(value.toString(), valuePort.toString()); else Toast.makeText(context, getString(R.string.invalidPort), Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Toast.makeText(context, getString(R.string.invalidPort), Toast.LENGTH_SHORT).show(); } }).setNegativeButton(getString(R.string.cancel), (dialog, whichButton) -> { // close dialog dialog.dismiss(); // hide keyboard getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); }).show(); } }; private void whenBackPressed() { if (tcp != null) { tcp.Stop(); if (tcpParser != null) tcpParser.Stop(); } cancelTimerLogin(); try { getApplicationContext().unbindService(serviceConnection); } catch (IllegalArgumentException ignored) { //ignored } activity.finish(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); } // Create runnable for posting final Runnable initTCPRUN = () -> { // start thread to add listener SM.Debug("##### initTCPRUN"); if (!AppParams.DEMO) tcpInit(); }; @Override public void onPause() { super.onPause(); SM.Debug("##### onPAUSE #####"); } @Override public void onResume() { super.onResume(); SM.Debug("##### onRESUME #####"); } private void startTabActivity(long userID) { // good login - load activity Intent intent = new Intent(context, TabLayoutActivity.class); // send parameters intent.putExtra("userID", userID); intent.putExtra(USERNAME, etUsername.getText().toString()); intent.putExtra(PASSWORD, etPassword.getText().toString()); AppParams.USERNAME = etUsername.getText().toString(); AppParams.PASSWORD = etPassword.getText().toString(); AppParams.USERID = userID; if (!AppParams.DEMO && tcpParser != null && itcpListener != null) { // unregister tcpParser tcpParser.removeTCPListener(itcpListener); } // start activity startActivityForResult(intent, 0); } private void updateUIwithTCPStatus(boolean enable) { SM.Debug("UPDATE UI :" + enable); if (enable) layoutTCP.setVisibility(View.INVISIBLE); else layoutTCP.setVisibility(View.VISIBLE); enableUI(enable); } // cancel loading dialog and show sending error message private void cancelLoadingDialog() { // cancel loading dialog if (loadingDialog != null) loadingDialog.cancel(); } // this will cancel the timer that waits for the authenticating procedure to complete private void cancelTimerLogin() { if (timerLogin != null) { timerLogin.cancel(); timerLogin = null; } } // listener when select language pressed private final OnClickListener LanguageListener = new OnClickListener() { @Override public void onClick(View v) { final LanguageSpinnerAdapter adapter = new LanguageSpinnerAdapter(context, android.R.layout.simple_spinner_item, languages, getLayoutInflater()); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(getString(R.string.selLanguage)); builder.setAdapter(adapter, (dialog, which) -> { Bundle saved = new Bundle(); saved.putString(USERNAME, etUsername.getText().toString()); saved.putString(PASSWORD, etPassword.getText().toString()); saved.putBoolean("checked", checkBoxSaveDefault.isChecked()); switch (which) { case 0: imageLanguage.setImageResource(R.drawable.en); saved.putString(LANGUAGE, "en"); AppParams.LANGUAGETMP = "en"; AppParams.LANGUAGE = "en"; break; case 1: imageLanguage.setImageResource(R.drawable.de); saved.putString(LANGUAGE, "de"); AppParams.LANGUAGETMP = "de"; AppParams.LANGUAGE = "de"; break; case 2: imageLanguage.setImageResource(R.drawable.tr); saved.putString(LANGUAGE, "tr"); AppParams.LANGUAGETMP = "tr"; AppParams.LANGUAGE = "tr"; break; case 3: imageLanguage.setImageResource(R.drawable.ro); saved.putString(LANGUAGE, "ro"); AppParams.LANGUAGETMP = "ro"; AppParams.LANGUAGE = "ro"; break; case 4: imageLanguage.setImageResource(R.drawable.ru); saved.putString(LANGUAGE, "ru"); AppParams.LANGUAGETMP = "ru"; AppParams.LANGUAGE = "ru"; break; case 5: imageLanguage.setImageResource(R.drawable.es); saved.putString(LANGUAGE, "es"); AppParams.LANGUAGETMP = "es"; AppParams.LANGUAGE = "es"; break; default: throw new IllegalStateException("Unexpected value: " + which); } // recreate the activity onCreate(saved); }); AlertDialog alert = builder.create(); alert.show(); } }; private void tcpInit() { int port = 0; try { port = Integer.parseInt(AppParams.PORT); } catch (Exception ex) { SM.Debug("PORT is not an integer"); } //create TCP handle SM.Debug("new TCP on IP: " + AppParams.IP + " | PORT: " + port); // connect to the server new connectTask().execute("tcp"); new connectParserTask().execute(""); } // load settings public void loadSettings() { try { // get Preferences for SafeDispatch AppParams.prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE); // get default language AppParams.LANGUAGE = AppParams.prefs.getString(LANGUAGE, DATABASE_LANGUAGE); // get default username AppParams.USERNAME = AppParams.prefs.getString(USERNAME, "n/a"); // get default password AppParams.PASSWORD = AppParams.prefs.getString(PASSWORD, "n/a"); // get default IP AppParams.IP = AppParams.prefs.getString("ip", "192.168.2.100"); // get Radio ID & IP AppParams.RADIOID = AppParams.prefs.getInt("radioId", 100); AppParams.RADIOIP = AppParams.prefs.getString("radioIp", "192.168.10.40"); // get default communication port AppParams.PORT = AppParams.prefs.getString("port", "13589"); // get default value -> IP,PORT AppParams.DEFAULT = AppParams.prefs.getString(DEFAULT, "0#0"); // get default sound source value AppParams.SOURCE = AppParams.prefs.getString("source", "TCP"); SM.Debug("LOAD SETTINGS ### UserName: " + AppParams.USERNAME + " |Password: " + AppParams.PASSWORD + " |IP: " + AppParams.IP + " |PORT: " + AppParams.PORT + " | LANGUAGE: " + AppParams.LANGUAGE); } catch (Exception ex) { SM.Exception("Exception", "loadSettings exception"); } } public void saveSettings(boolean modify) { // get editor editor = AppParams.prefs.edit(); // put new values editor.putString(LANGUAGE, AppParams.LANGUAGETMP); editor.putString("languagetmp", AppParams.LANGUAGETMP); // save new username and password if (modify) { if (etUsername.getText().toString().length() > 0) editor.putString(USERNAME, etUsername.getText().toString()); else editor.putString(USERNAME, "n/a"); if (etPassword.getText().toString().length() > 0) editor.putString(PASSWORD, etPassword.getText().toString()); else editor.putString(PASSWORD, "n/a"); // safe default -> ip#port editor.putString(DEFAULT, AppParams.IP + "#" + AppParams.PORT); } else // reset username and password { editor.putString(USERNAME, "n/a"); editor.putString(PASSWORD, "n/a"); editor.putString(DEFAULT, "0#0"); } AppParams.USERNAME = etUsername.getText().toString(); AppParams.PASSWORD = etPassword.getText().toString(); SM.Debug("SAVE SETTINGS ### UserName: " + AppParams.USERNAME + " |Password: " + AppParams.PASSWORD + " |IP: " + AppParams.IP + " |PORT: " + AppParams.PORT); editor.commit(); } public void createLoadingDialog(String message) { loadingDialog = new Dialog(context); loadingDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); loadingDialog.setContentView(R.layout.dialogloading); loadingDialog.setCancelable(true); loadingDialog.setCanceledOnTouchOutside(false); Button cancel = (Button) loadingDialog.findViewById(R.id.buttonCancel); cancel.setVisibility(View.GONE); TextView textView1 = (TextView) loadingDialog.findViewById(R.id.textView1); textView1.setText(message); } public void showInfoDialog(String message) { /* Dialog */ Dialog dialogInfo = new Dialog(context); dialogInfo.requestWindowFeature(Window.FEATURE_NO_TITLE); dialogInfo.setContentView(R.layout.dialog_login); TextView textTitle = dialogInfo.findViewById(R.id.textTitle); TextView text = dialogInfo.findViewById(R.id.text); TextView text2 = dialogInfo.findViewById(R.id.text2); ImageView image = dialogInfo.findViewById(R.id.image); textTitle.setText(getString(R.string.connectionError)); image.setImageResource(R.drawable.error); text.setText(getString(R.string.userPassError)); text2.setVisibility(View.GONE); dialogInfo.setCancelable(true); dialogInfo.setCanceledOnTouchOutside(true); try { dialogInfo.show(); } catch (Exception ex) { ex.toString(); } } public void showErrorDialog(String title, String errorMsg) { Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_login); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); TextView textTitle = (TextView) dialog.findViewById(R.id.textTitle); textTitle.setText(title); TextView text = (TextView) dialog.findViewById(R.id.text); TextView text2 = (TextView) dialog.findViewById(R.id.text2); text2.setVisibility(View.GONE); ImageView image = (ImageView) dialog.findViewById(R.id.image); image.setImageResource(R.drawable.error); text.setText(errorMsg); dialog.show(); } private void saveIPandRestartTCP(String myIP, String port) { // get IP if (myIP.length() > 1) AppParams.IP = myIP; // get Preferences for SafeDispatch // save net ip editor = AppParams.prefs.edit(); // put new values editor.putString("ip", AppParams.IP); // get PORT AppParams.PORT = port; if (AppParams.PORT.length() < 1) AppParams.PORT = "n/a"; // save port editor.putString("port", AppParams.PORT); editor.commit(); SM.Exception("TCP CHANGED WITH IP AND PORT " + myIP + " | " + port); // if port or IP changed if (!AppParams.DEMO) { if (tcp != null) { tcp.Stop(); if (tcpParser != null) tcpParser.clearMsgList(); tcp = null; } uiHandler.post(() -> { if (myService != null) { myService.stopTCPConnection(); myService.recreateTCPConnection(); uiHandler.post(initTCPRUN); } SM.Debug("RECREATE TCP", "IP: " + AppParams.IP + " | Port: " + AppParams.PORT); }); } } //tcp public boolean getUsers() { if (tcp == null) return false; if (Boolean.FALSE.equals(tcp.isConnectionUP)) return false; boolean res = tcp.Write("0.0", "#20#"); if (res) { SM.Debug("Message sent to app server"); } else { SM.Debug("Could not send message!!"); } return res; } public class connectTask extends AsyncTask { @Override protected TCPhandler doInBackground(String... params) { if (params[0].equals("tcp")) { if (myService != null) { tcp = myService.getTCPConnection(); } } else if (params[0].equals(LOGIN)) { getUsers(); // start a timer to display an error message if response isn't received timerLogin = new Timer(); timerLogin.schedule(new TimerTask() { @Override public void run() { uiHandler.post(() -> { loadingDialog.cancel(); showErrorDialog("Login Error", "Could not receive response for login. Check connectivity and try again"); }); } }, 10000); } return null; } } public class connectParserTask extends AsyncTask { @Override protected TCPhandler doInBackground(String... params) { if (myService != null) tcpParser = myService.getTCPmsgParser(); // add TCPParserListener if (tcpParser != null) { tcpParser.clearITCPListeners(); tcpParser.addTCPListener(itcpListener = new ITCPListener() { @Override public void onLoginReceived(TCPEvent event) { SM.Debug("LoginReceived", "LoginReceived"); TCPmsg msg = event.msg(); LoginMSG lMSG = new LoginMSG(msg); SM.Debug("userList:" + lMSG.userList.size()); for (User u : lMSG.userList) { SM.Debug("$$$$$$ user:" + u.login + " id:" + u.id + " pass:" + u.password); } // save received users AppParams.allUsers = lMSG.userList; boolean good = false; // remembers if username and password are good for (User u : AppParams.allUsers) if (u.login.equals(etUsername.getText().toString()) && etPassword.getText().toString().equals(u.password)) { good = true; // flag good login userID = u.id; SM.Debug("Loged userID (LoginActivity):" + userID); } if (!good) { SM.Debug("Invalid username or password"); // invalid username uiHandler.post(() -> { cancelLoadingDialog(); cancelTimerLogin(); showErrorDialog("Login Error", getString(R.string.invalidUser)); }); } else { // clear tcp listener tcpParser.removeTCPListener(itcpListener); AppParams.USERNAME = etUsername.getText().toString(); AppParams.USERID = userID; // login was successful so I can load Tab Activity startTabActivity(userID); } } @Override public void onGPSReceived(TCPEvent event) { } @Override public void onSMSReceived(TCPEvent event) { } @Override public void onVehiclesReceived(TCPEvent event) { } @Override public void onLastSMSsReceived(TCPEvent event) { } @Override public void onSMSAckReceived(TCPEvent event) { } @Override public void onNewSMSReceived(TCPEvent event) { } @Override public void onLastPositionsReceived(TCPEvent event) { } @Override public void onRadioMsgReceived(TCPEvent event) { } @Override public void onHistoryPositionsReceived(TCPEvent event) { } @Override public void onHistoryPositionsCountReceived(TCPEvent event) { } @Override public void onAlarmsReceived(TCPEvent event) { } @Override public void onAlarmAckReceived(TCPEvent event) { } @Override public void alarmLiveReceived(TCPEvent event) { } @Override public void onRecordingPlayReceived(TCPEvent event) { } @Override public void onPollReceived(TCPEvent event) { } @Override public void onConnectionReplyReceived(TCPEvent event) { SM.Debug("Connection Ack Received", "##### Connection Ack Received #####"); } @Override public void onContactsListReceived(TCPEvent event) { } @Override public void onRecordingsListReceived(TCPEvent event) { } @Override public void onTextMessagesListReceived(TCPEvent event) { } @Override public void onTCPConnectionDown(boolean previousWasConnectionUp) { SM.Debug("TCP connection with:" + (tcp != null ? tcp.serverHostname : AppParams.RADIOIP) + ":" + (tcp != null ? tcp.getPort() : 0) + " is DOWN!!!"); // update ui only when a change happens with tcp connection if (tcp != null && prevTCPState.equals(tcp.isConnectionUP)) uiHandler.post(() -> { updateUIwithTCPStatus(false); // cancel loading dialog if an authenticating procedure is going on if (loadingDialog.isShowing()) { cancelLoadingDialog(); cancelTimerLogin(); } }); if (tcp != null) prevTCPState = tcp.isConnectionUP; // I can cancel the timer because I don't need for it to request the TCP status // the listener is now created and it will handle all the events broadcast cancelTimerLogin(); } @Override public void onTCPConnectionUp(boolean previousWasConnectionUp) { SM.Debug("TCP connection with:" + (tcp != null ? tcp.serverHostname : AppParams.RADIOIP) + " is UP!!!"); // update state only if previous was offline if (Boolean.TRUE.equals(!prevTCPState) || layoutTCP.getVisibility() == View.VISIBLE) { uiHandler.post(() -> updateUIwithTCPStatus(true)); } if (tcp != null) prevTCPState = tcp.isConnectionUP; // I can cancel the timer because I don't need for it to request the TCP status // the listener is now created and it will handle all the events broadcasted cancelTimerLogin(); } @Override public void onTCPConnectionStatusReceived(boolean isConnectionUp, boolean previousWasConnectionUp) { } @Override public void onPONGReceived() { // TODO Auto-generated method stub } }); } return null; } } }