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

1549 lines
46 KiB
Java

package com.safemobile.safedispatch;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
/** fix 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.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.AppParams.ActivityResult;
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.ActivityNotFoundException;
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.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
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;
public class SDMobileActivity_beforeMod extends Activity {
/* Visual Elements */
private Button buttonLogin;
private TextView textViewSpinnerUsername;
private EditText passwordBox, editUserName;
private LinearLayout layoutSpinnerUsername;
private CheckBox checkBoxSaveDefault;
private RelativeLayout layoutTCP;
private ImageView imageLanguage, imageLoading, imageSettings;
/* 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;
private ArrayList<String> allLogin = new ArrayList<String>();
private ArrayAdapter<String> adapterUsername;
/* Dialog */
private Dialog loadingDialog, dialog = null;
/* Handler for callbacks to the UI thread */
private final Handler myHandler = new Handler();
/* TCP */
protected TCPhandler tcp ;
protected TCPmsgParser tcpParser;
protected ITCPListener itcpListener;
private Boolean lastTCPstatus = true;
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
// 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);
if(AppParams.theme == AppParams.Theme.SAFENET)
this.setTheme(R.style.Theme_Safenet);
else
this.setTheme(R.style.AppTheme);
// get settings
loadSettings();
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.main);
// get Context
context = this;
activity = this;
// set demo value accoding to package name
AppParams.DEMO = getPackageName().contains("demo") ? true : false;
/*
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);
layoutSpinnerUsername = (LinearLayout) findViewById(R.id.layoutSpinnerUsername);
textViewSpinnerUsername = (TextView) findViewById(R.id.textViewSpinnerUsername);
if(AppParams.theme == AppParams.Theme.SAFENET)
{
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(layoutSpinnerUsername, InputMethodManager.SHOW_FORCED);
}
else
{
//set click listener
layoutSpinnerUsername.setOnClickListener(selectUsernameListener);
}
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);
layoutTCP = (RelativeLayout) findViewById(R.id.layoutTCP);
editUserName = (EditText) findViewById(R.id.editUserName);
passwordBox = (EditText) findViewById(R.id.Password);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(AppParams.DEMO)
{
// good login - load activity
Intent intent=new Intent(context, TabLayoutActivity.class);
intent.putExtra("userID", userID);
intent.putExtra("userName", textViewSpinnerUsername.getText().toString());
intent.putExtra("demo", AppParams.DEMO);
//startActivity(intent);
startActivityForResult(intent, 0);
}
else if(AppParams.theme == AppParams.Theme.SAFENET)
{
// check user name in json
}
else // if AppParams.SAFEDISPATCH
{
boolean good = false; // remembers if username and password are good
for(User u: AppParams.allUsers)
if(u.login.equals(textViewSpinnerUsername.getText().toString()) && passwordBox.getText().toString().equals(u.password))
{
good = true; // flag good login
userID = u.id;
SM.Debug("Loged userID (LoginActivity):" +userID);
}
if(!good && passwordBox.getText().toString().length()<1)
showDialog("Password is empty!");
else if (!good)
showDialog("Incorrect password!");
else
{
// if save username and password
if(checkBoxSaveDefault.isChecked())
saveSettings(true); // save settings
else
saveSettings(false); // reset username and password
if(!AppParams.DEMO) {
// unregister tcpParser
if(tcpParser!= null && itcpListener != null)
tcpParser.removeTCPListener(itcpListener);
}
CancelTimerLogin();
// good login - load activity
Intent intent=new Intent(context, TabLayoutActivity.class);
intent.putExtra("userID", userID);
intent.putExtra("userName", textViewSpinnerUsername.getText().toString());
intent.putExtra("demo", AppParams.DEMO);
// intent.putExtra("SCAN_MODE", "ONE_D_MODE");
startActivityForResult(intent, 0);
}
}
}
});
imageSettings = (ImageView) findViewById(R.id.imageSettings);
imageSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// show dialog
changeIP();
AnimationDrawable anim = (AnimationDrawable) imageLoading.getBackground();
anim.setOneShot(false);
if(anim.isRunning())
anim.stop();
else
anim.start();
}
});
layoutTCP.setVisibility(View.INVISIBLE);
// reset values when language changes
if(AppParams.allUsers.size()>0 && savedInstanceState.getString("username")!=null)
{
SM.Exception("LANGUAGE CHANGE ", "USer: " + savedInstanceState.getString("username") + " | " + savedInstanceState.getString("password"));
textViewSpinnerUsername.setText(savedInstanceState.getString("username"));
passwordBox.setText(savedInstanceState.getString("password"));
checkBoxSaveDefault.setChecked(savedInstanceState.getBoolean("checked"));
}
// create was done as a logout/tcp down
else if (AppParams.allUsers.size()>0 && savedInstanceState.getString("username") == null) {
textViewSpinnerUsername.setText(AppParams.USERNAME);
passwordBox.setText(AppParams.PASSWORD);
SM.Exception("Logout CHANGE", "USer: " + AppParams.USERNAME + " | " + AppParams.PASSWORD);
// recreate all login array
allLogin = new ArrayList<String>();
// get all users from database
for(User u: AppParams.allUsers)
allLogin.add(u.login); // add login name to array list
}
else
{
SM.Exception("NORMAL CREATE ","allUsers size : " + AppParams.allUsers.size());
textViewSpinnerUsername.setText("");
passwordBox.setText("");
}
// create loading dialog
createLoadingDialog(getString(R.string.getUsers));
/*
if(!AppParams.DEMO)
{
//start TCP timer
tcpTimer = new Timer();
tcpTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 3000, 2000);
}*/
if(AppParams.theme == AppParams.Theme.SAFENET)
{
imageSettings.setVisibility(View.INVISIBLE);
/*
buttonChangeIP.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
activity.finish();
if(AppParams.SAFENET)
AppParams.SAFENET = false;
else
AppParams.SAFENET = true;
//activity.setTheme(R.style.Theme_Safedispatch);
activity.startActivity(new Intent(activity, activity.getClass()));
}
});
*/
layoutSpinnerUsername.setVisibility(View.GONE);
editUserName.setVisibility(View.VISIBLE);
editUserName.setText(AppParams.USERNAME);
}
if(!AppParams.DEMO)
{
if(savedInstanceState == null)
updateUIwithTCPStatus(false);
//*
// disable UI only if the activity wasn't created as a consequence of language change or logout
// on first create the savedInstance will be null so I can determine this case
if(savedInstanceState == null) {
updateUIwithTCPStatus(false);
// start timer which will check TCP state
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);
}
//*/
/** Create Service and bind on it */
getApplicationContext().bindService(new Intent(this, TCPService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}
}
@Override
public void onBackPressed()
{
// if loading dialog is showing
if(loadingDialog.isShowing())
{
CancelLoadingDialog();
}
else
{
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();
}
}
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
//Toast.makeText(context, "Service is disconnected", 1000).show();
SM.Debug("Service is disconnected");
isBound = false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//Toast.makeText(context, "Service is connected", 1000).show();
SM.Debug("Service is connected");
TCPBinder binder = (TCPBinder) service;
myService = binder.getService();
if(myService!= null)
tcp = myService.getTCPConnection();
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)
{
allLogin.add("demo");
AppParams.allUsers.clear();
AppParams.allUsers.add(new User(0, "demo", "demo", "demo", "demo", 1, 1));
passwordBox.setText("demo");
textViewSpinnerUsername.setText("demo");
}
if(dialog!=null)
dialog.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
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
@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");
// enable UI
updateUIwithTCPStatus(true);
// recreate all login array
allLogin = new ArrayList<String>();
// get all users from database
for(User u: AppParams.allUsers)
allLogin.add(u.login); // add login name to array list
// check tcp status and set UI
if(myService != null) {
SM.Exception("SERVICe is noT NULL");
tcp = myService.getTCPConnection();
}
else {
SM.Exception("SERVICe is NULL");
/** Create Service and bind on it */
getApplicationContext().bindService(new Intent(this, TCPService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}
// connect to the server
new connectParserTask().execute("");
new connectTask().execute("");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
myHandler.post(getUsersRUN);
}
}).start();
}
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();
updateUIwithTCPStatus(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) {
}
}
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 void whenBackPressed()
{
if(tcp!=null)
{
tcp.Stop();
if(tcpParser!=null)
tcpParser.Stop();
}
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();
}
};
// Create runnable for posting
final Runnable getUsersRUN = new Runnable() {
public void run() {
// start a thread to wait 3 seconds for ack
new Thread(new Runnable() {
@Override
public void run() {
try {
SM.Debug("##### getUsersRUN()");
// get all users
if(!getUsers())
{
//close loading dialog
loadingDialog.cancel();
// show connection error
myHandler.post(new Runnable() {
@Override
public void run() {
showDialog(getString(R.string.notloadUser));
}
});
}
Thread.sleep(5000);
} catch (InterruptedException e) {
//e.printStackTrace();
SM.Exception(e.toString());
}
// if message ack not received
myHandler.post(CancelLoadingDialogRUN);
}
}).start();
}
};
@Override
public void onPause()
{
super.onPause();
SM.Debug("##### onPAUSE #####");
}
@Override
public void onResume()
{
super.onResume();
SM.Debug("##### onRESUME #####");
// if IP and PORT not set -> show dialog
if(AppParams.IP.equals("n/a") && AppParams.PORT.equals("n/a") && !AppParams.DEMO)
changeIP();
}
//timer stuff
private void TimerMethod()
{
//Do something to the UI thread here
if(tcp != null)
{
if(!tcp.isConnectionUP)
{
SM.Debug("TCP connection with:"+tcp.serverHostname + " is DOWN!!!");
myHandler.post(new Runnable() {
@Override
public void run() {
updateUIwithTCPStatus(false);
}
});
}
else
{
//SM.Debug("TCP connection with:"+tcp.serverHostname + " is OKKKKK!!!");
myHandler.post(new Runnable() {
@Override
public void run() {
updateUIwithTCPStatus(true);
}
});
}
// save crt status
lastTCPstatus = tcp.isConnectionUP;
}
else
myHandler.post(new Runnable() {
@Override
public void run() {
updateUIwithTCPStatus(false);
}
});
}
private void updateUIwithTCPStatus(boolean enable)
{
if(enable)
{
// if last status was offline get Users
if(lastTCPstatus == false)
{
// show loading dialog
if(!loadingDialog.isShowing())
{
loadingDialog.show();
//showLoadingDialog("Getting users from database...");
myHandler.post(getUsersRUN);
}
}
layoutTCP.setVisibility(View.INVISIBLE);
if(dialog!=null && dialog.isShowing())
dialog.hide();
}
else
{
if(!loadingDialog.isShowing())
{
// clear spinner and password
//textViewSpinnerUsername.setText("");
//passwordBox.setText("");
/*
allLogin.clear();
allUsers.clear();*/
layoutTCP.setVisibility(View.VISIBLE);
}
}
// enable or disable UI elements
buttonLogin.setEnabled(enable);
passwordBox.setEnabled(enable);
checkBoxSaveDefault.setEnabled(enable);
layoutSpinnerUsername.setEnabled(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
loadingDialog.cancel();
//if()
{
// show connection error
//showDialog("Could not load users!! Please check the connection and restart.");
}
}
// 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) {
// save current UI values
Bundle saved = new Bundle();
saved.putString("username", textViewSpinnerUsername.getText().toString());
saved.putString("password", passwordBox.getText().toString());
saved.putBoolean("checked", checkBoxSaveDefault.isChecked());
switch(which)
{
case 0: imageLanguage.setImageResource(R.drawable.en);
AppParams.LANGUAGETMP = "en";
saved.putString("language", "en");
break;
case 1: imageLanguage.setImageResource(R.drawable.de);
AppParams.LANGUAGETMP = "de";
saved.putString("language", "de");
break;
case 2: imageLanguage.setImageResource(R.drawable.tr);
AppParams.LANGUAGETMP = "tr";
saved.putString("language", "tr");
break;
case 3: imageLanguage.setImageResource(R.drawable.ro);
AppParams.LANGUAGETMP = "ro";
saved.putString("language", "ro");
break;
case 4: imageLanguage.setImageResource(R.drawable.ru);
AppParams.LANGUAGETMP = "ru";
saved.putString("language", "ru");
break;
case 5: imageLanguage.setImageResource(R.drawable.es);
AppParams.LANGUAGETMP = "es";
saved.putString("language", "es");
break;
}
// recreate the activity
onCreate(saved);
}
});
AlertDialog alert = builder.create();
alert.show();
}
};
private OnClickListener selectUsernameListener = new OnClickListener() {
@Override
public void onClick(View v) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_dropdown_item_1line, allLogin);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.selUsername));
builder.setAdapter(adapter , new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(AppParams.DEMO)
{
// set textView
textViewSpinnerUsername.setText("demo");
passwordBox.setText("demo");
}
else
{
// set textView
textViewSpinnerUsername.setText(allLogin.get(which));
// if IP and PORT equals with default IP and PORT set saved username and password
String[] splitDefault = AppParams.DEFAULT.split("#");
SM.Debug(" ################## " + AppParams.DEFAULT);
if(splitDefault[0].equals(AppParams.IP) && splitDefault[1].equals(AppParams.PORT))
{
if(AppParams.USERNAME.equals(allLogin.get(which)))
{
textViewSpinnerUsername.setText(AppParams.USERNAME);
passwordBox.setText(AppParams.PASSWORD);
}
else
{
textViewSpinnerUsername.setText(allLogin.get(which));
passwordBox.setText("");
}
}
else
{
textViewSpinnerUsername.setText(allLogin.get(which));
passwordBox.setText("");
}
}
}
});
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 connectParserTask().execute("");
new connectTask().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", 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", "n/a");
// get default communication port
AppParams.PORT = AppParams.prefs.getString("port", "n/a");
// get default value -> IP,PORT
AppParams.DEFAULT = AppParams.prefs.getString("default", "0#0");
SM.Debug("LOAD SETTINGS ### UserName: " + AppParams.USERNAME + " |Password: " + AppParams.PASSWORD
+ " |IP: " + AppParams.IP + " |PORT: " + AppParams.PORT);
}
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);
// save new username and password
if(modify)
{
if(textViewSpinnerUsername.getText().toString().length() > 0)
editor.putString("username", textViewSpinnerUsername.getText().toString());
else
editor.putString("username", "n/a");
if(passwordBox.getText().toString().length() > 0)
editor.putString("password", passwordBox.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");
}
SM.Debug("SAVE SETTINGS ### UserName: " + AppParams.USERNAME + " |Password: " + AppParams.PASSWORD
+ " |IP: " + AppParams.IP + " |PORT: " + AppParams.PORT);
editor.commit();
}
public void showDialog(String errorMsg)
{
dialog = new Dialog(context);
dialog.setTitle(getString(R.string.connectionError));
dialog.setContentView(R.layout.dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
TextView text = (TextView) dialog.findViewById(R.id.text);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.error);
text.setText(errorMsg);
dialog.show();
}
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 changeIP()
{
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialogip);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
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);
// hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// save old IP and PORT values
// get IP
AppParams.IP = editTextIP.getText().toString();
if(AppParams.IP.length()<1)
AppParams.IP = "n/a";
// get Preferences for SafeDispatch
// save net ip
editor = AppParams.prefs.edit();
// put new values
editor.putString("ip", AppParams.IP);
// get PORT
try
{
AppParams.PORT = editTextPort.getText().toString();
if(AppParams.PORT.length()<1)
AppParams.PORT = "n/a";
// save port
editor.putString("port", AppParams.PORT);
// close dialog
dialog.dismiss();
}
catch(Exception ex)
{
editTextPort.requestFocus();
}
editor.commit();
// if port or IP changed
//if(!oldIP.equalsIgnoreCase(IP) || !oldPort.equalsIgnoreCase(PORT))
{
// clear values
allLogin = new ArrayList<String>();
AppParams.allUsers = new ArrayList<User>();
if(AppParams.DEMO)
{
allLogin.add("demo");
AppParams.allUsers.add(new User(0, "demo", "demo", "demo", "demo", 1, 1));
}
textViewSpinnerUsername.setText("");
passwordBox.setText("");
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(AppParams.IP, AppParams.PORT);
myHandler.post(initTCPRUN);
/*
// start thread to add listener
SM.Debug("##### initTCPRUN");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myHandler.post(getUsersRUN);
}
}).start();
*/
//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);
}
});
if(!loadingDialog.isShowing())
loadingDialog.show();
}
}
}
});
// show dialog
dialog.show();
}
//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");
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
SM.Exception(e.toString());
}
// if message ack not received
myHandler.post(CancelLoadingDialogRUN);
}
}).start();
}else{
SM.Debug("Could not send message!!");
}
return res;
}
// Create runnable for posting
final Runnable UpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
private void updateResultsInUi()
{
try
{
//close loading dialog
loadingDialog.cancel();
}
catch(IllegalArgumentException ex)
{
SM.Exception(ex.toString());
}
SM.Debug("SET adapter");
textViewSpinnerUsername = (TextView) findViewById(R.id.textViewSpinnerUsername);
try
{
//close loading dialog
loadingDialog.cancel();
}
catch(Exception ex)
{
SM.Exception(ex.toString());
}
adapterUsername = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item , allLogin);
adapterUsername.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
adapterUsername.notifyDataSetChanged();
// if IP and PORT equals with default IP and PORT set saved username and password
String[] splitDefault = AppParams.DEFAULT.split("#");
if(splitDefault[0].equals(AppParams.IP) && splitDefault[1].equals(AppParams.PORT))
{
if(!AppParams.USERNAME.equals("n/a") && allLogin.contains(AppParams.USERNAME))
{
textViewSpinnerUsername.setText(AppParams.USERNAME);
passwordBox.setText(AppParams.PASSWORD);
}
else
{
textViewSpinnerUsername.setText(allLogin.get(0));
passwordBox.setText("");
}
}
else
{
textViewSpinnerUsername.setText(allLogin.get(0));
passwordBox.setText("");
}
}
public static boolean setShortCut(String appName,Context context) throws Exception
{
try
{
//Log.i("shortcut method in androidhelper start","in the shortcutapp on create method ");
boolean flag =false ;
int app_id=-1;
PackageManager p = context.getPackageManager();
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> res =p.queryIntentActivities( i,0);
//System.out.println("the res size is: "+res.size());
for(int k=0;k<res.size();k++)
{
//Log.i("","the application name is: "+res.get(k).activityInfo.loadLabel(p));
if(res.get(k).activityInfo.loadLabel(p).toString().equals(appName))
{
flag = true;
app_id = k;
break;
}
}
if(flag)
{
ActivityInfo ai = res.get(app_id).activityInfo;
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName(ai.packageName, ai.name);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.addCategory(Intent.ACTION_PICK_ACTIVITY);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
// Sets the custom shortcut's title
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
BitmapDrawable bd = (BitmapDrawable)(res.get(app_id).activityInfo.loadIcon(p).getCurrent());
Bitmap newbit;
newbit=bd.getBitmap();
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, newbit);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
context.sendBroadcast(intent);
}
else
{
//throw new UserException(UserException.KErrGeneral,"Application not found");
}
}
catch(ActivityNotFoundException e)
{
e.printStackTrace();
throw e;
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
return true;
}
public class connectTask extends AsyncTask<String, Void, TCPhandler>
{
@Override
protected TCPhandler doInBackground(String... params) {
if(myService!= null)
tcp = myService.getTCPConnection();
//tcp = new TCPhandler(AppParams.IP, Integer.parseInt(AppParams.PORT));
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);
}
allLogin = new ArrayList<String>();
// get all users from database
AppParams.allUsers = lMSG.userList;
for(User u: AppParams.allUsers)
allLogin.add(u.login); // add login name to array list
// update UI
myHandler.post(UpdateResults);
}
@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 onPollReceived(TCPEvent event) { }
@Override
public void onConnectionReplyReceived(TCPEvent event) { }
@Override
public void onRecordingPlayReceived(TCPEvent event) { }
@Override
public void onContactsListReceived(TCPEvent event) { }
@Override
public void onTextMessagesListReceived(TCPEvent event) { }
@Override
public void onRecordingsListReceived(TCPEvent event) { }
@Override
public void onTCPConnectionDown(boolean previousWasConnectionUp) {
SM.Debug("TCP Connection Down");
// set connection is down
lastTCPstatus = false;
// disable UI
myHandler.post(new Runnable() {
@Override
public void run() {
// hide loading dialog
if(!loadingDialog.isShowing())
loadingDialog.dismiss();
// disable UI
updateUIwithTCPStatus(false);
}
});
// 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 previousWasConnectionUp) {
SM.Debug("TCP Connection UP");
// set connection is up
lastTCPstatus = true;
// enable UI
myHandler.post(new Runnable() {
@Override
public void run() {
// enable UI
updateUIwithTCPStatus(true);
// 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();
}
if(!loadingDialog.isShowing())
loadingDialog.show();
//showLoadingDialog("Getting users from database...");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
myHandler.post(getUsersRUN);
}
}).start();
}
}
});
// 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(final boolean isConnectionUp, boolean previousWasConnectionUp) {
//SM.Debug("TCP STATUS", "ConnectionUP: " + isConnectionUp + " | previous: " + previuosWasConnectionUp );
/*
if(!lastTCPstatus && isConnectionUp) {
myHandler.post(new Runnable() {
@Override
public void run() {
// update UI
updateUIwithTCPStatus(isConnectionUp);
}
});
// get
if(isConnectionUp)
myHandler.post(getUsersRUN);
}
// update previous TCP state
lastTCPstatus = isConnectionUp;
//*/
}
@Override
public void onPONGReceived() {
// TODO Auto-generated method stub
}
});
}
return null;
}
}
// this will cancel the timer that waits for the autheticating procedure to complete
private void CancelTimerLogin() {
if(timerLogin!=null) {
timerLogin.cancel();
timerLogin = null;
}
}
}