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

2760 lines
88 KiB
Java

package com.safemobile.safedispatch;
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.Objects;
import java.util.Timer;
import java.util.TimerTask;
import com.google.android.gms.tasks.Task;
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.enums.AuthorizationCode;
import com.safemobile.enums.AuthorizationStatus;
import com.safemobile.enums.ProviderSettingsStatus;
import com.safemobile.helpers.ProviderSettingsHelper;
import com.safemobile.interfaces.IPermissionModule;
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.DialogService;
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.PermissionModule;
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.User;
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.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationChannel;
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.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.View;
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;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class TabLayoutActivity extends AbstractSDParentActivity {
private final String TAG = "TabLayoutActivity";
/* Misc */
private Resources res;
private Context context;
private Activity activity;
public static final int RADIO_TAB_ID = 4;
private static final String HASH_ERROR_MESSAGE = "Error load hash: ";
private static final boolean NO_SOUND = false;
private boolean isMenuVisible = true;
private boolean isFirstGetVehicles = true;
private boolean lastTcpStatus = false;
private boolean isInCall = false;
private int crtActivity = 0;
private RadioGW crtRadio = null;
private MsgType activePopupType = MsgType.TCP;
/* Activities */
private AbstractLiveActivity liveActivity = null;
private RadioActivity radioActivity = null;
private MessagesActivity messageActivity = null;
private HistoryActivity historyActivity = null;
private RecordingsActivity recordingsActivity = null;
private AlarmActivity alarmActivity = null;
/* Handler for callbacks to the UI thread */
public final Handler myHandler = new Handler(Looper.getMainLooper());
/* Lists */
private ArrayList<RadioGW> allRadios;
private ArrayList<HistPos> historyPositionList = new ArrayList<>();
private volatile Boolean firstHistoryData = false;
private volatile Boolean dropAllData = false;
private ArrayList<Boolean> historyMessageList = new ArrayList<>();
/* DEMO lists */
private ArrayList<SMS> demoSmsList;
private ArrayList<HistPos> demoPositions = new ArrayList<>();
/* Tab */
private TabHost tabHost;
/* Visual Elements */
private RelativeLayout layoutNewMessage;
private TextView textViewNMMessage;
private TextView textViewNMFrom = null;
private TextView slideTabsText;
private ImageView imageViewPopUp;
private ImageView imageViewClose;
private ImageButton buttonLive;
private ImageButton buttonHistory;
private ImageButton buttonText;
private ImageButton buttonRadio;
private ImageButton buttonAlarms;
private ImageButton buttonRecordings;
private ImageButton buttonSetup;
/* NOTIFICATION */
private static 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;
/* TABS */
private static final String LIVE = "Live";
private static final String HISTORY = "History";
private static final String TEXT = "Text";
private static final String RADIO = "Radio";
private static final String RECORDINGS = "Recordings";
private static final String ALARMS = "Alarms";
private static final String SETTINGS = "Setup";
private static final String ABOUT = "SafeMobile";
private final Handler uiHandler = new Handler(Looper.getMainLooper());
// default app language
public static final String DATABASE_LANGUAGE = "en"; // database language : en, de, tr, ro or empty
public RadioGW getCrtRadio() {
return crtRadio;
}
public void setCrtRadio(RadioGW crtRadio) {
this.crtRadio = crtRadio;
}
public int getCrtActivity() {
return crtActivity;
}
public void setCrtActivity(int crtActivity) {
this.crtActivity = crtActivity;
}
public boolean isInCall() {
return isInCall;
}
public void setInCall(boolean inCall) {
isInCall = inCall;
}
public AbstractLiveActivity getLiveActivity() {
return liveActivity;
}
public RadioActivity getRadioActivity() {
return radioActivity;
}
public void setRadioActivity(RadioActivity radioActivity) {
this.radioActivity = radioActivity;
}
public MessagesActivity getMessageActivity() {
return messageActivity;
}
public void setMessageActivity(MessagesActivity messageActivity) {
this.messageActivity = messageActivity;
}
public HistoryActivity getHistoryActivity() {
return historyActivity;
}
public void setHistoryActivity(HistoryActivity historyActivity) {
this.historyActivity = historyActivity;
}
public RecordingsActivity getRecordingsActivity() {
return recordingsActivity;
}
public void setRecordingsActivity(RecordingsActivity recordingsActivity) {
this.recordingsActivity = recordingsActivity;
}
public AlarmActivity getAlarmActivity() {
return alarmActivity;
}
public void setAlarmActivity(AlarmActivity alarmActivity) {
this.alarmActivity = alarmActivity;
}
public ArrayList<RadioGW> getAllRadios() {
return allRadios;
}
public void setAllRadios(ArrayList<RadioGW> allRadios) {
this.allRadios = allRadios;
}
public ArrayList<HistPos> getHistoryPositionList() {
return historyPositionList;
}
public void setHistoryPositionList(ArrayList<HistPos> historyPositionList) {
this.historyPositionList = historyPositionList;
}
public void clearHistoryPositionList() {
this.historyPositionList.clear();
}
public Boolean getFirstHistoryData() {
return firstHistoryData;
}
public void setFirstHistoryData(Boolean firstHistoryData) {
this.firstHistoryData = firstHistoryData;
}
public Boolean getDropAllData() {
return dropAllData;
}
public void setDropAllData(Boolean dropAllData) {
this.dropAllData = dropAllData;
}
public ArrayList<Boolean> getHistoryMessageList() {
return historyMessageList;
}
public void setHistoryMessageList(ArrayList<Boolean> historyMessageList) {
this.historyMessageList = historyMessageList;
}
public void clearHistoryMessageList() {
this.historyMessageList.clear();
}
public ArrayList<SMS> getDemoSmsList() {
return demoSmsList;
}
public void setDemoSmsList(ArrayList<SMS> demoSmsList) {
this.demoSmsList = demoSmsList;
}
public ArrayList<HistPos> getDemoPositions() {
return demoPositions;
}
public void setDemoPositions(ArrayList<HistPos> demoPositions) {
this.demoPositions = demoPositions;
}
public MsgType getActivePopupType() {
return activePopupType;
}
public void setActivePopupType(MsgType activePopupType) {
this.activePopupType = activePopupType;
}
public enum MsgType {TCP, SMS, POLL, ALARM}
/**
* Called when the activity is first created.
*/
@SuppressLint("UseCompatLoadingForDrawables")
@SuppressWarnings("deprecation")
@Override
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;
activity = this;
res = getResources(); // Resource object to get Drawables
// 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));
//
// setDemoSmsList(new ArrayList<>());
//
// getDemoSmsList().add(new SMS(1, 1, 1324016412, "Only one left", 101, 0));
// getDemoSmsList().add(new SMS(2, 1, 1328061660, "Thanks", 0, 105));
// getDemoSmsList().add(new SMS(3, 1, 1328060100, "i'm at the train station", 0, 102));
// getDemoSmsList().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("Logged user:" + AppParams.USERNAME + " | id: " + AppParams.USERID);
// do not dim the display
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// get NewMessage Visual Element
layoutNewMessage = findViewById(R.id.layoutNewMessage);
textViewNMMessage = findViewById(R.id.textViewNMMessage);
textViewNMFrom = findViewById(R.id.textViewNMFrom);
slideTabsText = findViewById(R.id.slideTabsText);
imageViewPopUp = findViewById(R.id.imageViewPopUp);
imageViewClose = findViewById(R.id.imageViewClose);
// if (AppParams.DEMO)
// imageViewClose.setVisibility(View.VISIBLE);
tabHost = getTabHost(); // The activity TabHost
tabHost.setTag("Tab Panel");
/* Tab */
TabWidget tabWidget = findViewById(android.R.id.tabs);
tabWidget.setVisibility(View.GONE);
TabSpec[] tabSpecs = populateTabs();
// add tab in tabHost
for (TabSpec tab : tabSpecs) {
if (tabHost != null)
tabHost.addTab(tab);
}
LinearLayout layoutMenu = findViewById(R.id.layoutMenu);
// get slide Menu layout image
ImageView imageViewSlideMenu = findViewById(R.id.imageViewSlideMenu);
// get Live Button
buttonLive = findViewById(R.id.buttonLive);
buttonLive.setOnClickListener(buttonLiveClickListener);
// get History Button
buttonHistory = findViewById(R.id.buttonHistory);
buttonHistory.setOnClickListener(buttonHistoryClickListener);
// get Text Button
buttonText = findViewById(R.id.buttonText);
buttonText.setOnClickListener(buttonTextClickListener);
// get Radio Button
buttonRadio = findViewById(R.id.buttonRadio);
if (NO_SOUND)
buttonRadio.setVisibility(View.GONE);
buttonRadio.setOnClickListener(buttonRadioClickListener);
// get Recordings Button
buttonRecordings = findViewById(R.id.buttonRecording);
if (NO_SOUND)
buttonRecordings.setVisibility(View.GONE);
buttonRecordings.setOnClickListener(buttonRecordingsClickListener);
// get Alarm Button
buttonAlarms = findViewById(R.id.buttonAlarms);
buttonAlarms.setOnClickListener(buttonAlarmsClickListener);
//get Setup button
buttonSetup = findViewById(R.id.buttonSetup);
buttonSetup.setOnClickListener(buttonSetupClickListener);
// get About Button
ImageButton buttonLogo = findViewById(R.id.buttonLogo);
buttonLogo.setOnClickListener(buttonLogoClickListener);
imageViewClose.setOnTouchListener((v, event) -> {
layoutNewMessage.setVisibility(View.GONE);
return false;
});
// set Click event for NewMessageLayout
layoutNewMessage.setOnClickListener(v -> {
if (tcp != null && tcp.isConnectionUP && !isInCall()) {
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);
});
LinearLayout layoutSlideMenu = findViewById(R.id.layoutSlideMenu);
layoutSlideMenu.setOnClickListener(v -> {
layoutMenu.setVisibility(isMenuVisible ? View.GONE : View.VISIBLE);
imageViewSlideMenu.setImageResource(isMenuVisible ? R.drawable.arrow_left : R.drawable.arrow_right);
isMenuVisible = !isMenuVisible;
});
// 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 && getLiveActivity() != null) {
// getLiveActivity().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);
ConnectivityManager connectivityManager =
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
connectivityManager.registerDefaultNetworkCallback(networkCallback);
else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
}
private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// network available
Log.v(TAG, "network available");
Log.v(TAG, "tcp: " + (tcp != null));
if (tcp != null) {
if (tcp.isConnectionUP)
tcp.isConnectionUP = false;
uiHandler.post(() -> {
Log.v(TAG, "myService: " + (myService != null));
if (myService != null) {
myService.stopTCPConnection();
myService.recreateTCPConnection();
getApplicationContext().bindService(new Intent(context, TCPService.class), serviceConnection, Context.BIND_AUTO_CREATE);
if (getRadioActivity() != null)
getRadioActivity().onCreate(getRadioActivity().getSavedInstanceState());
if (getMessageActivity() != null)
getMessageActivity().onCreate(getMessageActivity().getSavedInstanceState());
if (getRecordingsActivity() != null)
getRecordingsActivity().onCreate(getRecordingsActivity().getSavedInstanceState());
if (getAlarmActivity() != null)
getAlarmActivity().onCreate(getAlarmActivity().getSavedInstanceState());
uiHandler.post(initTCPRUN);
}
});
}
}
@Override
public void onLost(Network network) {
// network unavailable
Log.v(TAG, "network unavailable");
}
};
/**
* 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 Text button
selectButton(buttonText);
// select text tab
tabHost.setCurrentTabByTag(TEXT);
// save text as current tab
AppParams.crtTab = AppParams.Tabs.message;
Vehicle vehicle = getVehicle4Imei(getImei());
if (vehicle != null)
getMessageActivity().setScId(vehicle.sc_id);
Log.v(TAG, "lastmessages: false");
getMessageActivity().LASTMESSAGES = false;
getMessageActivity().getLastSMS();
// disable notification
if (mNotificationManager != null)
mNotificationManager.cancel(R.drawable.message);
break;
case AppParams.alertNotif:
// hide NewMessage Layout
layoutNewMessage.setVisibility(View.GONE);
// select Alarms button
selectButton(buttonAlarms);
// select Alarms tab
tabHost.setCurrentTabByTag(ALARMS);
// save Alarms as current tab
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 Live button
selectButton(buttonLive);
// select tab
tabHost.setCurrentTabByTag(LIVE);
// save Live as current tab
AppParams.crtTab = AppParams.Tabs.live;
// disable notification
if (mNotificationManager != null)
mNotificationManager.cancel(R.drawable.poll);
break;
default:
throw new IllegalStateException("Unexpected value: " + icon);
}
}
public void demoPositionsList() {
AssetManager assetManager = res.getAssets();
SM.Debug("TRY 2 OPEN demo_positions.txt");
InputStream input = null;
try {
input = assetManager.open("demo_positions.txt");
InputStreamReader inputReader = new InputStreamReader(input);
try (BufferedReader bufferedReader = new BufferedReader(inputReader)) {
String line = "";
while ((line = bufferedReader.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];
getDemoPositions().add(gps);
}
}
HistPosmsg msg = new HistPosmsg(new TCPmsg(new char[]{}));
setDemoPositions(msg.CalcHeadingForArray(getDemoPositions()));
} catch (IOException e1) {
e1.printStackTrace();
}
}
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
SM.Debug("Service is disconnected");
isBound = false;
myService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
SM.Debug("Service is connected");
TCPBinder binder = (TCPBinder) service;
myService = binder.getService();
isBound = true;
tcpParser();
}
};
@Override
public void whenBackPressed(AppParams.ActivityResult result) {
try {
prepareForLogOut(result);
finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
} catch (Exception e) {
Log.v(TAG, e.getMessage());
}
}
private void prepareForLogOut(AppParams.ActivityResult result) {
Log.v(TAG, "prepareForLogOut");
if (tcpTimer != null) {
tcpTimer.cancel();
tcpTimer.purge();
tcpTimer = null;
}
if (getRadioActivity() != null && getRadioActivity().audioThread != null) {
Thread moribund = getRadioActivity().audioThread;
getRadioActivity().audioThread = null;
moribund.interrupt();
}
// 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
}
@Override
public void changeLanguage() {
// recreate UI
Locale locale = new Locale(AppParams.LANGUAGETMP);
Locale.setDefault(locale);
setLocale(getLiveActivity(), locale);
// change UI for RadioActivity and MessageActivity
if (getLiveActivity() != null)
getLiveActivity().setLanguage();
if (getHistoryActivity() != null)
getHistoryActivity().setLanguage();
if (getRadioActivity() != null)
getRadioActivity().onCreate(getRadioActivity().getSavedInstanceState());
if (getMessageActivity() != null)
getMessageActivity().onCreate(getMessageActivity().getSavedInstanceState());
if (getRecordingsActivity() != null)
getRecordingsActivity().onCreate(getRecordingsActivity().getSavedInstanceState());
if (getAlarmActivity() != null)
getAlarmActivity().onCreate(getAlarmActivity().getSavedInstanceState());
}
public static void setLocale(Activity activity, Locale locale) {
Resources resources = activity.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
//timer stuff
private void timerMethod() {
if (!AppParams.DEMO)
this.runOnUiThread(timerTick);
else
// build timerMethod for demo
this.runOnUiThread(timerTickDemo);
}
private final Runnable timerTickDemo = () -> {
if (AppParams.crtTab == AppParams.Tabs.live && getSuperVehHash().containsKey((long) 101)) {
HistPos crtPos = getDemoPositions().get(demoPosition++ % getDemoPositions().size());
SM.Debug("########### UPDATE");
int scId = demoPosition % 3 == 0 ? 101 : 102;
SuperVehicle superVehicle = (getSuperVehHash().get((long) scId));
if (superVehicle != null)
superVehicle.SetNewPosition(crtPos.lat, crtPos.lng, Calendar.getInstance().getTime().getTime(), crtPos.speed);
getLiveActivity().refreshMap();
}
};
@Override
public void updateDemoPosition() {
HistPos crtPos = getDemoPositions().get(demoPosition++ % getDemoPositions().size());
SM.Debug("########### UPDATE");
int scId = Integer.parseInt(getImei());
(Objects.requireNonNull(getSuperVehHash().get((long) scId))).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));
getLiveActivity().refreshMap();
}
private void selectButton(ImageButton imageButton) {
buttonText.setSelected(buttonText == imageButton);
buttonAlarms.setSelected(buttonAlarms == imageButton);
buttonLive.setSelected(buttonLive == imageButton);
buttonRadio.setSelected(buttonRadio == imageButton);
buttonRecordings.setSelected(buttonRecordings == imageButton);
buttonSetup.setSelected(buttonSetup == imageButton);
buttonHistory.setSelected(buttonHistory == imageButton);
}
private TabSpec[] populateTabs()
{
Intent[] intent = new Intent[8];
TabSpec[] 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(SETTINGS)
.setIndicator(SETTINGS, 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(ABOUT)
.setIndicator(ABOUT, 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]);
}
return tabSpecs;
}
private View.OnClickListener buttonLiveClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonLive.isSelected()) {
// select Live button
selectButton(buttonLive);
// select tab
tabHost.setCurrentTabByTag(LIVE);
AppParams.crtTab = AppParams.Tabs.live;
}
}
};
private View.OnClickListener buttonTextClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonText.isSelected()) {
// select Text button
selectButton(buttonText);
// select TEXT tab
tabHost.setCurrentTabByTag(TEXT);
// save Text tab
AppParams.crtTab = AppParams.Tabs.message;
// if (AppParams.DEMO && getMessageActivity().getAllVehicle().isEmpty()) {
//
// // select Text button
// selectButton(buttonText);
// // select TEXT tab
// tabHost.setCurrentTabByTag(TEXT);
// // save Text tab
// AppParams.crtTab = AppParams.Tabs.message;
//
// if (AppParams.DEMO && getMessageActivity().getAllVehicle().isEmpty()) {
// getMessageActivity().updateVehicles(getAllVehicle());
// getMessageActivity().updateSMS(getDemoSmsList());
// }
// }
}
}
};
private View.OnClickListener buttonRecordingslickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonRecordings.isSelected()) {
// select Recordings button
selectButton(buttonRecordings);
// select tab
tabHost.setCurrentTabByTag(RECORDINGS);
AppParams.crtTab = AppParams.Tabs.recordings;
// if (AppParams.DEMO)
// {
// if( getRecordingsActivity() != null && getRecordingsActivity().getAllRecordings() != null && getRecordingsActivity().getAllRecordings().isEmpty()) {
//
// ArrayList<Recording> listRecordings = new ArrayList<>();
// Recording rec = new Recording();
// rec.userWhoWasCalled = "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.userWhoWasCalled = "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.userWhoWasCalled = "Call2 [Rob]";
// rec.subID = 101;
// rec.endGMT = (int) Calendar.getInstance().getTime().getTime();
// rec.startGMT = rec.endGMT - 3;
// listRecordings.add(rec);
// rec.type = 103;
// getRecordingsActivity().updateRecordings(listRecordings);
// }
// }
}
}
};
private View.OnClickListener buttonAlarmslickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonAlarms.isSelected()) {
// select button
selectButton(buttonAlarms);
// select tab
tabHost.setCurrentTabByTag(ALARMS);
AppParams.crtTab = AppParams.Tabs.alarms;
// if (AppParams.DEMO) {
// if (getAlarmActivity() != null && getAlarmActivity().getAllAlarms() != null && getAlarmActivity().getAllAlarms().isEmpty()) {
//
// ArrayList<Alarm> listAlarms = new ArrayList<>();
// Alarm alarm = new Alarm();
// alarm.ack = 0;
// alarm.unitName = "Police";
// alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 5210L;
// 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() - 3315L;
// 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() - 1900L;
// 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() - 1521L;
// 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() - 521L;
// alarm.sc_id = 108;
// alarm.typestr = "Emergency";
// listAlarms.add(alarm);
//
// getAlarmActivity().updateAlarms(listAlarms);
// }
// }
}
}
};
private View.OnClickListener buttonHistoryClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonHistory.isSelected()) {
// select History button
selectButton(buttonHistory);
// select History tab
tabHost.setCurrentTabByTag(HISTORY);
// save History tab
AppParams.crtTab = AppParams.Tabs.history;
}
}
};
private View.OnClickListener buttonRadioClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonRadio.isSelected()) {
// check audio permission
IPermissionModule permissionModule = new PermissionModule();
AuthorizationStatus audioAuthorizationStatus = permissionModule.getAuthorizationStatus(activity, AuthorizationCode.RECORD_AUDIO);
if (audioAuthorizationStatus != AuthorizationStatus.AUTHORIZE) {
permissionModule.requestAuthorization(activity, AuthorizationCode.RECORD_AUDIO);
return;
}
// select Radio button
selectButton(buttonRadio);
// select Radio tab
tabHost.setCurrentTabByTag(RADIO);
// save Radio tab
AppParams.crtTab = AppParams.Tabs.radio;
RadioActivity radioActivity = getRadioActivity();
if (radioActivity != null && radioActivity.allVehicle != null && radioActivity.allVehicle.isEmpty()) {
radioActivity.allVehicle = getAllVehicle();
radioActivity.UpdateVehicle();
}
}
}
};
private View.OnClickListener buttonRecordingsClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonRecordings.isSelected()) {
// select button
selectButton(buttonRecordings);
// select Recordings tab
tabHost.setCurrentTabByTag(RECORDINGS);
// save Recordings tab
AppParams.crtTab = AppParams.Tabs.recordings;
// if (AppParams.DEMO) {
//
// if (getRecordingsActivity() != null && getRecordingsActivity().getAllRecordings() != null && getRecordingsActivity().getAllRecordings().isEmpty()) {
//
// ArrayList<Recording> listRecordings = new ArrayList<>();
// Recording rec = new Recording();
// rec.userWhoWasCalled = "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.userWhoWasCalled = "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.userWhoWasCalled = "Call2 [Rob]";
// rec.subID = 101;
// rec.endGMT = (int) Calendar.getInstance().getTime().getTime();
// rec.startGMT = rec.endGMT - 3;
// listRecordings.add(rec);
// rec.type = 103;
// getRecordingsActivity().updateRecordings(listRecordings);
// }
// }
}
}
};
private View.OnClickListener buttonAlarmsClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonAlarms.isSelected()) {
// select button
selectButton(buttonAlarms);
// select tab
tabHost.setCurrentTabByTag(ALARMS);
AppParams.crtTab = AppParams.Tabs.alarms;
// if (AppParams.DEMO) {
// if (getAlarmActivity() != null && getAlarmActivity().getAllAlarms() != null && getAlarmActivity().getAllAlarms().isEmpty()) {
//
//
// ArrayList<Alarm> listAlarms = new ArrayList<>();
// Alarm alarm = new Alarm();
// alarm.ack = 0;
// alarm.unitName = "Police";
// alarm.timeGMT = (int) Calendar.getInstance().getTime().getTime() - 5210L;
// 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() - 3315L;
// 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() - 1900L;
// 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() - 1521L;
// 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() - 521L;
// alarm.sc_id = 108;
// alarm.typestr = "Emergency";
// listAlarms.add(alarm);
//
// getAlarmActivity().updateAlarms(listAlarms);
// }
// }
}
}
};
private View.OnClickListener buttonSetupClickListener = new View.OnClickListener(){
@Override
public void onClick(View v) {
if (!buttonSetup.isSelected()) {
// select Setup button
selectButton(buttonSetup);
// select Setup tab
tabHost.setCurrentTabByTag(SETTINGS);
// save Setup tab
AppParams.crtTab = AppParams.Tabs.setup;
}
}
};
private View.OnClickListener buttonLogoClickListener = new View.OnClickListener() {
@Override
public void onClick(View 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) + " " + BuildConfig.VERSION_NAME);
text2.setText(String.format("%s: support@safemobile.com", getString(R.string.email)));
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
};
private Runnable timerTick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
if (tcp != null) {
if (Boolean.FALSE.equals(tcp.isConnectionUP)) {
// 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)
getRadioActivity().UpdateEnableDisableButtons("offline");
} catch (Exception ex) {
SM.Debug(ex.toString());
}
} else {
if (getAllVehicle().isEmpty())
new ConnectTask().execute(OperationCodes.GetVehicles + "", AppParams.USERID + "");
if (getRadioActivity() != null && AppParams.listRadios.isEmpty())
new ConnectTask().execute(OperationCodes.GetRadiosList + "");
layoutNewMessage.setVisibility(View.INVISIBLE);
}
// remember this tcp connection status
lastTcpStatus = tcp.isConnectionUP;
}
}
};
// TCP part
public void tcpInit() {
SM.Debug("#### TCP INIT ####");
new ConnectTask().execute(OperationCodes.TCP_CONNECTION_REQ + "");
}
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();
}
}
public void tcpParserListener() {
SM.Debug("ADDING TCP Listener", "NEW TCP Listener");
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();
GPSmsg gpsPositionMessage = new GPSmsg(msg);
SuperVehicle superVehicle = getSuperVehHash().get(gpsPositionMessage.gpsValue.imei);
if (superVehicle != null) {
superVehicle.SetNewPosition(gpsPositionMessage.gpsValue.lat, gpsPositionMessage.gpsValue.lng, gpsPositionMessage.gpsValue.timeGMT, gpsPositionMessage.gpsValue.speed);
if (superVehicle.needUpdate && AppParams.crtTab == AppParams.Tabs.live) {
//list for live
SM.Debug("currentActivity instanceof LiveActivity");
try {
if (getLiveActivity() != null)
getLiveActivity().refreshMap();
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
}
}
}
}
@Override
public void onPollReceived(TCPEvent event) {
SM.Debug("Got POLL GPS message");
TCPmsg msg = event.msg();
GPSmsg gpsPositionMessage = new GPSmsg(msg);
setImei(Long.toString(gpsPositionMessage.gpsValue.imei));
setMess("LAT:" + gpsPositionMessage.gpsValue.lat + " LNG:" + gpsPositionMessage.gpsValue.lng);
SM.Debug("Got new Poll pos data:" + gpsPositionMessage.data);
SuperVehicle superVehicle = getSuperVehHash().get(gpsPositionMessage.gpsValue.imei);
if (superVehicle != null) {
superVehicle.SetNewPosition(gpsPositionMessage.gpsValue.lat, gpsPositionMessage.gpsValue.lng, gpsPositionMessage.gpsValue.timeGMT, gpsPositionMessage.gpsValue.speed);
//if is not check i need to force check to put on the map
boolean forceChecked = false;
if (!superVehicle.needUpdate) {
superVehicle.needUpdate = true;
forceChecked = true;
}
//back to standard procedures to put on the map
if (AppParams.crtTab == AppParams.Tabs.live) {
//list for live
try {
int x = 0;
if (forceChecked) {
for (Vehicle veh : getAllVehicle()) {
if (veh.imei.compareTo(Long.toString(gpsPositionMessage.gpsValue.imei)) == 0)
break;
x++;
}
} else x = -1;
if (getLiveActivity() != null) {
if (x != getAllVehicle().size())
getLiveActivity().pollReceived(x, gpsPositionMessage.gpsValue.lat, gpsPositionMessage.gpsValue.lng);
else
getLiveActivity().pollReceived(-1, gpsPositionMessage.gpsValue.lat, gpsPositionMessage.gpsValue.lng);
}
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
}
}
}
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 text message tab
if (AppParams.crtTab == AppParams.Tabs.message && getMessageActivity() != null) {
getMessageActivity().updateSMS(sms.smsList);
}
} catch (Exception ex) {
SM.Debug("Error on smsReceived:" + ex.toString());
}
}
public void onVehiclesReceived(TCPEvent event) {
TCPmsg msg = event.msg();
VehMSG vMSG = new VehMSG(msg);
SM.Debug("### Vehicle Received ###", "Received " + vMSG.vehList.size() + " vehicles");
// =============================
// list for live tab
// =============================
if (AppParams.crtTab == AppParams.Tabs.live) {
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(HASH_ERROR_MESSAGE + ex);
}
if (getLiveActivity() != null)
getLiveActivity().vehiclesReceived(vMSG.vehList);
} else if (isFirstGetVehicles) {
// set vehicles to liveActivity
getLiveActivity().vehiclesReceived(vMSG.vehList);
isFirstGetVehicles = false;
}
// =============================
// list for text message tab
// =============================
if (AppParams.crtTab == AppParams.Tabs.message) {
SM.Debug("currentActivity instanceof MessagesActivity");
if (getMessageActivity() != null)
getMessageActivity().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 && getMessageActivity() != null) {
getMessageActivity().updateSMS(sms.smsList);
}
} catch (Exception ex) {
SM.Debug("Error on lastSMSReceived:" + ex);
}
}
@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 && getAlarmActivity() != null) {
SM.Debug("currentActivity instanceof AlarmActivity");
getAlarmActivity().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 && getAlarmActivity() != null) {
getAlarmActivity().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 (getMessageActivity() != null)
getMessageActivity().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 ignored) {
//ignored
}
// if tab is not TextTab
if (tabHost.getCurrentTab() != 2) {
myHandler.post(updateResults);
} else
myHandler.post(() ->
createNotification(AppParams.messageNotif));
//list for SMS
if (AppParams.crtTab == AppParams.Tabs.message && getMessageActivity() != null) {
SM.Debug("currentActivity instanceof MessagesActivity - newSMS | " + tempArr[0] + " | " + tempArr[1]);
getMessageActivity().newSMS(tempArr[0], tempArr[1], time);
}
}
@Override
public void onRecordingPlayReceived(TCPEvent event) {
TCPmsg msg = event.msg();
SM.Debug("Got PlayRec :" + msg.allData);
if (NO_SOUND) {
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 (getRecordingsActivity() != null)
getRecordingsActivity().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) {
SuperVehicle superVehicle = getSuperVehHash().get(posMsg.imei);
if (superVehicle != null)
superVehicle.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 histCountMsg = new HistCountmsg(msg);
SM.Debug("Message Count:" + histCountMsg.histcountValue.count);
if (AppParams.crtTab != AppParams.Tabs.history) {
//list for live
SM.Debug("currentActivity instanceof HistoryActivity");
try {
if (getHistoryActivity() != null) {
getHistoryActivity().UpdateCancel();
getHistoryActivity().UpdateUnableDisp();
}
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
}
return;
}
if (histCountMsg.histcountValue.count >= 2000) {
try {
if (getHistoryActivity() != null) {
getHistoryActivity().UpdateCancel();
getHistoryActivity().UpdateUnableDisp();
}
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
}
runOnUiThread(new Runnable() {
public void run() {
DialogService dialogService = new DialogService();
dialogService.showError(getHistoryActivity(), getString(R.string.too_many_positions, String.valueOf(histCountMsg.histcountValue.count)));
}
});
return;
}
if (histCountMsg.histcountValue.count == 0) {
try {
if (getHistoryActivity() != null) {
getHistoryActivity().UpdateCancel();
getHistoryActivity().UpdateUnableDisp();
}
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
}
runOnUiThread(new Runnable() {
public void run() {
DialogService dialogService = new DialogService();
dialogService.showError(getHistoryActivity(), getString(R.string.no_data_for_interval));
}
});
return;
}
}
@Override
public void onHistoryPositionsReceived(TCPEvent event) {
TCPmsg msg = event.msg();
SM.Debug("Got HistoryPos :" + msg.allData);
if (Boolean.FALSE.equals(getDropAllData())) {
HistPosmsg tmpHist = new HistPosmsg(msg);
boolean sendDataToMap = true;
try {
for (HistPos obj : tmpHist.PosList)
getHistoryPositionList().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, tmpHist.seqID.length()));
if (all != 0) {
if (Boolean.TRUE.equals(getFirstHistoryData())) {
try {
for (int i = 0; i < all; i++)
getHistoryMessageList().add(false);
} catch (Exception e) {
SM.Debug("Error on init hashTable:" + e);
}
setFirstHistoryData(false);
}
getHistoryMessageList().set(pos - 1, true);
for (int i = 0; i < (all); i++) {
if (Boolean.FALSE.equals(getHistoryMessageList().get(i))) {
sendDataToMap = false;
break;
}
}
}
} catch (Exception e) {
SM.Debug("Error on parse:" + e);
}
if (sendDataToMap) {
Collections.sort(getHistoryPositionList(), (Comparator<Object>) (o1, o2) -> {
HistPos p1 = (HistPos) o1;
HistPos p2 = (HistPos) o2;
return Long.compare(p1.timeGMT, p2.timeGMT);
});
//list for live
if (AppParams.crtTab == AppParams.Tabs.history) {
try {
if (getHistoryActivity() != null) {
// cancel last update
getHistoryActivity().UpdateCancel();
Thread.sleep(101);
if (getHistoryPositionList().size() < 2000) {
if ((getHistoryPositionList().size() != 1) || (getHistoryPositionList().get(0).timeGMT != 0)) {
getHistoryActivity().UpdateNrPos(getHistoryPositionList().size());
}
Thread.sleep(100);
getHistoryActivity().UpdateMap();
} else
getHistoryActivity().UpdateUnableDisp(); // update with more than 200 points
}
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
Thread.currentThread().interrupt();
}
}
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 radioMSG = new RadioMSG(msg);
if (!NO_SOUND) {
// update Zone and Channel
if (getRadioActivity() != null && radioMSG.zac != null) {
// update Zone and Channel in the allRadio List
for (RadioGW radio : getAllRadios()) {
if (radio.GW_ID == radioMSG.zac.gwID && radio.ID == radioMSG.zac.rgwID) {
radio.lastZoneNr = radioMSG.zac.zoneNr;
radio.lastChannelNr = radioMSG.zac.channelNr;
}
}
AppParams.crtZoneAndChannel = radioMSG.zac;
notifyBroadcast(OperationCodes.CHANNEL_BRDCST + "");
SM.Debug("Received from Apps -> UpdateZoneCH(" + radioMSG.zac.rgwID + "," + radioMSG.zac.gwID + "," + radioMSG.zac.zoneNr + "," + radioMSG.zac.channelNr + ")");
}
// =============================
// for radio tab
// =============================
if (AppParams.crtTab == AppParams.Tabs.radio) {
SM.Debug("#### RadioActivity");
// set crt activity to Radio
setCrtActivity(RADIO_TAB_ID);
SM.Debug("## " + (radioMSG.RadioGWList != null ? "RadioGWList" + radioMSG.RadioGWList.size() : "RadioGWList = null"));
SM.Debug("## " + (radioMSG.zac != null ? "zac" + radioMSG.zac : "zac = null"));
SM.Debug("## " + (radioMSG.rStatus != null ? "rStatus" + radioMSG.rStatus : "rStatus = null"));
if (getRadioActivity() != null && radioMSG.RadioGWList != null) {
getRadioActivity().UpdateRadios(radioMSG.RadioGWList);
SM.Debug("Received from Apps -> UpdateRadios( count:" + radioMSG.RadioGWList.size() + ")");
}
// update status in the crtRadio List
if (getRadioActivity() != null && radioMSG.rStatus != null) {
for (RadioGW radio : getAllRadios()) {
if (radio.GW_ID == radioMSG.rStatus.gwID && radio.ID == radioMSG.rStatus.rgwID)
radio.isOnline = (radioMSG.rStatus.status == 1);
}
SM.Debug("Received from Apps -> UpdateRadioStatus(" + radioMSG.rStatus.rgwID + "," + radioMSG.rStatus.gwID + "," + radioMSG.rStatus.status + ")");
if ((getCrtRadio() != null) && (getCrtRadio().GW_ID == radioMSG.rStatus.gwID) && (getCrtRadio().ID == radioMSG.rStatus.rgwID))
getRadioActivity().UpdateRadioStatus(radioMSG.rStatus.status);
}
//incCall
if (getRadioActivity() != null && radioMSG.incCall != null) {
SM.Debug("Received from Apps -> UpdateBroadcastCall(" + radioMSG.incCall.Imei + "," + radioMSG.incCall.callType + "," + radioMSG.incCall.groupId + ")");
// check if radioID and radioGW_ID needs to be changed
if (getCrtRadio() != null && (getCrtRadio().GW_ID != radioMSG.incCall.gwID || getCrtRadio().ID != radioMSG.incCall.rgwID)) {
for (RadioGW radio : getAllRadios()) {
if (radio.GW_ID == radioMSG.incCall.gwID && radio.ID == radioMSG.incCall.rgwID) {
setCrtRadio(radio);
notifyBroadcast(OperationCodes.RADIOID_CHANGED + "");
break;
}
}
}
if (getCrtRadio() != null) {
setInCall(radioMSG.incCall.callStatus != 3);
getRadioActivity().UpdateBroadcastCall(radioMSG.incCall.Imei, radioMSG.incCall.callType, radioMSG.incCall.groupId, radioMSG.incCall.callStatus);
}
}
} else {
if (radioMSG.incCall != null) {
setCrtActivity(0);
//incCall - update UI in Radio Activity
SM.Debug("Received from Apps -> UpdateBroadcastCall(" + radioMSG.incCall.Imei + "," + radioMSG.incCall.callType + "," + radioMSG.incCall.groupId + ")");
// check if radioID and radioGW_ID needs to be changed
if (getCrtRadio() != null && (getCrtRadio().GW_ID != radioMSG.incCall.gwID || getCrtRadio().ID != radioMSG.incCall.rgwID)) {
for (RadioGW radio : getAllRadios()) {
if (radio.GW_ID == radioMSG.incCall.gwID && radio.ID == radioMSG.incCall.rgwID) {
setCrtRadio(radio);
notifyBroadcast(OperationCodes.RADIOID_CHANGED + "");
break;
}
}
}
if (getCrtRadio() != null) {
if (radioMSG.incCall.callStatus == 3) {
setInCall(false);
// update recordings list
if (AppParams.crtTab == AppParams.Tabs.recordings && getRecordingsActivity() != null && getRecordingsActivity().getPlayingPosition() < 0) {
// no recording is playing
getRecordings(getCrtRadio().GW_ID, getCrtRadio().ID);
}
} else
setInCall(true);
getRadioActivity().UpdateBroadcastCall(radioMSG.incCall.Imei, radioMSG.incCall.callType, radioMSG.incCall.groupId, radioMSG.incCall.callStatus);
}
}
// update radios
if (radioMSG.RadioGWList != null && getRadioActivity() != null)
getRadioActivity().UpdateRadios(radioMSG.RadioGWList);
// update zones
if (radioMSG.zac != null && getRadioActivity() != null) {
getRadioActivity().UpdateZoneCH(radioMSG.zac.rgwID, radioMSG.zac.gwID, radioMSG.zac.zoneNr, radioMSG.zac.channelNr);
}
// update radio status
if (radioMSG.rStatus != null && getRadioActivity() != null) {
// update status in the allRadio List
for (RadioGW radio : getAllRadios()) {
if (radio.GW_ID == radioMSG.rStatus.gwID && radio.ID == radioMSG.rStatus.rgwID)
radio.isOnline = (radioMSG.rStatus.status == 1);
}
if ((getCrtRadio() != null) && (getCrtRadio().GW_ID == radioMSG.rStatus.gwID) && (getCrtRadio().ID == radioMSG.rStatus.rgwID))
getRadioActivity().UpdateRadioStatus(radioMSG.rStatus.status);
}
}
// save RadioList
if (radioMSG.RadioGWList != null) {
setAllRadios(radioMSG.RadioGWList);
if (getCrtRadio() == null) {
setCrtRadio(getAllRadios().get(0));
SM.Debug("radioMSG set 0 crtRadio GW_ID:" + getCrtRadio().GW_ID + " id:" + getCrtRadio().ID + ")");
notifyBroadcast(OperationCodes.RADIOID_CHANGED + "");
}
}
// save crt Radio id and GW
if (radioMSG.zac != null) {
for (RadioGW radio : getAllRadios()) {
if (radio.GW_ID == radioMSG.zac.gwID && radio.ID == radioMSG.zac.rgwID)
setCrtRadio(radio);
}
}
if (AppParams.crtTab == AppParams.Tabs.recordings && getRecordingsActivity() != null && radioMSG.RadioGWList != null) {
SM.Debug("GetRecordings Request + crtRadio:" + getCrtRadio().toString());
getRecordings(getCrtRadio().GW_ID, getCrtRadio().ID);
}
}
// used when a unit is enabled / disabled
if (radioMSG.suStatus != null) {
SM.Debug("ENABLED/DISABLED " + radioMSG.suStatus);
notifyBroadcast(OperationCodes.UNIT_STATUS_UPDATE + "", radioMSG.suStatus.imei + "#" + radioMSG.suStatus.status);
} else
SM.Debug("SUStatus is null");
}
@Override
public void alarmLiveReceived(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];
// 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);
//============
// live tab
//============
if ((msg.opCode == 138) && (AppParams.crtTab == AppParams.Tabs.live)) {
SuperVehicle superVehicle = getSuperVehHash().get(Long.parseLong(unitIMEI));
if (superVehicle != null) {
//if is not check i need to force check to put on the map
boolean forceChecked = false;
if (!superVehicle.needUpdate) {
superVehicle.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 (getLiveActivity() != null) {
if (x != getAllVehicle().size())
getLiveActivity().emergencyAlarmReceived(x, superVehicle.lat, superVehicle.lng);
else
getLiveActivity().emergencyAlarmReceived(-1, superVehicle.lat, superVehicle.lng);
}
} catch (Exception ex) {
SM.Debug(HASH_ERROR_MESSAGE + ex);
}
}
}
//list for SMS
if (AppParams.crtTab == AppParams.Tabs.alarms) {
SM.Debug("currentActivity instanceof AlarmActivity - newSMS | " + tempArr[0] + " | " + tempArr[1]);
getAlarms(AppParams.USERID);
}
}
@Override
public void onRecordingsListReceived(TCPEvent event) {
TCPmsg msg = event.msg();
RecordMSG recordMSG = new RecordMSG(msg);
SM.Debug("am primit lista cu Recording");
//recordings tab
if (AppParams.crtTab == AppParams.Tabs.recordings) {
for (Recording rec : recordMSG.getRecordList()) {
SuperVehicle superVehicle = getSuperVehHash().get((long) rec.subID);
// set the name to be displayed
switch (rec.callType) {
case 0:
for (User u : AppParams.allUsers) {
if (u.id == rec.dispatcherId)
rec.userWhoCalled = u.login;
}
if (rec.userWhoCalled == null || rec.userWhoCalled.isEmpty())
rec.userWhoCalled = String.valueOf(rec.dispatcherId);
if (superVehicle != null)
rec.userWhoWasCalled = superVehicle.name;
else
rec.userWhoWasCalled = String.valueOf(rec.subID);
break;
case 4:
rec.userWhoWasCalled = AppParams.USERNAME;
if (superVehicle != null)
rec.userWhoCalled = superVehicle.name;
else
rec.userWhoCalled = String.valueOf(rec.subID);
break;
case 1:
for (User u : AppParams.allUsers) {
if (u.id == rec.dispatcherId)
rec.userWhoCalled = u.login;
}
if (rec.userWhoCalled == null || rec.userWhoCalled.isEmpty())
rec.userWhoCalled = String.valueOf(rec.dispatcherId);
if (rec.groupName == null || rec.groupName.isEmpty())
rec.userWhoWasCalled = String.valueOf(rec.groupCpsId);
else
rec.userWhoWasCalled = rec.groupName;
break;
case 5:
if (superVehicle != null)
rec.userWhoCalled = superVehicle.name;
else
rec.userWhoCalled = String.valueOf(rec.subID);
if (rec.groupName == null || rec.groupName.isEmpty())
rec.userWhoWasCalled = String.valueOf(rec.groupCpsId);
else
rec.userWhoWasCalled = rec.groupName;
break;
case 2:
for (User u : AppParams.allUsers) {
if (u.id == rec.dispatcherId)
rec.userWhoCalled = u.login;
}
if (rec.userWhoCalled == null || rec.userWhoCalled.isEmpty())
rec.userWhoCalled = String.valueOf(rec.dispatcherId);
rec.userWhoWasCalled = "All Call";
break;
case 6:
rec.userWhoWasCalled = "All Call";
if (superVehicle != null)
rec.userWhoCalled = superVehicle.name;
else
rec.userWhoCalled = String.valueOf(rec.subID);
break;
}
}
// save recordings to AppParams
AppParams.recordings = recordMSG.getRecordList();
// notify recordings were received
notifyBroadcast(OperationCodes.RECORDINGS_LIST_REP + "");
}
}
@Override
public void onConnectionReplyReceived(TCPEvent event) {
}
@Override
public void onContactsListReceived(TCPEvent event) {
}
@Override
public void onTextMessagesListReceived(TCPEvent event) {
}
@Override
public void onTCPConnectionDown(boolean previousWasConnectionUp) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
boolean isNetworkConnected = isNetworkConnected();
Log.v(TAG, "isNetworkConnected: " + isNetworkConnected);
if (isNetworkConnected) {
if (tcp != null && !tcp.isConnectionUP) {
tcp.Stop();
// if (tcpParser != null)
// tcpParser.clearMsgList();
tcp = null;
uiHandler.post(() -> {
if (myService != null) {
myService.stopTCPConnection();
myService.recreateTCPConnection();
getApplicationContext().bindService(new Intent(context, TCPService.class), serviceConnection, Context.BIND_AUTO_CREATE);
if (getRadioActivity() != null)
getRadioActivity().onCreate(getRadioActivity().getSavedInstanceState());
if (getMessageActivity() != null)
getMessageActivity().onCreate(getMessageActivity().getSavedInstanceState());
if (getRecordingsActivity() != null)
getRecordingsActivity().onCreate(getRecordingsActivity().getSavedInstanceState());
if (getAlarmActivity() != null)
getAlarmActivity().onCreate(getAlarmActivity().getSavedInstanceState());
uiHandler.post(initTCPRUN);
}
SM.Debug("RECREATE TCP", "IP: " + AppParams.IP + " | Port: " + AppParams.PORT);
});
}
this.cancel();
}
}
}, 0, 100);
prepareForLogOut(AppParams.ActivityResult.tcpDown);
// execute logout
// whenBackPressed(AppParams.ActivityResult.tcpDown);
// send a broadcast
// notifyBroadcast(OperationCodes.TCP_CONNECTION_DOWN + "");
}
@Override
public void onTCPConnectionUp(boolean previousWasConnectionUp) {
}
@Override
public void onTCPConnectionStatusReceived(boolean isConnectionUp, boolean previousWasConnectionUp) {
}
@Override
public void onPONGReceived() {
}
});
}
// Create runnable for posting
final Runnable initTCPRUN = () -> {
// start thread to add listener
SM.Debug("##### initTCPRUN");
if (!AppParams.DEMO)
tcpInit();
};
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
// 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 {
setActivePopupType(MsgType.ALARM);
imageViewPopUp.setImageResource(R.drawable.siren_on);
slideTabsText.setText(getString(R.string.newAlarm));
Vehicle vehicle = getVehicle4Imei(getImei());
if (vehicle != null)
textViewNMFrom.setText(String.format("%s: %s", getString(R.string.from), vehicle.name));
else
textViewNMFrom.setText(String.format("%s: %s", getString(R.string.from), getImei()));
textViewNMMessage.setText(String.format("TYPE: %s", 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("Error 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) {
setActivePopupType(MsgType.POLL);
imageViewPopUp.setImageResource(R.drawable.poll);
slideTabsText.setText(getString(R.string.newPoll));
textViewNMFrom.setText(String.format("%s: %s", getString(R.string.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) {
// setActivePopupType(MsgType.POLL);
// imageViewPopUp.setImageResource(R.drawable.poll);
// slideTabsText.setText(R.string.newPoll);
// textViewNMFrom.setText(getString(R.string.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) {
setActivePopupType(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");
// setActivePopupType(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 iconValue = 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) + ": " + getVehicle4Imei(getImei()).name;
contentText = "\"" + getMess() + "\"";
contentTitle = getString(R.string.newAlarm) + vehName;
tickerText = "SafeMobile Dispatch: " + getString(R.string.newAlarm) + vehName;
icon = R.drawable.alert;
break;
default:
throw new IllegalStateException("Unexpected value: " + icon);
}
Notification notification = new Notification(icon, tickerText, System.currentTimeMillis());
// flag that the notification will be closed when clicked
notification.flags |= Notification.FLAG_AUTO_CANCEL;
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);
Intent intent = new Intent(this, NotificationActivity.class);
intent.putExtra("key", iconValue);
// cancel old notification
mNotificationManager.cancel(icon);
PendingIntent pendingIntent = PendingIntent.getActivity(context, NOTIFICATION_ACTIVITY_RESULT, intent, PendingIntent.FLAG_CANCEL_CURRENT);
createNotificationChannel(icon, contentTitle, contentText, pendingIntent);
}
private void createNotificationChannel(int icon, String title, String text, PendingIntent pendingIntent) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
String notificationChannelID = String.valueOf(icon);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification Channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(notificationChannelID, name, importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, notificationChannelID)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(icon, builder.build());
}
// return vehicle according to imei
private Vehicle getVehicle4Imei(String imei) {
for (Vehicle vehicle : getAllVehicle())
if (vehicle.imei.equals(imei))
return vehicle;
return null;
}
@Override
public void enableMenuButtons(boolean enabled) {
buttonAlarms.setEnabled(enabled);
buttonHistory.setEnabled(enabled);
buttonLive.setEnabled(enabled);
buttonRecordings.setEnabled(enabled);
buttonText.setEnabled(enabled);
buttonRadio.setEnabled(enabled);
buttonSetup.setEnabled(enabled);
}
// 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 && (latMax == latMin) && (latMax == 0) && (lngMax == lngMin) && (lngMax == 0)) {
return 2;
}
// Center latitude in radians
double centerLat = 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(centerLat))) / 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();
Thread.currentThread().interrupt();
}
boolean response = tcp.Write("0.0", "#30#" + callType + "#" + gwID + "." + rgwid + "." + id + "#" + userID + "#");
if (response) {
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) {
//ignored
}
getRecentSMSs(Integer.parseInt(params[1]), Long.parseLong(params[2]));
break;
case OperationCodes.SEND_TM:
sendSMS(params[1], Integer.parseInt(params[2]), params[3]);
break;
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;
default:
throw new IllegalStateException("Unexpected value: " + Integer.parseInt(params[0]));
}
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();
// 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) {
}
@Override
public void setLiveActivity(AbstractLiveActivity liveActivity) {
this.liveActivity = liveActivity;
}
@Override
public void setMessagesActivity(AbstractMessagesActivity messageActivity) {
}
@Override
public void unregisterReceivers(BroadcastReceiver receiver) {
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(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
*/
private void notifyBroadcast(String action) {
Intent intent = new Intent();
intent.setAction(action);
getBaseContext().sendBroadcast(intent);
}
// send a message to be broadcast 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 (Objects.equals(action, OperationCodes.UNIT_STATUS_UPDATE + ""))
intent.putExtra("unitStatus", (String) object);
else if (Objects.equals(action, OperationCodes.BLUETOOTH_TETHER + ""))
intent.putExtra("tether", Boolean.parseBoolean((String) object));
else
intent.putExtra("extra", new SerializedObject(object, action));
getBaseContext().sendBroadcast(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
SM.Debug("onRequestPermissionsResult", "[requestCode] " + requestCode);
String permission = "";
switch (requestCode) {
case PermissionModule.RECORD_AUDIO_PERMISSION_REQUEST_CODE:
permission = Manifest.permission.RECORD_AUDIO;
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
AuthorizationStatus result;
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
result = AuthorizationStatus.AUTHORIZE;
} else {
result = AuthorizationStatus.DENIED;
}
if (permissions.length == 0)
return;
if (permissions[0].equals(Manifest.permission.RECORD_AUDIO)) {
onAudioPermissionChanged(result);
}
}
private void onAudioPermissionChanged(AuthorizationStatus result) {
if (result == AuthorizationStatus.AUTHORIZE) {
// 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 (getRadioActivity() != null && getRadioActivity().allVehicle != null && getRadioActivity().allVehicle.isEmpty()) {
getRadioActivity().allVehicle = getAllVehicle();
getRadioActivity().UpdateVehicle();
}
} else {
DialogService dialogService = new DialogService();
Task<Boolean> responseTask = dialogService.showPermissionRequestDialog(this,
getString(R.string.permissionBlocked, getString(R.string.microphone), getString(R.string.radio_tab), getString(R.string.microphone)),
getString(R.string.cancel));
responseTask.addOnCompleteListener(task -> waitForUserInput(task.getResult()));
}
}
private void waitForUserInput(Boolean result) {
if (result) {
final int requestCode = 1202;
//navigate to application's settings
String action = ProviderSettingsHelper.getAction(ProviderSettingsStatus.APPLICATION_DETAILS);
if (action == null || action == "")
return;
boolean isActionApplicationDetailsSettings = action.equals(ProviderSettingsHelper.ACTION_APPLICATION_DETAILS_SETTINGS);
if (!ProviderSettingsHelper.canHandleAction(context, action))
action = ProviderSettingsHelper.getAction(ProviderSettingsStatus.SETTINGS);
Intent intent = new Intent(action);
if (isActionApplicationDetailsSettings) {
Uri uri = Uri.fromParts(ProviderSettingsHelper.PACKAGE, this.getPackageName(), null);
intent.setData(uri);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(mReceiver);
}
}