safedispatch-mobile/safeDispatch/src/main/java/com/safemobile/safedispatch/SDMobileActivity.java

1051 lines
31 KiB
Java
Raw Normal View History

2022-03-24 09:18:49 +00:00
package com.safemobile.safedispatch;
2022-03-10 14:31:03 +00:00
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;
2022-03-10 14:31:03 +00:00
import android.text.Editable;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
2022-03-10 14:31:03 +00:00
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;
2022-03-10 14:31:03 +00:00
public class SDMobileActivity extends Activity {
2022-03-10 14:31:03 +00:00
/* Visual Elements */
private Button btLogin;
private EditText etPassword;
private EditText etUsername;
2022-03-10 14:31:03 +00:00
private CheckBox checkBoxSaveDefault;
private RelativeLayout layoutTCP;
private LinearLayout llUsername;
private LinearLayout llPassword;
private ImageView imageLanguage;
2022-03-10 14:31:03 +00:00
/* Preferences */
private SharedPreferences.Editor editor;
2022-03-10 14:31:03 +00:00
/* Misc */
private String[] languages = {"English", "German", "Turkish", "Romanian", "Russian", "Spanish"};
2022-03-10 14:31:03 +00:00
private Context context;
private Activity activity;
private Dialog loadingDialog;
2022-03-10 14:31:03 +00:00
/* Handler for callbacks to the UI thread */
private final Handler uiHandler = new Handler(Looper.getMainLooper());
2022-03-10 14:31:03 +00:00
/* TCP */
protected TCPhandler tcp;
2022-03-10 14:31:03 +00:00
protected TCPmsgParser tcpParser;
protected ITCPListener itcpListener;
protected Timer timerLogin;//timer to check connection!!!
/**
* TCP Service
*/
2022-03-10 14:31:03 +00:00
private TCPService myService;
private boolean isBound = false;
2022-03-10 14:31:03 +00:00
/* User details */
protected int userID;// ID of logged in user
2022-03-10 14:31:03 +00:00
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
2022-03-10 14:31:03 +00:00
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);
2022-03-10 14:31:03 +00:00
}
}
});
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));
2022-03-10 14:31:03 +00:00
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);
}
2022-03-28 13:34:53 +00:00
layoutTCP = findViewById(R.id.layoutTCP);
2022-03-28 13:34:53 +00:00
llUsername = findViewById(R.id.llUsername);
llPassword = 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() {
2022-03-10 14:31:03 +00:00
@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) {
2022-03-10 14:31:03 +00:00
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() {
2022-03-10 14:31:03 +00:00
@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(context, getString(R.string.serviceDisconnected), Toast.LENGTH_SHORT).show();
isBound = false;
2022-03-10 14:31:03 +00:00
}
2022-03-10 14:31:03 +00:00
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
TCPBinder binder = (TCPBinder) service;
myService = binder.getService();
isBound = true;
2022-03-10 14:31:03 +00:00
}
};
2022-03-10 14:31:03 +00:00
@Override
public void onStop() {
2022-03-10 14:31:03 +00:00
super.onStop();
SM.Debug("##### onSTOP #####");
// Unbind from the service
if (isBound) {
getApplicationContext().unbindService(serviceConnection);
isBound = false;
}
2022-03-10 14:31:03 +00:00
}
@Override
public void onStart() {
super.onStart();
SM.Debug("##### onSTART #####");
if (AppParams.DEMO) {
2022-03-10 14:31:03 +00:00
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);
}
});
2022-03-10 14:31:03 +00:00
}
}, 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() {
2022-03-10 14:31:03 +00:00
@Override
public void onClick(View v) {
// show dialog
LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
2022-03-10 14:31:03 +00:00
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);
2022-03-10 14:31:03 +00:00
ll.addView(input, 0);
2022-03-10 14:31:03 +00:00
final TextView tv = new TextView(context);
tv.setText(":");
tv.setTextColor(Color.WHITE);
ll.addView(tv, 1);
2022-03-10 14:31:03 +00:00
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);
2022-03-10 14:31:03 +00:00
ll.setGravity(Gravity.CENTER);
2022-03-10 14:31:03 +00:00
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();
2022-03-10 14:31:03 +00:00
}
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();
2022-03-10 14:31:03 +00:00
};
@Override
public void onPause() {
super.onPause();
2022-03-10 14:31:03 +00:00
SM.Debug("##### onPAUSE #####");
}
2022-03-10 14:31:03 +00:00
@Override
public void onResume() {
super.onResume();
2022-03-10 14:31:03 +00:00
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());
2022-03-10 14:31:03 +00:00
AppParams.USERNAME = etUsername.getText().toString();
AppParams.PASSWORD = etPassword.getText().toString();
AppParams.USERID = userID;
if (!AppParams.DEMO && tcpParser != null && itcpListener != null) {
2022-03-10 14:31:03 +00:00
// unregister tcpParser
tcpParser.removeTCPListener(itcpListener);
2022-03-10 14:31:03 +00:00
}
2022-03-10 14:31:03 +00:00
// start activity
startActivityForResult(intent, 0);
}
private void updateUIwithTCPStatus(boolean enable) {
2022-03-10 14:31:03 +00:00
SM.Debug("UPDATE UI :" + enable);
if (enable)
2022-03-10 14:31:03 +00:00
layoutTCP.setVisibility(View.INVISIBLE);
else
layoutTCP.setVisibility(View.VISIBLE);
2022-03-10 14:31:03 +00:00
enableUI(enable);
}
2022-03-10 14:31:03 +00:00
// cancel loading dialog and show sending error message
private void cancelLoadingDialog() {
2022-03-10 14:31:03 +00:00
// cancel loading dialog
if (loadingDialog != null)
2022-03-10 14:31:03 +00:00
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;
}
2022-03-10 14:31:03 +00:00
}
// listener when select language pressed
private final OnClickListener LanguageListener = new OnClickListener() {
2022-03-10 14:31:03 +00:00
@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());
2022-03-14 09:53:00 +00:00
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();
2022-03-10 14:31:03 +00:00
}
};
2022-03-10 14:31:03 +00:00
private void tcpInit() {
2022-03-10 14:31:03 +00:00
int port = 0;
try {
port = Integer.parseInt(AppParams.PORT);
} catch (Exception ex) {
2022-03-10 14:31:03 +00:00
SM.Debug("PORT is not an integer");
}
//create TCP handle
2022-03-10 14:31:03 +00:00
SM.Debug("new TCP on IP: " + AppParams.IP + " | PORT: " + port);
2022-03-10 14:31:03 +00:00
// 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
2022-03-28 13:34:53 +00:00
AppParams.IP = AppParams.prefs.getString("ip", "185.8.154.190");
// 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");
}
2022-03-10 14:31:03 +00:00
}
public void saveSettings(boolean modify) {
2022-03-10 14:31:03 +00:00
// get editor
editor = AppParams.prefs.edit();
// put new values
editor.putString(LANGUAGE, AppParams.LANGUAGETMP);
2022-03-10 14:31:03 +00:00
editor.putString("languagetmp", AppParams.LANGUAGETMP);
// save new username and password
if (modify) {
if (etUsername.getText().toString().length() > 0)
editor.putString(USERNAME, etUsername.getText().toString());
2022-03-10 14:31:03 +00:00
else
editor.putString(USERNAME, "n/a");
if (etPassword.getText().toString().length() > 0)
editor.putString(PASSWORD, etPassword.getText().toString());
2022-03-10 14:31:03 +00:00
else
editor.putString(PASSWORD, "n/a");
2022-03-10 14:31:03 +00:00
// safe default -> ip#port
editor.putString(DEFAULT, AppParams.IP + "#" + AppParams.PORT);
} else // reset username and password
2022-03-10 14:31:03 +00:00
{
editor.putString(USERNAME, "n/a");
editor.putString(PASSWORD, "n/a");
editor.putString(DEFAULT, "0#0");
2022-03-10 14:31:03 +00:00
}
2022-03-10 14:31:03 +00:00
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) {
2022-03-10 14:31:03 +00:00
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);
2022-03-28 11:02:10 +00:00
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();
2022-03-10 14:31:03 +00:00
}
}
public void showErrorDialog(String title, String errorMsg) {
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_login);
2022-03-10 14:31:03 +00:00
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);
2022-03-10 14:31:03 +00:00
dialog.show();
}
2022-03-10 14:31:03 +00:00
private void saveIPandRestartTCP(String myIP, String port) {
// get IP
if (myIP.length() > 1)
2022-03-10 14:31:03 +00:00
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)
2022-03-10 14:31:03 +00:00
AppParams.PORT = "n/a";
// save port
editor.putString("port", AppParams.PORT);
editor.commit();
SM.Exception("TCP CHANGED WITH IP AND PORT " + myIP + " | " + port);
2022-03-10 14:31:03 +00:00
// 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);
});
2022-03-10 14:31:03 +00:00
}
}
2022-03-10 14:31:03 +00:00
//tcp
public boolean getUsers() {
if (tcp == null)
2022-03-10 14:31:03 +00:00
return false;
if (Boolean.FALSE.equals(tcp.isConnectionUP))
2022-03-10 14:31:03 +00:00
return false;
2022-03-10 14:31:03 +00:00
boolean res = tcp.Write("0.0", "#20#");
if (res) {
2022-03-10 14:31:03 +00:00
SM.Debug("Message sent to app server");
} else {
2022-03-10 14:31:03 +00:00
SM.Debug("Could not send message!!");
}
return res;
}
public class connectTask extends AsyncTask<String, Void, TCPhandler> {
2022-03-10 14:31:03 +00:00
@Override
protected TCPhandler doInBackground(String... params) {
if (params[0].equals("tcp")) {
if (myService != null) {
2022-03-10 14:31:03 +00:00
tcp = myService.getTCPConnection();
}
} else if (params[0].equals(LOGIN)) {
2022-03-10 14:31:03 +00:00
getUsers();
// start a timer to display an error message if response isn't received
2022-03-10 14:31:03 +00:00
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");
2022-03-10 14:31:03 +00:00
});
}
}, 10000);
}
return null;
}
}
public class connectParserTask extends AsyncTask<String, Void, TCPhandler> {
2022-03-10 14:31:03 +00:00
@Override
protected TCPhandler doInBackground(String... params) {
if (myService != null)
2022-03-10 14:31:03 +00:00
tcpParser = myService.getTCPmsgParser();
// add TCPParserListener
if (tcpParser != null) {
2022-03-10 14:31:03 +00:00
tcpParser.clearITCPListeners();
tcpParser.addTCPListener(itcpListener = new ITCPListener() {
@Override
public void onLoginReceived(TCPEvent event) {
2022-03-10 14:31:03 +00:00
SM.Debug("LoginReceived", "LoginReceived");
TCPmsg msg = event.msg();
2022-03-10 14:31:03 +00:00
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);
2022-03-10 14:31:03 +00:00
}
2022-03-10 14:31:03 +00:00
// 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
2022-03-10 14:31:03 +00:00
userID = u.id;
SM.Debug("Loged userID (LoginActivity):" + userID);
2022-03-10 14:31:03 +00:00
}
if (!good) {
2022-03-10 14:31:03 +00:00
SM.Debug("Invalid username or password");
// invalid username
uiHandler.post(() -> {
cancelLoadingDialog();
cancelTimerLogin();
showErrorDialog("Login Error", getString(R.string.invalidUser));
2022-03-10 14:31:03 +00:00
});
} else {
2022-03-10 14:31:03 +00:00
// clear tcp listener
tcpParser.removeTCPListener(itcpListener);
2022-03-10 14:31:03 +00:00
AppParams.USERNAME = etUsername.getText().toString();
AppParams.USERID = userID;
2022-03-10 14:31:03 +00:00
// login was successful so I can load Tab Activity
startTabActivity(userID);
}
}
2022-03-10 14:31:03 +00:00
@Override
public void onGPSReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onSMSReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onVehiclesReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onLastSMSsReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onSMSAckReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onNewSMSReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onLastPositionsReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onRadioMsgReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onHistoryPositionsReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onHistoryPositionsCountReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onAlarmsReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onAlarmAckReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void alarmLiveReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onRecordingPlayReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onPollReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onConnectionReplyReceived(TCPEvent event) {
SM.Debug("Connection Ack Received", "##### Connection Ack Received #####");
2022-03-10 14:31:03 +00:00
}
@Override
public void onContactsListReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onRecordingsListReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onTextMessagesListReceived(TCPEvent event) {
}
2022-03-10 14:31:03 +00:00
@Override
public void onTCPConnectionDown(boolean previousWasConnectionUp) {
SM.Debug("TCP connection with:" + (tcp != null ? tcp.serverHostname : AppParams.RADIOIP) + ":"
+ (tcp != null ? tcp.getPort() : 0) + " is DOWN!!!");
2022-03-10 14:31:03 +00:00
// 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();
2022-03-10 14:31:03 +00:00
}
});
if (tcp != null)
2022-03-10 14:31:03 +00:00
prevTCPState = tcp.isConnectionUP;
2022-03-10 14:31:03 +00:00
// 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();
2022-03-10 14:31:03 +00:00
}
@Override
public void onTCPConnectionUp(boolean previousWasConnectionUp) {
SM.Debug("TCP connection with:" + (tcp != null ? tcp.serverHostname : AppParams.RADIOIP) + " is UP!!!");
2022-03-10 14:31:03 +00:00
// update state only if previous was offline
if (Boolean.TRUE.equals(!prevTCPState) || layoutTCP.getVisibility() == View.VISIBLE) {
uiHandler.post(() -> updateUIwithTCPStatus(true));
2022-03-10 14:31:03 +00:00
}
if (tcp != null)
2022-03-10 14:31:03 +00:00
prevTCPState = tcp.isConnectionUP;
2022-03-10 14:31:03 +00:00
// 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();
2022-03-10 14:31:03 +00:00
}
2022-03-10 14:31:03 +00:00
@Override
public void onTCPConnectionStatusReceived(boolean isConnectionUp, boolean previousWasConnectionUp) {
2022-03-10 14:31:03 +00:00
}
@Override
public void onPONGReceived() {
// TODO Auto-generated method stub
}
});
2022-03-10 14:31:03 +00:00
}
return null;
}
}
}