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

2352 lines
76 KiB
Java

package com.safemobile.dispatch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import com.safemobile.activities.AbstractEmptyActivity;
import com.safemobile.activities.AbstractLiveActivity;
import com.safemobile.activities.AbstractMessagesActivity;
import com.safemobile.activities.AbstractRadioActivity;
import com.safemobile.activities.AbstractSDParentActivity;
import com.safemobile.interfaces.ITCPListener;
import com.safemobile.interfaces.TCPEvent;
import com.safemobile.lib.Alarm;
import com.safemobile.lib.AlarmMSG;
import com.safemobile.lib.AppParams;
import com.safemobile.lib.GPSmsg;
import com.safemobile.lib.HistCountmsg;
import com.safemobile.lib.HistPos;
import com.safemobile.lib.HistPosmsg;
import com.safemobile.lib.OperationCodes;
import com.safemobile.lib.RadioMSG;
import com.safemobile.lib.LastPos;
import com.safemobile.lib.LastPosmsg;
import com.safemobile.lib.RecordMSG;
import com.safemobile.lib.Recording;
import com.safemobile.lib.SM;
import com.safemobile.lib.SMS;
import com.safemobile.lib.SMSmsg;
import com.safemobile.lib.SerializedObject;
import com.safemobile.lib.SuperVehicle;
import com.safemobile.lib.TCPmsg;
import com.safemobile.lib.VehMSG;
import com.safemobile.lib.Vehicle;
import com.safemobile.lib.radio.RadioGW;
import com.safemobile.services.TCPService;
import com.safemobile.services.TCPhandler;
import com.safemobile.services.TCPService.TCPBinder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
public class TabLayoutActivity extends AbstractSDParentActivity{
/* Misc */
private Resources res;
private Context context;
public RadioGW crtRadio = null;
public int crtActivity = 0, RADIO = 4;
private Boolean isMenuVisible = true, firstGetVehs = true, lastTCPstatus = false;
private Boolean NOSOUND = false;
public Boolean inCall = false;
//public boolean DEMO; // value received through intent.getExtra()
/* Activities */
public AbstractLiveActivity liveActivity = null;
public RadioActivity radioActivity = null;
public MessagesActivity messageActivity = null;
public HistoryActivity historyActivity = null;
public RecordingsActivity recordingsActivity = null;
public AlarmActivity alarmActivity = null;
/* Handler for callbacks to the UI thread */
public final Handler myHandler = new Handler();
/* Lists */
public ArrayList<RadioGW> allRadios;
public volatile ArrayList<HistPos> HistPosList = new ArrayList<>();
public volatile Boolean firstHistData = false;
public volatile Boolean dropAllData = false;
public volatile ArrayList<Boolean> HistMsgList = new ArrayList<>();
/* DEMO lists */
public ArrayList<SMS> listSMS;
public ArrayList<HistPos> demoPositions = new ArrayList<>();
/* Tab */
private TabWidget tabWidget;
private TabSpec[] tabspecs;
private TabHost tabHost;
private Intent[] intent;
/* Visual Elements */
private LinearLayout layoutMenu, layoutSlideMenu;
private RelativeLayout layoutNewMessage;
private TextView textViewNMMessage, textViewNMFrom = null, slideTabsText;
private ImageView imageViewSlideMenu, imageViewPopUp, imageViewClose;
private ImageButton buttonLive, buttonHistory, buttonText, buttonRadio, buttonAlarms, buttonRecordings, buttonSetup, buttonLogo;
/* Notification */
private Intent notificationIntent;
private final int NOTIFICATION_ACTIVITY_RESULT = 1;
private NotificationManager mNotificationManager;
/* TCP */
protected Timer tcpTimer;//timer to check connection!!!
/** TCP Service */
private TCPService myService;
private boolean isBound = false;
/* User details */
//protected int userID = 1;// ID of loged in userr
//public String userName;
// default app language
public String databaseLanguage = "en"; // database language : en, de, tr, ro or empty
public enum MsgType { TCP,SMS,POLL,ALARM};
public MsgType activePopupType = MsgType.TCP;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
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);
super.onCreate(savedInstanceState);
SM.Debug("######### ON CREATE TAB");
// get settings
loadSettings();
// save selected language (may differ from saved one)
if(AppParams.LANGUAGETMP==null)
AppParams.LANGUAGETMP = AppParams.LANGUAGE;
// change locale
Locale locale = new Locale(AppParams.LANGUAGETMP);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
setContentView(R.layout.tabpanel);
context = this;
res = getResources(); // Resource object to get Drawables
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectNetwork().build();
// StrictMode.setThreadPolicy(policy);
//AppParams.USERID = getIntent().getExtras().getInt("userID");
//AppParams.userName = getIntent().getExtras().getString("userName");
//AppParams.DEMO = getIntent().getExtras().getBoolean("demo");
if(AppParams.DEMO)
{
getAllVehicle().add(new Vehicle(101, "101", 101, "101", 101, 101, 101, 0));
getAllVehicle().add(new Vehicle(102, "102", 102, "102", 102, 102, 102, 0));
getAllVehicle().add(new Vehicle(103, "103", 103, "Ambulance", 78, 103, 103, 0));
getAllVehicle().add(new Vehicle(104, "104", 104, "104", 104, 104, 104, 0));
getAllVehicle().add(new Vehicle(105, "105", 105, "Police", 105, 105, 105, 0));
getAllVehicle().add(new Vehicle(106, "106", 106, "Mike", 106, 106, 106, 0));
getAllVehicle().add(new Vehicle(107, "107", 107, "Rob", 107, 107, 107, 0));
getAllVehicle().add(new Vehicle(108, "108", 108, "Ben", 108, 108, 108, 0));
getAllVehicle().add(new Vehicle(109, "109", 109, "Taxi_3", 109, 109, 109, 0));
getAllVehicle().add(new Vehicle(110, "110", 110, "Pam", 110, 110, 110, 0));
listSMS = new ArrayList<SMS>();
listSMS.add(new SMS(1, 1, 1324016412, "Only one left", 101, 0));
listSMS.add(new SMS(2, 1, 1328061660, "Thanks", 0, 105));
listSMS.add(new SMS(3, 1, 1328060100, "i'm at the train station", 0, 102));
listSMS.add(new SMS(4, 1, 1121016818, "I'll be right there", 0, 103));
for(Vehicle veh: getAllVehicle())
{
SuperVehicle tmpSuper = new SuperVehicle(veh.sc_id,veh.imei,veh.lp, veh.name, veh.driver_id, veh.time_route, veh.GPS_reporting_interval, veh.is_stolen);
if (veh.sc_id == 101)
tmpSuper.SetDataFromLastPos(30.1038811728358, -95.6229997426271, Calendar.getInstance().getTimeInMillis(), 47, "800-804 Sandy Ln, Tomball, TX 77375, USA", true);
else if (veh.sc_id == 102)
tmpSuper.SetDataFromLastPos(30.1035, -95.623, Calendar.getInstance().getTimeInMillis(), 33, "9th St", true);
else if (veh.sc_id == 103)
tmpSuper.SetDataFromLastPos(42.320986,-85.183182, Calendar.getInstance().getTimeInMillis(), 61, "Battle Creek, MI, USA", true);
else if (veh.sc_id == 104)
tmpSuper.SetDataFromLastPos(42.337166,-83.049345, Calendar.getInstance().getTimeInMillis(), 47, "Downtown Detroit, USA", true);
else if (veh.sc_id == 105)
tmpSuper.SetDataFromLastPos(42.382514,-83.373184, Calendar.getInstance().getTimeInMillis(), 47, "Livonia, MI, Detroit, USA", true);
else if (veh.sc_id == 106)
tmpSuper.SetDataFromLastPos(41.741667,-87.972336, Calendar.getInstance().getTimeInMillis(), 47, "Darien, IL , USA", true);
else if (veh.sc_id == 107)
tmpSuper.SetDataFromLastPos(41.739329,-87.97225, Calendar.getInstance().getTimeInMillis(), 47, "8205 S Cass Ave , USA", true);
else if (veh.sc_id == 108)
tmpSuper.SetDataFromLastPos(41.739105,-87.97298, Calendar.getInstance().getTimeInMillis(), 47, "8201-8205 S Cass Ave , USA", true);
else if (veh.sc_id == 109)
tmpSuper.SetDataFromLastPos(41.752521,-87.944655, Calendar.getInstance().getTimeInMillis(), 47, "Kingery Hwy, Willowbrook, IL 60527, USA", true);
else if (veh.sc_id == 110)
tmpSuper.SetDataFromLastPos(41.748391,-87.933497, Calendar.getInstance().getTimeInMillis(), 47, "Historic U.S. 66, Burr Ridge, IL 60527 , USA", true);
getSuperVehHash().put(Long.valueOf(veh.imei), tmpSuper);
getVehHashByScId().put(veh.sc_id, veh);
}
}
SM.Debug("Loged user:" + AppParams.USERNAME + " | ID: " + AppParams.USERID);
// do not dim the display
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// get NewMessage Visual Element
layoutNewMessage = (RelativeLayout) findViewById(R.id.layoutNewMessage);
textViewNMMessage = (TextView) findViewById(R.id.textViewNMMessage);
textViewNMFrom = (TextView) findViewById(R.id.textViewNMFrom);
slideTabsText = (TextView) findViewById(R.id.slideTabsText);
imageViewPopUp = (ImageView) findViewById(R.id.imageViewPopUp);
imageViewClose = (ImageView) findViewById(R.id.imageViewClose);
if(AppParams.DEMO)
imageViewClose.setVisibility(View.VISIBLE);
tabHost = getTabHost(); // The activity TabHost
tabHost.setTag("Tab Panel");
tabWidget = findViewById(android.R.id.tabs);
tabWidget.setVisibility(View.GONE);
intent = new Intent[8];
tabspecs = new TabSpec[8];
// add live tab
try
{
intent[0] = new Intent(context, LiveActivity.class);
tabspecs[0] = tabHost.newTabSpec("Live")
.setIndicator("Live", res.getDrawable(R.drawable.ic_tab_live_selected))
.setContent(intent[0]);
}
catch(NoClassDefFoundError e)
{
// exception when GoogleApi does not exist
intent[0] = new Intent(context, AbstractEmptyActivity.class);
tabspecs[0] = tabHost.newTabSpec("Live")
.setIndicator("Live", res.getDrawable(R.drawable.ic_tab_live_selected))
.setContent(intent[0]);
}
// add text tab
intent[1] = new Intent(context, MessagesActivity.class);
tabspecs[1] = tabHost.newTabSpec("Text")
.setIndicator("Text", res.getDrawable(R.drawable.ic_tab_text_selected))
.setContent(intent[1]);
// add radio tab
intent[2] = new Intent(context, RadioActivity.class);
tabspecs[2] = tabHost.newTabSpec("Radio")
.setIndicator("Radio", res.getDrawable(R.drawable.ic_tab_radio_selected))
.setContent(intent[2]);
// add recordings tab
intent[3] = new Intent(context, RecordingsActivity.class);
tabspecs[3] = tabHost.newTabSpec("Recordings")
.setIndicator("Recordings", res.getDrawable(R.drawable.ic_tab_recording_selected))
.setContent(intent[3]);
// add alarms tab
intent[4] = new Intent(context, AlarmActivity.class);
tabspecs[4] = tabHost.newTabSpec("Alarms")
.setIndicator("Alarms", res.getDrawable(R.drawable.ic_tab_alarms_selected))
.setContent(intent[4]);
// add setup tab
intent[5] = new Intent(context, SetupActivity.class);
tabspecs[5] = tabHost.newTabSpec("Setup")
.setIndicator("Setup", res.getDrawable(R.drawable.ic_tab_settings_selected))
.setContent(intent[5]);
// add radio tab
intent[6] = new Intent(context, AbstractEmptyActivity.class);
tabspecs[6] = tabHost.newTabSpec("SafeMobile")
.setIndicator("SafeMobile", res.getDrawable(AppParams.DEMO ? R.drawable.icon_demo : R.mipmap.ic_launcher))
.setContent(intent[6]);
// add history tab
try
{
intent[7] = new Intent(context, HistoryActivity.class);
tabspecs[7] = tabHost.newTabSpec("History")
.setIndicator("History", res.getDrawable(R.drawable.ic_tab_history_selected))
.setContent(intent[7]);
} catch(NoClassDefFoundError e) {
// exception when GoogleApi not exists
intent[7] = new Intent(context, AbstractEmptyActivity.class);
tabspecs[7] = tabHost.newTabSpec("History")
.setIndicator("History", res.getDrawable(R.drawable.ic_tab_history_selected))
.setContent(intent[1]);
}
// add tab in tabHost
// for(int i=0;i<7;i++
for (TabSpec tab: tabspecs) {
if(tabHost != null)
tabHost.addTab(tab);
}
layoutMenu = (LinearLayout) findViewById(R.id.layoutMenu);
// get slide Menu layout image
imageViewSlideMenu = (ImageView) findViewById(R.id.imageViewSlideMenu);
// get Live Button
buttonLive = findViewById(R.id.buttonLive);
buttonLive.setOnClickListener(v -> {
if (!buttonLive.isSelected()) {
// select button
buttonLive.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonHistory.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonText.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Live");
AppParams.crtTab = AppParams.Tabs.live;
}
});
// get History Button
buttonHistory = findViewById(R.id.buttonHistory);
buttonHistory.setOnClickListener(v -> {
if (!buttonHistory.isSelected()) {
// select button
buttonHistory.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonText.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("History");
AppParams.crtTab = AppParams.Tabs.history;
}
});
// get Text Button
buttonText= findViewById(R.id.buttonText);
buttonText.setOnClickListener(v -> {
if (!buttonText.isSelected()) {
// select button
buttonText.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonHistory.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Text");
AppParams.crtTab = AppParams.Tabs.message;
if (AppParams.DEMO && messageActivity.getAllVehicle().size()== 0) {
// select button
buttonText.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonHistory.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Text");
AppParams.crtTab = AppParams.Tabs.message;
if (AppParams.DEMO && messageActivity.getAllVehicle().size()== 0) {
messageActivity.updateVehicles(getAllVehicle());
messageActivity.updateSMS(listSMS);
}
}
}
});
// get Radio Button
buttonRadio = (ImageButton) findViewById(R.id.buttonRadio);
if(NOSOUND)
buttonRadio.setVisibility(View.GONE);
buttonRadio.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!buttonRadio.isSelected())
{
// select button
buttonRadio.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonRecordings.setSelected(false);
buttonHistory.setSelected(false);
buttonSetup.setSelected(false);
buttonText.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Radio");
AppParams.crtTab = AppParams.Tabs.radio;
if(radioActivity!= null && radioActivity.allVehicle!= null && radioActivity.allVehicle.size()==0)
{
radioActivity.allVehicle = getAllVehicle();
radioActivity.UpdateVehicle();
}
}
}
});
// get Recordings Button
buttonRecordings = (ImageButton) findViewById(R.id.buttonRecording);
if(NOSOUND)
buttonRecordings.setVisibility(View.GONE);
buttonRecordings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!buttonRecordings.isSelected())
{
// select button
buttonRecordings.setSelected(true);
// deselect other buttons
buttonRadio.setSelected(false);
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonHistory.setSelected(false);
buttonSetup.setSelected(false);
buttonText.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Recordings");
AppParams.crtTab = AppParams.Tabs.recordings;
if(AppParams.DEMO && recordingsActivity!= null && recordingsActivity.allRecordings!= null && recordingsActivity.allRecordings.size() ==0 )
{
ArrayList<Recording> listRecordings = new ArrayList<Recording>();
Recording rec = new Recording();
rec.NameForDisplay = "Rob";
rec.subID = 101;
rec.endGMT = (int) Calendar.getInstance().getTime().getTime();
rec.startGMT = rec.endGMT - 2;
rec.type = 102;
listRecordings.add(rec);
rec = new Recording();
rec.NameForDisplay = "Call1 [Rob]";
rec.subID = 102;
rec.endGMT = (int) Calendar.getInstance().getTime().getTime();
rec.startGMT = rec.endGMT - 2;
rec.type = 101;
listRecordings.add(rec);
rec = new Recording();
rec.NameForDisplay = "Call2 [Rob]";
rec.subID = 101;
rec.endGMT = (int) Calendar.getInstance().getTime().getTime();
rec.startGMT = rec.endGMT - 3;
listRecordings.add(rec);
rec.type = 103;
recordingsActivity.UpdateRecordings(listRecordings);
}
}
}
});
// get Alarm Button
buttonAlarms = (ImageButton) findViewById(R.id.buttonAlarms);
buttonAlarms.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!buttonAlarms.isSelected())
{
// select button
buttonAlarms.setSelected(true);
// deselect other buttons
buttonHistory.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonText.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Alarms");
AppParams.crtTab = AppParams.Tabs.alarms;
if(AppParams.DEMO && alarmActivity!=null && alarmActivity.getAllAlarms() != null && alarmActivity.getAllAlarms().size() ==0 )
{
ArrayList<Alarm> listAlarms = new ArrayList<Alarm>();
Alarm alarm = new Alarm();
alarm.ack = 0;
alarm.unitName = "Police";
alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 5210;
alarm.sc_id = 105;
alarm.typestr = "Speeding";
listAlarms.add(alarm);
alarm = new Alarm();
alarm.ack = 0;
alarm.unitName = "101";
alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 3315;
alarm.sc_id = 101;
alarm.typestr = "Geofence";
listAlarms.add(alarm);
alarm = new Alarm();
alarm.ack = 0;
alarm.unitName = "101";
alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 1900;
alarm.sc_id = 101;
alarm.typestr = "Telemetry";
listAlarms.add(alarm);
alarm = new Alarm();
alarm.ack = 0;
alarm.unitName = "Taxi_3";
alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 1521;
alarm.sc_id = 109;
alarm.typestr = "Landmark";
listAlarms.add(alarm);
alarm = new Alarm();
alarm.ack = 0;
alarm.unitName = "Ben";
alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 521;
alarm.sc_id = 108;
alarm.typestr = "Emergency";
listAlarms.add(alarm);
alarmActivity.updateAlarms(listAlarms);
}
}
}
});
//get Setup button
buttonSetup = (ImageButton) findViewById(R.id.buttonSetup);
buttonSetup.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!buttonSetup.isSelected())
{
// select button
buttonSetup.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonHistory.setSelected(false);
buttonText.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Setup");
AppParams.crtTab = AppParams.Tabs.setup;
}
}
});
// get About Button
buttonLogo = findViewById(R.id.buttonLogo);
buttonLogo.setOnClickListener(v -> {
// create dialog
final Dialog dialog = new Dialog(context);
dialog.setTitle(AppParams.DEMO ? getString(R.string.app_name_demo) : getString(R.string.app_name));
dialog.setContentView(R.layout.dialog);
ImageView image = dialog.findViewById(R.id.image);
image.setImageResource(AppParams.DEMO ? R.drawable.icon_demo : R.mipmap.ic_launcher);
TextView text = dialog.findViewById(R.id.text);
TextView text2 = dialog.findViewById(R.id.text2);
text.setText(getString(R.string.version) + "1.0.8");
text2.setText(getString(R.string.email) + ": support@safemobile.com");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
});
imageViewClose.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
layoutNewMessage.setVisibility(View.GONE);
return false;
}
});
// set Click event for NewMessageLayout
layoutNewMessage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(tcp!=null && tcp.isConnectionUP && inCall == false)
{
if(slideTabsText.getText().toString().equals(getString(R.string.newMessage)))
viewReceived(AppParams.messageNotif);
else if(slideTabsText.getText().toString().equals(getString(R.string.newAlarm)))
viewReceived(AppParams.alertNotif);
else if(slideTabsText.getText().toString().equals(getString(R.string.newPoll)))
viewReceived(AppParams.pollNotif);
}
else if (AppParams.DEMO)
{
if(slideTabsText.getText().toString().equals(getString(R.string.newMessage)))
viewReceived(AppParams.messageNotif);
else if(slideTabsText.getText().toString().equals(getString(R.string.newPoll)))
viewReceived(AppParams.pollNotif);
}
layoutNewMessage.clearAnimation();
layoutNewMessage.setVisibility(View.INVISIBLE);
/*
String currentActivityId = getLocalActivityManager().getCurrentId();
SM.Debug(" curent activityID: " +currentActivityId);
while(currentActivityId == null)
{
try {
Thread.sleep(100);
currentActivityId = getLocalActivityManager().getCurrentId();
SM.Debug(" curent activityID: " +currentActivityId);
} catch (InterruptedException e) {
SM.Debug(e.toString());
}
}
Activity currentActivity = getLocalActivityManager().getActivity(currentActivityId);
//list for SMS
if(currentActivity instanceof MessagesActivity)
{
// run update showSMS4unit(int scId) form MessageActivity
((MessagesActivity)currentActivity).showSMS4unit(getVehicle4Imei(imei).scId);
}
*/
}
});
// if RADIOPAD hide buttons
/*
// alarm animation
Animation a = AnimationUtils.loadAnimation(this, R.anim.alpha);
a.reset();
textViewAlarm.clearAnimation();
textViewAlarm.startAnimation(a);
imageViewAlarm.clearAnimation();
imageViewAlarm.startAnimation(a);
*/
layoutSlideMenu = (LinearLayout) findViewById(R.id.layoutSlideMenu);
layoutSlideMenu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(isMenuVisible)
{
// hide Menu
layoutMenu.setVisibility(View.GONE);
// change image
imageViewSlideMenu.setImageResource(R.drawable.arrow_left);
// set visibile false
isMenuVisible = false;
}
else
{
// hide Menu
layoutMenu.setVisibility(View.VISIBLE);
// change image
imageViewSlideMenu.setImageResource(R.drawable.arrow_right);
// set visibile true
isMenuVisible = true;
}
}
});
// got to tab
tabHost.setCurrentTabByTag("Radio");
tabHost.setCurrentTabByTag("Live");
buttonLive.setSelected(true);
AppParams.crtTab = AppParams.Tabs.live;
//start TCP timer
tcpTimer = new Timer();
tcpTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, AppParams.DEMO ? 3000 : 1000, 3000);
// hide buttons if safenet
if (AppParams.theme == AppParams.Theme.SAFENET) {
buttonRadio.setVisibility(View.GONE);
buttonRecordings.setVisibility(View.GONE);
}
if (AppParams.DEMO && liveActivity != null) {
liveActivity.vehiclesReceived(getAllVehicle());
demoPositionsList();
}
if (!AppParams.DEMO) {
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
// init tcp
TCPinit();
}
}, 100);
}
// Notification Click Filter
IntentFilter intentAlertFilter = new IntentFilter(NotificationActivity.NOTIFICATION_ALERT_INTENT);
IntentFilter intentMessageFilter = new IntentFilter(NotificationActivity.NOTIFICATION_MESSAGE_INTENT);
IntentFilter intentPollFilter = new IntentFilter(NotificationActivity.NOTIFICATION_POLL_INTENT);
this.registerReceiver(mReceiver, intentAlertFilter);
this.registerReceiver(mReceiver, intentMessageFilter);
this.registerReceiver(mReceiver, intentPollFilter);
/** Create Service and bind to it */
getApplicationContext().bindService(new Intent(this, TCPService.class), serviceConnection, Context.BIND_AUTO_CREATE);
// set tab
/*
tabHost.setCurrentTabByTag("Alarms");
AppParams.crtTab = AppParams.Tabs.setup;
//*/
}
/** Broadcast Received for notifications */
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// get notification click action
if (action.equals(NotificationActivity.NOTIFICATION_MESSAGE_INTENT) && tabHost.getCurrentTab() != 2)
viewReceived(AppParams.messageNotif);
else if (action.equals(NotificationActivity.NOTIFICATION_ALERT_INTENT) && tabHost.getCurrentTab() != 2)
viewReceived(AppParams.alertNotif);
else if (action.equals(NotificationActivity.NOTIFICATION_POLL_INTENT) && tabHost.getCurrentTab() != 2)
viewReceived(AppParams.pollNotif);
}
};
private void viewReceived(int icon)
{
switch(icon)
{
case AppParams.messageNotif :
// hide NewMessage Layout
layoutNewMessage.setVisibility(View.GONE);
// select button
buttonText.setSelected(true);
// deselect other buttons
buttonAlarms.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonHistory.setSelected(false);
// select text tab
tabHost.setCurrentTabByTag("Text");
AppParams.crtTab = AppParams.Tabs.message;
messageActivity.setScId(getVehicle4Imei(getImei()).sc_id);
messageActivity.LASTMESSAGES = false;
messageActivity.getLastSMS();
// disable notification
if(mNotificationManager!=null)
mNotificationManager.cancel(R.drawable.message);
break;
case AppParams.alertNotif:
// hide NewMessage Layout
layoutNewMessage.setVisibility(View.GONE);
// select button
buttonAlarms.setSelected(true);
// deselect other buttons
buttonText.setSelected(false);
buttonLive.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonHistory.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("Alarms");
AppParams.crtTab = AppParams.Tabs.alarms;
// disable notification
if(mNotificationManager!=null)
mNotificationManager.cancel(R.drawable.alert);
break;
case R.drawable.poll:
// hide NewMessage Layout
layoutNewMessage.setVisibility(View.GONE);
// select button
buttonLive.setSelected(true);
// deselect other buttons
buttonText.setSelected(false);
buttonAlarms.setSelected(false);
buttonRadio.setSelected(false);
buttonRecordings.setSelected(false);
buttonSetup.setSelected(false);
buttonHistory.setSelected(false);
// select tab
tabHost.setCurrentTabByTag("live");
AppParams.crtTab = AppParams.Tabs.live;
// disable notification
if(mNotificationManager!=null)
mNotificationManager.cancel(R.drawable.poll);
break;
}
}
public void demoPositionsList() {
AssetManager assetManager = res.getAssets();
SM.Debug("TRY 2 OPEN demo_positions.txt");
InputStream input;
try {
input = assetManager.open("demo_positions.txt");
InputStreamReader inputreader = new InputStreamReader(input);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while ((line = buffreader.readLine()) != null) {
String[] posi = line.split("#");
HistPos gps = new HistPos();
gps.lat = Double.parseDouble(posi[1]);
gps.lng = Double.parseDouble(posi[2]);
gps.speed = Integer.parseInt(posi[3]);
gps.Address = posi[4];
demoPositions.add(gps);
}
HistPosmsg msg = new HistPosmsg(new TCPmsg(new char[]{}));
demoPositions = msg.CalcHeadingForArray(demoPositions);
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void onStart()
{
super.onStart();
/*
SM.Debug("##### onSTART #####");
if(FIRST)
{
// start thread to add listener
SM.Debug("##### START initTCPRUN");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myHandler.post(initTCPRUN);
}
}).start();
FIRST = false;
}
*/
}
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
//Toast.makeText(context, "Fucking Service is disconnected", 1000).show();
SM.Debug("Service is disconnected");
isBound = false;
myService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//Toast.makeText(context, "Fucking Service is connected", 2000).show();
SM.Debug("Service is connected");
TCPBinder binder = (TCPBinder) service;
myService = binder.getService();
isBound = true;
tcpParser();
}
};
@Override
public void whenBackPressed(AppParams.ActivityResult result)
{
// close TCP
/*
if(tcp!= null)
{
tcp.Stop();
tcpParser.Stop();
}*/
if(tcpTimer!=null)
{
tcpTimer.cancel();
tcpTimer.purge();
tcpTimer = null;
}
if(radioActivity.audioThread != null)
{
Thread moribund = radioActivity.audioThread;
radioActivity.audioThread = null;
moribund.interrupt();
}
if(mReceiver!=null)
this.unregisterReceiver(mReceiver);
// unbound from tcp service
if (isBound) {
getApplicationContext().unbindService(serviceConnection);
isBound = false;
}
// cancel new message notification if any
if(mNotificationManager!=null) {
mNotificationManager.cancel(R.drawable.message);
mNotificationManager.cancel(R.drawable.alert);
mNotificationManager.cancel(R.drawable.poll);
}
getIntent().putExtra("result", result);
setResult(RESULT_OK, getIntent()); //-> used for exit
finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
@Override
public void changeLanguage()
{
// recreate UI
Locale locale = new Locale(AppParams.LANGUAGETMP);
Locale.setDefault(locale);
android.content.res.Configuration configuration = new android.content.res.Configuration();
configuration.locale = locale;
getBaseContext().getResources().updateConfiguration(configuration,
getBaseContext().getResources().getDisplayMetrics());
// change UI in Live Activity
// if(liveActivity != null)
//liveActivity.onCreate(liveActivity.savedInstanceState);
if(historyActivity!=null)
//historyActivity.onCreate(historyActivity.savedInstanceState);
// change UI for RadioActivity and MessageActivity
if(radioActivity!=null)
radioActivity.onCreate(radioActivity.savedInstanceState);
if(messageActivity!=null)
messageActivity.onCreate(messageActivity.getSavedInstanceState());
if(recordingsActivity!=null)
recordingsActivity.onCreate(recordingsActivity.savedInstanceState);
if(alarmActivity!=null)
alarmActivity.onCreate(alarmActivity.getSavedInstanceState());
}
// Create runnable for posting
public final Runnable initTCPRUN = new Runnable() {
public void run() {
//SM.Debug("##### GetVehicles()");
// get all vehicles
//getVehs();
}
};
//timer stuff
private void TimerMethod()
{
if(!AppParams.DEMO)
this.runOnUiThread(Timer_Tick);
else
// build TimerMethod for demo
this.runOnUiThread(Timer_TickDemo);
}
private Runnable Timer_TickDemo = new Runnable() {
public void run() {
if(AppParams.crtTab == AppParams.Tabs.live)
{
if(getSuperVehHash().containsKey((long)101))
{
HistPos crtPos = demoPositions.get(demoPosition++ % demoPositions.size());
SM.Debug("########### UPDATE");
int sc_id = demoPosition%3 == 0 ? 101:102;
getSuperVehHash().get((long)sc_id).SetNewPosition(crtPos.lat, crtPos.lng, Calendar.getInstance().getTime().getTime(), crtPos.speed);
liveActivity.refreshMap();
}
}
}
};
@Override
public void updateDemoPosition()
{
HistPos crtPos = demoPositions.get(demoPosition++ % demoPositions.size());
SM.Debug("########### UPDATE");
int sc_id = Integer.parseInt(getImei());
getSuperVehHash().get((long)sc_id).SetNewPosition(crtPos.lat + 0.0002, crtPos.lng + 0.0002, Calendar.getInstance().getTime().getTime(), crtPos.speed+2);
setMess("Lat:" + String.format("%5f", crtPos.lat + 0.0002) + ", Lng:" + String.format("%5f", crtPos.lng + 0.0002));
liveActivity.refreshMap();
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
if(tcp != null)
{
if(!tcp.isConnectionUP)
{
//SM.Debug("TCP connection with:"+tcp.serverHostname + " is DOWN!!!");
// set TextViews
slideTabsText.setText(getString(R.string.connectionError));
textViewNMFrom.setText(getString(R.string.tcpConnection));
textViewNMMessage.setText("");
imageViewPopUp.setImageResource(R.drawable.error);
// show layout
layoutNewMessage.setVisibility(View.VISIBLE);
// hide close button
imageViewClose.setVisibility(View.INVISIBLE);
try
{
if(lastTCPstatus)
radioActivity.UpdateEnableDisableButtons("offline");
}
catch(Exception ex)
{
SM.Debug(ex.toString());
}
}
else
{
//SM.Debug("TCP connection with:"+tcp.serverHostname + " is OKKKKK!!!");
/*
if(layoutNewMessage.getVisibility() == View.VISIBLE)
{
switch (activePopupType)
{
case SMS:
imageViewPopUp.setImageResource(R.drawable.message);
break;
case ALARM:
imageViewPopUp.setImageResource(R.drawable.siren_on);
break;
case POLL:
imageViewPopUp.setImageResource(R.drawable.poll);
break;
default:
imageViewPopUp.setImageResource(R.drawable.error);
break;
}
*/
// reset image to message
//imageViewPopUp.setImageResource(R.drawable.message);
// hide layout
//if(layoutNewMessage.getVisibility() == View.VISIBLE)
// when connection becomes true after it was false
if(getAllVehicle().size() == 0)
//connectTask.doIn(OperationCodes.GetVehicles, new Object[] {AppParams.USERID});
new ConnectTask().execute(new String[] {OperationCodes.GetVehicles + "", AppParams.USERID + ""});
//getVehicles(AppParams.USERID);
if(radioActivity != null && AppParams.listRadios.size() == 0)
new ConnectTask().execute(new String[] {OperationCodes.GetRadiosList + ""});
//connectTask.execute("3#getRadiosList");
/*
new Thread(new Runnable() {
public void run()
{
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//GetRadioStatus(crtRadio.GW_ID, crtRadio.ID); // get radio status
}
}).start();
*/
layoutNewMessage.setVisibility(View.INVISIBLE);
}
// remember this tcp connection status
lastTCPstatus = tcp.isConnectionUP;
}
}
};
// hide tabs
public void hideTabs()
{
//tabWidget.setVisibility( View.GONE );
layoutMenu.setVisibility(View.GONE);
}
// show tabs
public void showTabs()
{
//tabWidget.setVisibility( View.VISIBLE );
layoutMenu.setVisibility(View.VISIBLE);
}
// TCP part
public void TCPinit()
{
SM.Debug("#### TCP INIT ####");
new ConnectTask().execute(new String[] {OperationCodes.TCP_CONNECTION_REQ + ""});
//connectTask.execute(new Object[] {OperationCodes.GetTCPConnection});
}
public void tcpParser()
{
SM.Debug("TCP PARSER ", "connectParserTask().execute && myService is : " + (myService == null ? " null " : " not null"));
if(myService != null) {
tcpParser = myService.getTCPmsgParser();
tcp = myService.getTCPConnection();
}
SM.Debug("connectParserTask","tcpParser is : " + (tcpParser == null ? "null" : "not null"));
// add TCPParserListener
if(tcpParser!=null)
{
SM.Debug("## tcpParser != null ", "#### call tcpParserListener(") ;
tcpParserListener();
}
//new connectParserTask().execute("");
}
public void tcpParserListener()
{
SM.Debug("ADDING TCP Listener", "NEW TCP Listener");
//manager.getActivity(id);
tcpParser.clearITCPListeners();
tcpParser.addTCPListener(new ITCPListener() {
public void onLoginReceived(TCPEvent event) { }
public void onGPSReceived(TCPEvent event) {
SM.Debug("Got GPS message");
TCPmsg msg= event.msg();
//SM.Debug("Got GPS message :" + msg.allData);
GPSmsg GPSPos= new GPSmsg(msg);
//SM.Debug("Got new GPS pos data:" + GPSPos.data);
if (getSuperVehHash().get(GPSPos.gpsValue.imei) != null) {
getSuperVehHash().get(GPSPos.gpsValue.imei).SetNewPosition(GPSPos.gpsValue.lat, GPSPos.gpsValue.lng, GPSPos.gpsValue.timeGMT, GPSPos.gpsValue.speed);
// if (getSuperVehHash().get(GPSPos.gpsValue.imei).needUpdate) {
//list for live
if (AppParams.crtTab == AppParams.Tabs.live) {
//SM.Debug("+++++ duda +++++");
SM.Debug("currentActivity instanceof LiveActivity");
try {
if(liveActivity != null)
liveActivity.refreshMap();
} catch (Exception ex) {
SM.Debug("Error load hash:"+ex.toString());
}
}
// }
}
}
@Override
public void onPollReceived(TCPEvent event) {
SM.Debug("Got POLL GPS message");
TCPmsg msg= event.msg();
GPSmsg GPSPos= new GPSmsg(msg);
setImei(Long.toString(GPSPos.gpsValue.imei));
setMess("LAT:"+Double.toString(GPSPos.gpsValue.lat)+" LNG:"+Double.toString(GPSPos.gpsValue.lng));
SM.Debug("Got new Poll pos data:" + GPSPos.data);
if(getSuperVehHash().get(GPSPos.gpsValue.imei) != null) {
((SuperVehicle) getSuperVehHash().get(GPSPos.gpsValue.imei)).SetNewPosition(GPSPos.gpsValue.lat, GPSPos.gpsValue.lng, GPSPos.gpsValue.timeGMT, GPSPos.gpsValue.speed);
//if is not check i need to force check to put on the map
Boolean forceChecked =false;
if (!getSuperVehHash().get(GPSPos.gpsValue.imei).needUpdate) {
getSuperVehHash().get(GPSPos.gpsValue.imei).needUpdate =true;
forceChecked =true;
}
//back to standard procedures to put on the map
if(getSuperVehHash().get(GPSPos.gpsValue.imei).needUpdate)
{
//list for live
if(AppParams.crtTab == AppParams.Tabs.live)
{
//SM.Debug("+++++ duda +++++");
//SM.Debug("currentActivity instanceof LiveActivity");
try
{
int x = 0;
if (forceChecked)
{
for (Vehicle veh : getAllVehicle())
{
if (veh.imei.compareTo(Long.toString(GPSPos.gpsValue.imei))==0) break;
x++;
}
}
else x = -1;
if(liveActivity!=null)
{
if (x!= getAllVehicle().size())
liveActivity.pollReceived(x ,GPSPos.gpsValue.lat,GPSPos.gpsValue.lng);
else
liveActivity.pollReceived(-1 ,GPSPos.gpsValue.lat,GPSPos.gpsValue.lng);
}
}
catch (Exception ex)
{
SM.Debug("Error load hash:"+ex.toString());
}
}
}
}
myHandler.post(UpdateResultsPoll);
}
public void onSMSReceived(TCPEvent event)
{
try{
TCPmsg msg= event.msg();
SMSmsg sms= new SMSmsg(msg);
SM.Debug("am primit lista cu primele SMSuri");
//list for SMS
if(AppParams.crtTab == AppParams.Tabs.message)
{
//SM.Debug("currentActivity instanceof MessagesActivity - newSMS");
if(messageActivity != null)
messageActivity.updateSMS(sms.smsList);
}
}
catch(Exception ex)
{
SM.Debug("Error on smsRecived:"+ex.toString());
}
}
public void onVehiclesReceived(TCPEvent event) {
//SM.Debug("#########################","###########################");
TCPmsg msg= event.msg();
VehMSG vMSG = new VehMSG(msg);
SM.Debug("### Vehicle Received ###","Received " + vMSG.vehList.size() + " vehicles");
//list for live
if(AppParams.crtTab == AppParams.Tabs.live)
{
//SM.Debug("+++++ duda +++++");
SM.Debug("currentActivity instanceof LiveActivity");
try
{
for(Vehicle veh:vMSG.vehList)
{
SuperVehicle tmpSuper = new SuperVehicle(veh.sc_id,veh.imei,veh.lp, veh.name, veh.driver_id, veh.time_route, veh.GPS_reporting_interval, veh.is_stolen);
getSuperVehHash().put(Long.valueOf(veh.imei), tmpSuper);
getVehHashByScId().put(veh.sc_id, veh);
}
SM.Debug(" #$############# " + getSuperVehHash().size() + " \nVEH " + vMSG.vehList.size());
}
catch (Exception ex)
{
SM.Debug("Error load hash:"+ex.toString());
}
if(liveActivity!=null)
liveActivity.vehiclesReceived(vMSG.vehList);
}
else if(firstGetVehs)
{
// set vehicles to liveActivity
liveActivity.vehiclesReceived(vMSG.vehList);
firstGetVehs = false;
}
//list for SMS
if(AppParams.crtTab == AppParams.Tabs.message)
{
SM.Debug("currentActivity instanceof MessagesActivity");
if(messageActivity != null)
messageActivity.updateVehicles(vMSG.vehList);
}
setAllVehicle(vMSG.vehList);
}
public void onLastSMSsReceived(TCPEvent event) {
try
{
TCPmsg msg= event.msg();
SMSmsg sms= new SMSmsg(msg);
SM.Debug("am primit lista cu primele SMSuri");
//list for SMS
if(AppParams.crtTab == AppParams.Tabs.message)
{
//SM.Debug("currentActivity instanceof MessagesActivity");
if(messageActivity != null)
messageActivity.updateSMS(sms.smsList);
}
}
catch (Exception ex)
{
SM.Debug("Error on lastSMSRecived:"+ex.toString());
}
}
@Override
public void onAlarmsReceived(TCPEvent event) {
TCPmsg msg= event.msg();
AlarmMSG Alarms= new AlarmMSG(msg);
SM.Debug("am primit lista cu Alarme");
//list for SMS
if(AppParams.crtTab == AppParams.Tabs.alarms)
{
SM.Debug("currentActivity instanceof AlarmActivity");
if(alarmActivity != null)
alarmActivity.updateAlarms(Alarms.alarmList);
}
}
@Override
public void onAlarmAckReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got alarmACK :" + msg.allData);
String[] tempArr =msg.data.split("#");
if (Integer.parseInt(tempArr[0])==1 && AppParams.crtTab == AppParams.Tabs.alarms)
{
if(alarmActivity != null)
alarmActivity.updateACK();
}
}
@Override
public void onSMSAckReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SMSmsg sms= new SMSmsg(msg);
SM.Debug("Got smsComfirm msg.data:" + msg.data);
if (messageActivity != null)
messageActivity.confirmSMS(sms.data, msg.seqID);
}
@Override
public void onNewSMSReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got smsNew :" + msg.allData);
String[] tempArr =msg.data.split("#");
SM.Debug("Unit imei:" + tempArr[0]);
SM.Debug("Message:" + tempArr[1]);
// change Visual Elements
setImei(tempArr[0]);
setMess(tempArr[1]);
long time = Calendar.getInstance().getTimeInMillis() / 1000;
try {
// get time from the last received sms and divide it to 1000 to convert it to seconds
time = Long.parseLong(msg.seqID.replace('.', '#').split("#")[1]) / 1000 - 100;
}
catch(Exception ex) {
}
// if tab is not TextTab
if(tabHost.getCurrentTab() != 2) {
myHandler.post(UpdateResults);
//mHandler.dispatchMessage(new Message());
} else
myHandler.post(() -> {
// create Notification
createNotification(AppParams.messageNotif);
});
//list for SMS
if(AppParams.crtTab == AppParams.Tabs.message && messageActivity!= null) {
SM.Debug("currentActivity instanceof MessagesActivity - newSMS | " + tempArr[0] + " | " + tempArr[1]);
messageActivity.newSMS(tempArr[0], tempArr[1], time);
}
}
@Override
public void onRecordingPlayReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got PlayRec :" + msg.allData);
if(NOSOUND)
{
//String[] tempArr =msg.data.split("#");
//SM.Debug("Unit imei:" + tempArr[0]);
SM.Debug("Recording Play file ID:" + msg.data);
//list for SMS
if(AppParams.crtTab == AppParams.Tabs.recordings)
{
String tmp = msg.data.replace("#", "");
try {
long id = Long.parseLong(tmp);
if(recordingsActivity != null)
recordingsActivity.PlayRecording(id);
}
catch(Exception ex) {
SM.Exception(ex.toString());
}
}
}
}
@Override
public void onLastPositionsReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got last pos");
LastPosmsg lastPos= new LastPosmsg(msg);
for(LastPos posMsg: lastPos.PosList) {
if(getSuperVehHash().get(posMsg.imei) != null)
getSuperVehHash().get(posMsg.imei).SetDataFromLastPos(posMsg.lat, posMsg.lng, posMsg.timeGMT, posMsg.speed, posMsg.Address, posMsg.isON);
}
}
@Override
public void onHistoryPositionsCountReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got POS Count");
HistCountmsg histcount= new HistCountmsg(msg);
SM.Debug("Message Count:"+histcount.histcountValue.count);
if (histcount.histcountValue.count>=2000) {
//list for live
if(AppParams.crtTab == AppParams.Tabs.history) {
SM.Debug("currentActivity instanceof HistoryActivity");
try {
if(historyActivity != null) {
historyActivity.UpdateCancel();
historyActivity.UpdateUnableDisp();
}
} catch (Exception ex) {
SM.Debug("Error load hash:"+ ex);
}
}
}
}
@Override
public void onHistoryPositionsReceived(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got HistoryPos :" + msg.allData);
if (!dropAllData) {
HistPosmsg tmpHist= new HistPosmsg(msg);
Boolean SendDataToMap =true;
try {
for (HistPos obj : tmpHist.PosList)
HistPosList.add(obj);
SM.Debug("tmpHist seqID:"+tmpHist.seqID);
//
int pos = Integer.parseInt(tmpHist.seqID.substring(0,tmpHist.seqID.indexOf('.')));
int all = Integer.parseInt(tmpHist.seqID.substring(tmpHist.seqID.indexOf('.') + 1));
if (all != 0) {
if (firstHistData) {
try {
for(int i=0;i<all;i++)
HistMsgList.add(false);
} catch (Exception e) {
SM.Debug("Error on init hashTable:"+ e);
}
firstHistData =false;
}
HistMsgList.set(pos-1, true);
for (int i = 0; i < all; i++) {
if (!HistMsgList.get(i)) {
SendDataToMap =false;
break;
}
}
} else
SendDataToMap =true;
} catch (Exception e) {
SM.Debug("Error on parse: "+ e);
}
if (SendDataToMap) {
Collections.sort(HistPosList, (Comparator<Object>) (o1, o2) -> {
HistPos p1 = (HistPos) o1;
HistPos p2 = (HistPos) o2;
if (p1.timeGMT < p2.timeGMT)
return -1;
else if (p1.timeGMT == p2.timeGMT)
return 0;
else
return 1;
});
//list for live
if (AppParams.crtTab == AppParams.Tabs.history) {
try {
if(historyActivity != null) {
// cancel last update
historyActivity.UpdateCancel();
Thread.sleep(101);
if (HistPosList.size() < 2000) {
if (HistPosList.size() == 1 && HistPosList.get(0).timeGMT == 0)
;// do nothing is not data message
else
historyActivity.UpdateNrPos(HistPosList.size());
Thread.sleep(100);
historyActivity.UpdateMap();
} else
historyActivity.UpdateUnableDisp(); // update with more than 200 points
}
}
catch (Exception ex) {
SM.Debug("Error load hash: "+ ex);
}
}
SM.Debug("Got HistPost msg.data: " + msg.data);
}
} else
SM.Debug("Drop history data");
}
@Override
public void onRadioMsgReceived(TCPEvent event) {
SM.Debug("#### RadioMsgRecv");
TCPmsg msg= event.msg();
RadioMSG rmsg = new RadioMSG(msg);
if (!NOSOUND) {
// update Zone and Channel
if (radioActivity != null && rmsg.zac != null) {
// update Zone and Channel in the allRadio List
for (RadioGW radio: allRadios) {
if (radio.GW_ID == rmsg.zac.gwID && radio.ID == rmsg.zac.rgwID) {
radio.lastZoneNr = rmsg.zac.zoneNr;
radio.lastChannelNr = rmsg.zac.channelNr;
}
}
AppParams.crtZoneAndChannel = rmsg.zac;
notifyBroadcast(OperationCodes.CHANNEL_BRDCST+"");
SM.Debug("Received from Apps -> UpdateZoneCH(" + rmsg.zac.rgwID + "," + rmsg.zac.gwID + "," + rmsg.zac.zoneNr + "," + rmsg.zac.channelNr + ")");
}
//list for SMS
if (AppParams.crtTab == AppParams.Tabs.radio) {
SM.Debug("#### RadioActivity");
// set crt activity to Radio
crtActivity = RADIO;
SM.Debug("## " + (rmsg.RadioGWList!=null? "RadioGWList" + rmsg.RadioGWList.size() : "RadioGWList = null"));
SM.Debug("## " + (rmsg.zac!=null? "zac" + rmsg.zac : "zac = null"));
SM.Debug("## " + (rmsg.rStatus!=null? "rStatus" + rmsg.rStatus : "rStatus = null"));
if (radioActivity != null && rmsg.RadioGWList != null) {
radioActivity.UpdateRadios(rmsg.RadioGWList);
SM.Debug("Received from Apps -> UpdateRadios( count:" + rmsg.RadioGWList.size() + ")");
}
if (radioActivity != null &&rmsg.rStatus != null) {
// update status in the crtRadio List
for (RadioGW radio : allRadios) {
if (radio.GW_ID == rmsg.rStatus.gwID && radio.ID == rmsg.rStatus.rgwID)
radio.isOnline = rmsg.rStatus.status == 1;
}
SM.Debug("Received from Apps -> UpdateRadioStatus(" + rmsg.rStatus.rgwID + "," + rmsg.rStatus.gwID + "," + rmsg.rStatus.status+ ")");
if ((crtRadio != null)&&(crtRadio.GW_ID == rmsg.rStatus.gwID)&&(crtRadio.ID == rmsg.rStatus.rgwID))
radioActivity.UpdateRadioStatus(rmsg.rStatus.status);
}
//incCall
if (radioActivity != null && rmsg.incCall !=null) {
SM.Debug("Received from Apps -> UpdateBroadcastCall(" + rmsg.incCall.Imei + "," + rmsg.incCall.callType + "," + rmsg.incCall.groupId+ ")");
// check if radioID and radioGW_ID needs to be changed
if (crtRadio != null && (crtRadio.GW_ID != rmsg.incCall.gwID || crtRadio.ID != rmsg.incCall.rgwID)) {
for(RadioGW radio: allRadios) {
if(radio.GW_ID == rmsg.incCall.gwID && radio.ID == rmsg.incCall.rgwID) {
crtRadio = radio;
notifyBroadcast(OperationCodes.RADIOID_CHANGED + "");
break;
}
}
}
if(crtRadio != null) {
if(rmsg.incCall.callStatus == 3)
inCall = false;
else
inCall = true;
radioActivity.UpdateBroadcastCall(rmsg.incCall.Imei,rmsg.incCall.callType,rmsg.incCall.groupId,rmsg.incCall.callStatus);
}
}
} else {
if (rmsg.incCall !=null) {
crtActivity = 0;
//incCall - update UI in Radio Activity
SM.Debug("Received from Apps -> UpdateBroadcastCall(" + rmsg.incCall.Imei + "," + rmsg.incCall.callType + "," + rmsg.incCall.groupId+ ")");
// check if radioID and radioGW_ID needs to be changed
if(crtRadio != null && (crtRadio.GW_ID != rmsg.incCall.gwID || crtRadio.ID != rmsg.incCall.rgwID)) {
for(RadioGW radio: allRadios) {
if(radio.GW_ID == rmsg.incCall.gwID && radio.ID == rmsg.incCall.rgwID) {
crtRadio = radio;
notifyBroadcast(OperationCodes.RADIOID_CHANGED + "");
break;
}
}
}
if (crtRadio != null) {
if(rmsg.incCall.callStatus == 3) {
inCall = false;
// update recordings list
if(AppParams.crtTab == AppParams.Tabs.recordings) {
// no recording is playing
if(recordingsActivity != null && recordingsActivity.playingPosition < 0)
getRecordings(crtRadio.GW_ID, crtRadio.ID);
}
} else
inCall = true;
radioActivity.UpdateBroadcastCall(rmsg.incCall.Imei,rmsg.incCall.callType,rmsg.incCall.groupId,rmsg.incCall.callStatus);
}
}
if(rmsg.RadioGWList!=null && radioActivity!=null)
radioActivity.UpdateRadios(rmsg.RadioGWList);
if(rmsg.zac !=null && radioActivity!=null) {
radioActivity.UpdateZoneCH(rmsg.zac.rgwID, rmsg.zac.gwID, rmsg.zac.zoneNr, rmsg.zac.channelNr);
}
if(rmsg.rStatus !=null && radioActivity!=null) {
// update status in the allRadio List
for(RadioGW radio: allRadios) {
if(radio.GW_ID == rmsg.rStatus.gwID && radio.ID == rmsg.rStatus.rgwID)
radio.isOnline = (rmsg.rStatus.status == 1 ? true : false);
}
if ((crtRadio != null)&&(crtRadio.GW_ID == rmsg.rStatus.gwID)&&(crtRadio.ID == rmsg.rStatus.rgwID))
radioActivity.UpdateRadioStatus(rmsg.rStatus.status);
}
}
// save RadioList
if (rmsg.RadioGWList!=null) {
allRadios = rmsg.RadioGWList;
if (crtRadio == null) {
crtRadio = allRadios.get(0);
SM.Debug("rmsg set 0 crtRadio GW_ID:"+crtRadio.GW_ID+" ID:"+crtRadio.ID+")");
notifyBroadcast(OperationCodes.RADIOID_CHANGED+"");
}
}
// save crt Radio ID and GW
if (rmsg.zac !=null) {
for (RadioGW radio: allRadios) {
if (radio.GW_ID == rmsg.zac.gwID && radio.ID == rmsg.zac.rgwID)
crtRadio = radio;
}
}
if (AppParams.crtTab == AppParams.Tabs.recordings) {
if (recordingsActivity != null && rmsg.RadioGWList!=null) {
SM.Debug("GetRecordings Request + crtRadio:"+ crtRadio.toString());
getRecordings(crtRadio.GW_ID, crtRadio.ID);
}
}
}
// used when a unit is enabled / disabled
if (rmsg.suStatus !=null) {
SM.Debug("ENABLED/DISABLED " + rmsg.suStatus);
notifyBroadcast(OperationCodes.UNIT_STATUS_UPDATE+"", rmsg.suStatus.imei + "#" +rmsg.suStatus.status);
} else
SM.Debug("SUStatus is null");
}
@Override
public void alarmLiveRecv(TCPEvent event) {
TCPmsg msg= event.msg();
SM.Debug("Got alarmNew :" + msg.allData);
String[] tempArr =msg.data.split("#");
SM.Debug("Unit imei:" + tempArr[0]);
String UnitIMEI =tempArr[0];
//list for SMS
if (AppParams.crtTab == AppParams.Tabs.alarms) {
SM.Debug("currentActivity instanceof AlarmActivity - NewSMS | " + tempArr[0] + " | " + tempArr[1]);
getAlarms(AppParams.USERID);
}
// if tab is not TextTab
if (tabHost.getCurrentTab() != 5) {
// change Visual Elements
setImei(UnitIMEI);
switch (msg.opCode) {
case 135: setMess("speed "+tempArr[1]);
break;
case 136: setMess("landmark "+tempArr[1]);
break;
case 137: setMess("zone "+tempArr[1]);
break;
case 138: setMess("emergency");
break;
case 140: setMess("telemetry "+ tempArr[1]);
break;
default:
setMess("emergency");
}
myHandler.post(UpdateResultsAlarm);
if ((msg.opCode==138)&&(AppParams.crtTab == AppParams.Tabs.live)) {
if(getSuperVehHash().get(Long.parseLong(UnitIMEI)) != null) {
//if is not check i need to force check to put on the map
Boolean forceChecked =false;
if (!getSuperVehHash().get(Long.parseLong(UnitIMEI)).needUpdate) {
getSuperVehHash().get(Long.parseLong(UnitIMEI)).needUpdate =true;
forceChecked =true;
}
try {
int x = 0;
if (forceChecked) {
for (Vehicle veh : getAllVehicle()) {
if (veh.imei.compareTo(UnitIMEI)==0) break;
x++;
}
} else
x = -1;
if (liveActivity != null) {
if (x!= getAllVehicle().size())
liveActivity.emergencyAlarmReceived(x , getSuperVehHash().get(Long.parseLong(UnitIMEI)).lat, getSuperVehHash().get(Long.parseLong(UnitIMEI)).lng);
else
liveActivity.emergencyAlarmReceived(-1, getSuperVehHash().get(Long.parseLong(UnitIMEI)).lat, getSuperVehHash().get(Long.parseLong(UnitIMEI)).lng);
}
} catch (Exception ex) {
SM.Debug("Error load hash: "+ ex);
}
}
}
}
}
@Override
public void onRecordingsListReceived(TCPEvent event) {
TCPmsg msg= event.msg();
RecordMSG Records= new RecordMSG(msg);
SM.Debug("am primit lista cu Recording");
//list for SMS
if (AppParams.crtTab == AppParams.Tabs.recordings) {
for(Recording rec: Records.recordList) {
// set the name to be displayed
if (rec.typeID == 1)
rec.NameForDisplay = AppParams.USERNAME;
else {
if (getSuperVehHash().get((long)rec.subID)!=null)
rec.NameForDisplay = getSuperVehHash().get((long)rec.subID).name;
}
}
// save recodings to AppParams
AppParams.recordings = Records.recordList;
// notify recordings were received
notifyBroadcast(OperationCodes.RECORDINGS_LIST_REP + "");
}
}
@Override
public void onConnectionReplyReceived(TCPEvent event) {
}
@Override
public void onContactsListReceived(TCPEvent event) {
// TODO Auto-generated method stub
}
@Override
public void onTextMessagesListReceived(TCPEvent event) {
// TODO Auto-generated method stub
}
@Override
public void onTCPConnectionDown(boolean previousConnectionWasUP) {
// execute logout
whenBackPressed(AppParams.ActivityResult.tcpDown);
// send a broadcast
notifyBroadcast(OperationCodes.TCP_CONNECTION_DOWN + "");
}
@Override
public void onTCPConnectionUp(boolean previousConnectionWasUP) {
}
@Override
public void onTCPConnectionStatusReceived(boolean isConnectionUp, boolean previuosWasConnectionUp) {
}
@Override
public void onPONGReceived() {
}
});
}
// Create runnable for posting
final Runnable UpdateResultsAlarm = () -> updateResultsAlarmInUi("realpha");
public void updateResultsAlarmInUi(String animation) {
// Back in the UI thread
// set TextViews
if(tcp!=null && !AppParams.DEMO) {
try {
activePopupType= MsgType.ALARM;
imageViewPopUp.setImageResource(R.drawable.siren_on);
slideTabsText.setText(getString(R.string.newAlarm));
if (getVehicle4Imei(getImei())!=null)
textViewNMFrom.setText(getString(R.string.from) + ": " + getVehicle4Imei(getImei()).name);
else textViewNMFrom.setText(getString(R.string.from) + ": " + getImei());
textViewNMMessage.setText("TYPE: " + getMess());
// show layout
layoutNewMessage.setVisibility(View.VISIBLE);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
if(animation.equals("realpha"))
anim = AnimationUtils.loadAnimation(this, R.anim.realpha);
anim.reset();
layoutNewMessage.clearAnimation();
layoutNewMessage.startAnimation(anim);
// create Notification
createNotification(AppParams.alertNotif);
} catch (Exception ex) {
SM.Debug("Erorr on update alarm:"+ ex);
}
}
}
// Create runnable for posting
final Runnable UpdateResultsPoll = () -> updateResultsPollInUi("realpha");
public void updateResultsPollInUi(String animation) {
// Back in the UI thread
// set TextViews
String from = "";
Vehicle fromVehicle;
if ((fromVehicle = getVehicle4Imei(getImei())) != null)
from = fromVehicle.name;
if (tcp!=null && !AppParams.DEMO) {
activePopupType =MsgType.POLL;
imageViewPopUp.setImageResource(R.drawable.poll);
slideTabsText.setText("Poll Reply");
textViewNMFrom.setText("From: " + from);
textViewNMMessage.setText(getMess());
// show layout
layoutNewMessage.setVisibility(View.VISIBLE);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
if(animation.equals("realpha"))
anim = AnimationUtils.loadAnimation(this, R.anim.realpha);
anim.reset();
layoutNewMessage.clearAnimation();
layoutNewMessage.startAnimation(anim);
} else if (AppParams.DEMO) {
activePopupType =MsgType.POLL;
imageViewPopUp.setImageResource(R.drawable.poll);
slideTabsText.setText("Poll Reply");
textViewNMFrom.setText("From: " + from);
textViewNMMessage.setText(getMess());
// show layout
layoutNewMessage.setVisibility(View.VISIBLE);
}
// create Notification
createNotification(AppParams.pollNotif);
}
// Create runnable for posting
final Runnable UpdateResults = () -> updateResultsInUi("realpha");
public void updateResultsInUi(String animation) {
// Back in the UI thread
// set TextViews
if(tcp!=null && !AppParams.DEMO) {
activePopupType = MsgType.SMS;
imageViewPopUp.setImageResource(R.drawable.message);
slideTabsText.setText("New Message");
textViewNMFrom.setText("From: " + getVehicle4Imei(getImei()).name);
textViewNMMessage.setText("MSG: " + getMess());
// show layout
layoutNewMessage.setVisibility(View.VISIBLE);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
if(animation.equals("realpha"))
anim = AnimationUtils.loadAnimation(this, R.anim.realpha);
anim.reset();
layoutNewMessage.clearAnimation();
layoutNewMessage.startAnimation(anim);
} else if(AppParams.DEMO) {
setMess("i got your sms");
activePopupType = MsgType.SMS;
imageViewPopUp.setImageResource(R.drawable.message);
slideTabsText.setText("New Message");
textViewNMFrom.setText("From: " + getVehicle4Imei(getImei()).name);
textViewNMMessage.setText("MSG: " + "i got your sms");
// show layout
layoutNewMessage.setVisibility(View.VISIBLE);
// create Notification
createNotification(AppParams.messageNotif);
}
// create Notification
createNotification(AppParams.messageNotif);
}
public void createNotification(int icon) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String tickerText = "SafeMobile Dispatch: New Message from " + getImei();
String contentTitle = "New Message from " + getImei();
String contentText = "\"" + getMess() + "\"";
Vehicle veh = getVehicle4Imei(getImei());
int icon_value = icon;
switch(icon) {
case AppParams.messageNotif:
contentText = "\"" + getMess() + "\"";
contentTitle = "New Message from " + getImei();
icon = R.drawable.message;
break;
case AppParams.pollNotif:
contentText = "\"" + getMess() + "\"" ;
contentTitle = "Poll Reply from " + (veh !=null ? getVehicle4Imei(getImei()).name : getImei());
tickerText = "SafeMobile Dispatch: Poll Reply from " + (veh !=null ? getVehicle4Imei(getImei()).name : getImei());
icon = R.drawable.poll;
break;
case AppParams.alertNotif:
String vehName = getString(R.string.from) + ": " + getImei();
if(veh!=null)
vehName = getString(R.string.from) + ": " + (veh !=null ? getVehicle4Imei(getImei()).name : getImei());
contentText ="\"" + getMess() + "\"";
contentTitle = getString(R.string.newAlarm) + vehName;
tickerText = "SafeMobile Dispatch: " + getString(R.string.newAlarm) + vehName;
icon = R.drawable.alert;
break;
}
Notification notification = new Notification(icon, tickerText, System.currentTimeMillis());
// set intent to be opened on NotificationClick
notificationIntent = new Intent(this, NotificationActivity.class);
notificationIntent.putExtra("key", icon_value);
// cancel old notification
mNotificationManager.cancel(icon);
PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ACTIVITY_RESULT, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
//notification.defaults |= Notification.DEFAULT_SOUND;
// flag that the notification will be closed when clicked
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//notification.number = notificationNr++; // used for multiple notification (different numbers)
notification.number = 1; // the same notification will be shown;
notification.tickerText = tickerText; // notification text when arrives
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.new_sms );
// add notification to the manager
mNotificationManager.notify(icon, notification);
}
// return vehicle according to imei
private Vehicle getVehicle4Imei(String imei) {
Vehicle veh = null;
for(Vehicle vehicle: getAllVehicle())
if(vehicle.imei.equals(imei))
veh = vehicle;
return veh;
}
@Override
public void enableMenuButtons(boolean enable) {
if (enable) {
buttonAlarms.setEnabled(true);
buttonHistory.setEnabled(true);
buttonLive.setEnabled(true);
buttonRecordings.setEnabled(true);
buttonText.setEnabled(true);
buttonRadio.setEnabled(true);
buttonSetup.setEnabled(true);
} else {
// disable all buttons
buttonAlarms.setEnabled(false);
buttonHistory.setEnabled(false);
buttonLive.setEnabled(false);
buttonRecordings.setEnabled(false);
buttonText.setEnabled(false);
buttonRadio.setEnabled(false);
buttonSetup.setEnabled(false);
}
}
// load settings
public void loadSettings() {
try {
// get Preferences for SafeDispatch
AppParams.prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
// 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 language
AppParams.LANGUAGE = AppParams.prefs.getString("language", "en");
SM.Debug("PORT: " + AppParams.PORT + " | IP: " + AppParams.IP);
} catch(Exception ex) {
Log.e("Exception", "loadSettings exception");
}
}
@Override
public double best_zoom(double latMax, double latMin, double lngMax, double lngMin) {
double height =400;
double width =400;
double dlat = Math.abs(latMax - latMin);
double dlon = Math.abs(lngMax - lngMin);
if(dlat == 0 && dlon == 0) {
if ((latMax == latMin)&&(latMax ==0)&&(lngMax == lngMin)&&(lngMax ==0)) return 2;
}
// Center latitude in radians
double clat = Math.PI*(latMin + latMax)/360.;
double C = 0.0000107288;
double z0 = Math.ceil(Math.log(dlat/(C*height))/0.693);
double z1 = Math.ceil(Math.log(dlon/(C*width*Math.cos(clat)))/0.693);
return (z1 > z0) ? (17-z1) : (17-z0);
}
//callType:
//101 -allcall init
//111 -allcall stop
//102 -prvcall init
//112 -prvcall stop
//103 -grpcall init
//113 -grpcall stop
public void SendPTT(int callType, int id, int gwID, int rgwid, long userID) {
if(tcp!= null) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean res = tcp.Write("0.0", "#30#"+callType+"#"+gwID+"."+rgwid+"." + id+"#"+userID+"#");
if(res){
SM.Debug("Message (SendPTT) sent to app server");
} else {
SM.Debug("Could not send message(SendPTT)!!");
}
}
}
protected class ConnectTask extends AsyncTask<String, Void, TCPhandler> {
@Override
protected TCPhandler doInBackground(String... params) {
switch(Integer.parseInt(params[0])) {
case OperationCodes.TCP_CONNECTION_REQ:
SM.Exception("TCP CONNECTION REQ!!!");
if(myService!= null) {
tcp = myService.getTCPConnection();
SM.Exception("TCP is not null!!!");
}
break;
case OperationCodes.GetVehicles:
getVehicles(Integer.parseInt(params[1]));
break;
case OperationCodes.GetRadiosList:
getRadiosList();
break;
case OperationCodes.GetLastPositions:
getLastPositions(Integer.parseInt(params[1]));
break;
case OperationCodes.GetLastSMS:
getLastSMSs(Integer.parseInt(params[1]));
break;
case OperationCodes.GetRecentSMSs:
try
{
Long.parseLong(params[2]);
}
catch (Exception ignored) {
}
getRecentSMSs(Integer.parseInt(params[1]), Long.parseLong(params[2]));
break;
case OperationCodes.SEND_TM:
sendSMS(params[1], Integer.parseInt(params[2]), params[3]);
case OperationCodes.Option4Unit:
try {
SM.Debug(params[1] + " | " + params[2] + " | " + params[3] + " | " + params[4]);
setVehicleStatus(Integer.parseInt(params[1]), Integer.parseInt(params[2]), Integer.parseInt(params[3]), Integer.parseInt(params[4]));
}
catch(Exception ex) { SM.Exception("Paramas -> setVehicleStatus","EXCeption ex " + ex.toString()); }
break;
case OperationCodes.GetAlarms:
getAlarms(Integer.parseInt(params[1]));
break;
case OperationCodes.SendAlarmAcknoledge:
sendAlarmAcknowledge(Integer.parseInt(params[1]), Integer.parseInt(params[2]), params[3]);
break;
case OperationCodes.GetHistoryPositions:
getHistoryPositions(Integer.parseInt(params[1]), Long.parseLong(params[2]), Long.parseLong(params[3]));
break;
}
return null;
}
}
@Override
public void executeNetworkStuff(String [] params) {
new ConnectTask().execute(params);
}
public class connectParserTask extends AsyncTask<String, Void, TCPhandler>
{
@Override
protected TCPhandler doInBackground(String... params) {
if(myService!= null)
tcpParser = myService.getTCPmsgParser();
SM.Debug("connectParserTask","tcpParser is : " + tcpParser == null ? "null" : "not null");
// add TCPParserListener
if(tcpParser!=null)
{
SM.Debug("## tcpParser != null ", "#### call tcpParserListener(") ;
tcpParserListener();
}
return null;
}
}
/* Display Toast messages*/
@Override
public void displayToast(final String msg) {
myHandler.post(() -> Toast.makeText(context, msg, Toast.LENGTH_SHORT).show());
}
@Override
public void setRadioActivity(AbstractRadioActivity radioActivity) {
//this.radioActivity = radioActivity;
}
@Override
public void setLiveActivity(AbstractLiveActivity liveActivity) {
this.liveActivity = liveActivity;
}
@Override
public void setMessagesActivity(AbstractMessagesActivity messageActivity) {
//this.messageActivity = messageActivity;
}
@Override
public void unregisterReceivers(BroadcastReceiver receiver) {
if(mReceiver!=null)
this.unregisterReceiver(receiver);
}
@Override
public void cancelNotification(int drawable) {
if(mNotificationManager!=null)
mNotificationManager.cancel(drawable);
}
@Override
public void stopTCP() {
if(tcp != null)
tcp.Stop();
}
@Override
public void stopTCPParser() {
if(tcpParser != null)
tcpParser.Stop();
}
@Override
public void recreateTCPConnection() {
if(!AppParams.DEMO) {
if(tcpParser!=null)
tcpParser.clearMsgList();
myHandler.post(() -> {
if(myService != null) {
myService.stopTCPConnection();
myService.recreateTCPConnection();
new ConnectTask().execute(new String[] {OperationCodes.TCP_CONNECTION_REQ + ""});
// add a new ITCPListener
tcpParser();
}
SM.Debug("RECREATE TCP","IP: " + AppParams.IP + " | Port: " + AppParams.PORT);
});
}
}
@Override
public void removeITCPListener() {
if(tcpParser != null)
tcpParser.clearITCPListeners();
}
/** send a message to be broadcasted when a specific event happens
* every listener that is registered to the broadcast will be notified of these event
* @param action The type of action which will be notified
* @param object The object which will be passed through the intent
*/
private void notifyBroadcast(String action) {
Intent intent = new Intent();
intent.setAction(action);
getBaseContext().sendBroadcast(intent);
}
// send a message to be broadcasted when a specific event happens
// every listener that is registered to the broadcast will be notified of these event
private void notifyBroadcast(String action, Object object) {
Intent intent = new Intent();
intent.setAction(action);
if(action.equals(OperationCodes.UNIT_STATUS_UPDATE + ""))
intent.putExtra("unitStatus", (String)object);
else if(action.equals(OperationCodes.BLUETOOTH_TETHER + ""))
intent.putExtra("tether", Boolean.parseBoolean((String)object));
else
intent.putExtra("extra", new SerializedObject(object, action));
getBaseContext().sendBroadcast(intent);
}
}