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

1314 lines
40 KiB
Java
Raw Normal View History

2022-03-14 09:53:00 +00:00
package com.safemobile.dispatch;
2022-03-10 14:31:03 +00:00
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
//to fix R import
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 android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
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.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
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;
public class SDMobileActivity extends Activity {
/* Visual Elements */
private Button btLogin; //buttonChangeIP,
private EditText etPassword, etUsername;
private CheckBox checkBoxSaveDefault;
private RelativeLayout layoutTCP;
private LinearLayout llUsername, llPassword;
private ImageView imageLanguage, imageLoading, imageSettings, ivLogo;
/* Preferences */
private SharedPreferences.Editor editor;
//private String LANGUAGE, USERNAME, PASSWORD, IP, PORT, DEFAULT;
/* Misc */
//private boolean DEMO = false;
private String[] Languages = {"English", "German", "Turkish", "Romanian", "Russian", "Spanish"};
//private String LANGUAGETMP = null;
private Context context;
private Activity activity;
/* Dialog */
private Dialog dialogInfo, loadingDialog;
/* Handler for callbacks to the UI thread */
private final Handler myHandler = new Handler();
/* 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 loged in user
//private String oldUsername = null, oldPassword = null;
private String crtFirmwareVersion = "";
//private Boolean oldCheck = null;
private Boolean prevTCPState = false;
// default app language
public String databaseLanguage = "en"; // database language : en, de, tr, ro or empty
/** 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
2022-03-14 09:53:00 +00:00
this.setTheme(R.style.AppTheme);
2022-03-10 14:31:03 +00:00
// get Context
context = this;
activity = this;
// get settings
loadSettings();
// if package is demo set DEMO to true
2022-03-14 09:53:00 +00:00
AppParams.DEMO = (context.getPackageName().contains("demo"));
2022-03-10 14:31:03 +00:00
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;
2022-03-14 09:53:00 +00:00
getBaseContext().getResources().updateConfiguration(config,
2022-03-10 14:31:03 +00:00
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);
/*
RelativeLayout rlBackground = (RelativeLayout) findViewById(R.id.rlBackground);
int h = rlBackground.getHeight();
ShapeDrawable mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, h, Color.parseColor("#330000FF"), Color.parseColor("#110000FF"), Shader.TileMode.REPEAT));
rlBackground.setBackground(mDrawable);
*/
/*
try
{
// FIX Network in main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
catch(Exception ex)
{
;
}
*/
// 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);
ivLogo = (ImageView) findViewById(R.id.ivLogo);
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
if (AppParams.LANGUAGETMP.equals("en"))
imageLanguage.setImageResource(R.drawable.en);
else if (AppParams.LANGUAGETMP.equals("de"))
imageLanguage.setImageResource(R.drawable.de);
else if (AppParams.LANGUAGETMP.equals("tr"))
imageLanguage.setImageResource(R.drawable.tr);
else if (AppParams.LANGUAGETMP.equals("ro"))
imageLanguage.setImageResource(R.drawable.ro);
else if(AppParams.LANGUAGETMP.equals("es"))
imageLanguage.setImageResource(R.drawable.es);
else if(AppParams.LANGUAGETMP.equals("ru"))
imageLanguage.setImageResource(R.drawable.ru);
imageLanguage.setOnClickListener(LanguageListener);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btLogin = (Button) findViewById(R.id.btLogin);
btLogin.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(AppParams.DEMO)
startTabActivity(0);
else
{
if(etPassword.getText().toString().length()<1 || etUsername.getText().toString().length()<1)
showInfoDialog(getResources().getString(R.string.password));
//showDialog("Password or Username are empty!");
else {
// if save username and password
if(checkBoxSaveDefault.isChecked())
saveSettings(true); // save settings
else
saveSettings(false); // reset username and password
if(!loadingDialog.isShowing())
loadingDialog.show();
// TODO get users list
new connectTask().execute("login");
}
}
}
});
imageSettings = (ImageView) findViewById(R.id.imageSettings);
//buttonChangeIP = (Button) findViewById(R.id.buttonChangeIP);
imageSettings.setOnClickListener(changeIPListener);
//layoutTCP.setVisibility(View.INVISIBLE);
// 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 {
2022-03-14 09:53:00 +00:00
llUsername.setBackgroundResource(R.drawable.textboxx);
llPassword.setBackgroundResource(R.drawable.textboxx);
2022-03-10 14:31:03 +00:00
}
}
@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), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
whenBackPressed();
}
})
.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int 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), 1000).show();
//SM.Debug("Service is disconnected");
isBound = false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//Toast.makeText(context, getString(R.string.serviceConnected), 1000).show();
//SM.Debug("Service is connected");
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(!AppParams.IP.equals("n/a") && !AppParams.PORT.equals("n/a") && !AppParams.DEMO)
{
if(tcp == null)
{
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
myHandler.post(initTCPRUN);
}
}).start();
}
}
}
@Override
// this will be called when the user selects logout or exit
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
AppParams.ActivityResult result = (ActivityResult) intent.getSerializableExtra("result");
if(result == AppParams.ActivityResult.logout) {
SM.Debug("### RESULT ###", "LOGOUT");
updateUIwithTCPStatus(true);
}
else if(result == AppParams.ActivityResult.restart) {
// check tcp status and set UI
if(myService!= null)
tcp = myService.getTCPConnection();
SM.Debug("### RESULT ###", "RESTART");
/* authenticate again if tcp is ok */
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
myHandler.post(new Runnable() {
@Override
public void run() {
if(tcp!=null && tcp.isConnectionUP) {
if(!loadingDialog.isShowing())
loadingDialog.show();
enableUI(true);
layoutTCP.setVisibility(View.INVISIBLE);
new connectTask().execute("login");
}
}
});
}
}, 1000);
}
else if(result == AppParams.ActivityResult.tcpDown) {
SM.Debug("### RESULT ###", "TCP DOWN");
updateUIwithTCPStatus(false);
}
else if(result == AppParams.ActivityResult.exit) {
SM.Debug("### RESULT ###", "EXIT");
whenBackPressed();
}
} else if (resultCode == RESULT_CANCELED) {
//SM.Debug("LogOut","CANCeled " + (intent==null ? "null" : "not null"));
}
}
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
//changeIP();
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), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int 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), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int 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 ex)
{
}
activity.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
// Create runnable for posting
final Runnable initTCPRUN = new Runnable() {
public void run() {
// 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) {
// unregister tcpParser
if(tcpParser!= null && itcpListener != null)
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);
}
final Runnable CancelLoadingDialogRUN = new Runnable() {
@Override
public void run() {
// cancel loading dialog and show sending error message
CancelLoadingDialog();
}
};
// cancel loading dialog and show sending error message
private void CancelLoadingDialog()
{
// cancel loading dialog
if(loadingDialog!=null)
loadingDialog.cancel();
//if()
{
// show connection error
//showDialog("Could not load users!! Please check the connection and restart.");
}
}
// this will cancel the timer that waits for the autheticating procedure to complete
private void CancelTimerLogin() {
if(timerLogin!=null) {
timerLogin.cancel();
timerLogin = null;
}
}
// listener when select language pressed
private 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 , new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int 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
2022-03-10 14:31:03 +00:00
switch(which)
{
case 0: imageLanguage.setImageResource(R.drawable.en);
saved.putString("language", "en");
2022-03-14 09:53:00 +00:00
AppParams.LANGUAGETMP = "en"; AppParams.LANGUAGE = "en";
2022-03-10 14:31:03 +00:00
break;
case 1: imageLanguage.setImageResource(R.drawable.de);
saved.putString("language", "de");
2022-03-14 09:53:00 +00:00
AppParams.LANGUAGETMP = "de"; AppParams.LANGUAGE = "de";
2022-03-10 14:31:03 +00:00
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;
}
2022-03-14 09:53:00 +00:00
2022-03-10 14:31:03 +00:00
// recreate the activity
2022-03-14 09:53:00 +00:00
onCreate(saved);
2022-03-10 14:31:03 +00:00
}
});
AlertDialog alert = builder.create();
alert.show();
}
};
private void tcpInit()
{
int port = 0;
try
{
port = Integer.valueOf(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("");
//tcp = new TCPhandler(AppParams.IP, port);
//new TCPhandler().execute(AppParams.IP, port + "");
/*
try {
Thread.sleep(1000);
SM.Debug("new $$$ AUDIO $$$ TCP on IP: " + AppParams.IP );
AudioHandle audioH = new AudioHandle(AppParams.IP, context);
} catch (InterruptedException e) {
e.printStackTrace();
}
//*/
}
// 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", databaseLanguage);
// 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)
{
Log.e("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)
{
dialogInfo = new Dialog(context);
dialogInfo.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInfo.setContentView(R.layout.dialog_login);
TextView textTitle = (TextView) dialogInfo.findViewById(R.id.textTitle);
TextView text = (TextView) dialogInfo.findViewById(R.id.text);
TextView text2 = (TextView) dialogInfo.findViewById(R.id.text2);
ImageView image = (ImageView) 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();
}
/*
public void changeIP()
{
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialogip);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
final EditText editTextIP = (EditText) dialog.findViewById(R.id.editTextIP);
final EditText editTextPort = (EditText) dialog.findViewById(R.id.editTextPort);
if(!AppParams.IP.equals("n/a"))
editTextIP.setText(AppParams.IP);
SM.Debug("######## PORT " + AppParams.PORT);
if(!AppParams.PORT.equals("n/a"))
editTextPort.setText(AppParams.PORT);
//editTextPort.setText(PORT);
Button buttonCancel = (Button) dialog.findViewById(R.id.buttonCancelIP);
buttonCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// close dialog
dialog.dismiss();
// hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
});
Button buttonApply = (Button) dialog.findViewById(R.id.buttonApplyIP);
buttonApply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText editTextIP = (EditText) dialog.findViewById(R.id.editTextIP);
EditText editTextPort = (EditText) dialog.findViewById(R.id.editTextPort);
saveIPandRestartTCP(editTextIP.getText().toString(), editTextPort.getText().toString());
// hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// close dialog
dialog.dismiss();
}
});
// show dialog
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(!oldIP.equalsIgnoreCase(IP) || !oldPort.equalsIgnoreCase(PORT))
{
if(!AppParams.DEMO)
{
if(tcp!=null)
{
tcp.Stop();
if(tcpParser!= null)
tcpParser.clearMsgList();
tcp = null;
}
//showLoadingDialog("Getting users from database...");
myHandler.post(new Runnable() {
@Override
public void run() {
if(myService != null)
{
myService.stopTCPConnection();
myService.recreateTCPConnection();
myHandler.post(initTCPRUN);
/*
new connectTask().execute("");
new connectParserTask().execute("");
*/
// start thread to add listener
//tcp.updateTCPparameters(AppParams.IP, AppParams.PORT);
}
// recreate tcp
//myService.updateTCPparameters(AppParams.IP, AppParams.PORT);
//myService.recreateTCPConnection();
//tcpInit();
SM.Debug("RECREATE TCP","IP: " + AppParams.IP + " | Port: " + AppParams.PORT);
}
});
}
}
}
public static final String md5(final String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
//tcp
public boolean getUsers()
{
if(tcp==null)
return false;
if(!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<String, Void, TCPhandler>
{
@Override
protected TCPhandler doInBackground(String... params) {
if(params[0].equals("tcp")) {
if(myService!= null) {
tcp = myService.getTCPConnection();
if(myService!= null)
tcp = myService.getTCPConnection();
}
//tcp = new TCPhandler(AppParams.IP, Integer.parseInt(AppParams.PORT));
}
else if (params[0].equals("login")) {
getUsers();
// start a timert to display an error message if response isn't received
timerLogin = new Timer();
timerLogin.schedule(new TimerTask() {
@Override
public void run() {
myHandler.post(new Runnable() {
@Override
public void run() {
loadingDialog.cancel();
showErrorDialog("Login Error", "Could not receive response for login. Check connectivity and try again");
}
});
}
}, 10000);
}
return null;
}
}
public class connectParserTask extends AsyncTask<String, Void, TCPhandler>
{
@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
//Toast.makeText(context, getString(R.string.invalidUser), Toast.LENGTH_SHORT).show();
myHandler.post(new Runnable() {
@Override
public void run() {
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 alarmLiveRecv(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 previuosWasConnectionUp) {
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 != tcp.isConnectionUP)
myHandler.post(new Runnable() {
@Override
public void run() {
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 broadcasted
CancelTimerLogin();
}
@Override
public void onTCPConnectionUp(boolean previuosWasConnectionUp) {
SM.Debug("TCP connection with:"+ (tcp!=null ? tcp.serverHostname : AppParams.RADIOIP) + " is UP!!!");
// update state only if previous was offline
if(!prevTCPState || layoutTCP.getVisibility()==View.VISIBLE)
{
//SM.Debug("TCP connection with:"+tcp.serverHostname + " is OKKKKK!!!");
myHandler.post(new Runnable() {
@Override
public void run() {
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 previuosWasConnectionUp) {
}
@Override
public void onPONGReceived() {
// TODO Auto-generated method stub
}
});
}
return null;
}
}
}