Académique Documents
Professionnel Documents
Culture Documents
dashboard;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.ActivityManager;
android.app.AlertDialog;
android.app.DatePickerDialog;
android.app.ProgressDialog;
android.content.Context;
android.content.DialogInterface;
android.content.Intent;
android.graphics.Bitmap;
android.graphics.BitmapFactory;
android.graphics.Canvas;
android.graphics.Color;
android.graphics.Paint;
android.graphics.Rect;
android.graphics.Typeface;
android.os.AsyncTask;
android.os.Bundle;
android.support.v4.widget.DrawerLayout;
android.support.v7.app.ActionBarActivity;
android.support.v7.app.ActionBarDrawerToggle;
android.support.v7.widget.Toolbar;
android.view.Gravity;
android.view.Menu;
android.view.MenuInflater;
android.view.View;
android.view.ViewGroup;
android.widget.AdapterView;
android.widget.ArrayAdapter;
android.widget.Button;
android.widget.CompoundButton;
android.widget.DatePicker;
android.widget.ImageView;
android.widget.LinearLayout;
android.widget.ListView;
android.widget.TextView;
android.widget.ToggleButton;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
com.abistech.locationservice.LocationService;
com.abistech.utils.ErrorManagementSystem;
com.abistech.utils.HTTPConnection;
com.google.android.gms.maps.CameraUpdate;
com.google.android.gms.maps.CameraUpdateFactory;
com.google.android.gms.maps.GoogleMap;
com.google.android.gms.maps.SupportMapFragment;
com.google.android.gms.maps.model.BitmapDescriptor;
com.google.android.gms.maps.model.BitmapDescriptorFactory;
com.google.android.gms.maps.model.LatLng;
com.google.android.gms.maps.model.LatLngBounds;
com.google.android.gms.maps.model.Marker;
com.google.android.gms.maps.model.MarkerOptions;
com.google.android.gms.maps.model.PolylineOptions;
com.sothree.slidinguppanel.SlidingUpPanelLayout;
import
import
import
import
import
import
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
org.xml.sax.InputSource;
org.xml.sax.SAXException;
import
import
import
import
import
import
import
import
import
import
import
java.io.IOException;
java.io.StringReader;
java.text.ParseException;
java.text.SimpleDateFormat;
java.util.ArrayList;
java.util.Arrays;
java.util.Calendar;
java.util.Date;
java.util.HashMap;
java.util.List;
java.util.TimeZone;
import
import
import
import
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.parsers.ParserConfigurationException;
javax.xml.xpath.XPathExpressionException;
setToggleButtonStateToOFF();
}}).show();
}
private void setToggleButtonStateToOFF() {
flagSetToggleStateOFF = false;
((ToggleButton) findViewById(R.id.locServiceToggle)).setChecked(false);
((ToggleButton) findViewById(R.id.locServiceToggle)).setBackgroundColor(
Color.RED);
flagSetToggleStateOFF = true;
}
private void setToggleButtonStateToON() {
flagSetToggleStateOFF = false;
((ToggleButton) findViewById(R.id.locServiceToggle)).setChecked(true);
((ToggleButton) findViewById(R.id.locServiceToggle)).setBackgroundColor(
Color.GREEN);
flagSetToggleStateOFF = true;
}
private void stopLocService() {
new AlertDialog.Builder(this)
.setTitle("Confirm Action")
.setMessage("Stop Tracking Location ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnC
lickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String url = "http://abistarun.uphero.com/db_stop_trip.p
hp";
new StopLocationService(url, "LogOutTime="+sdfSQL.format
(new Date()), "TripId="+tripId).execute();
}})
.setNegativeButton(android.R.string.no, new DialogInterface.OnCl
ickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
setToggleButtonStateToON();
}})
.show();
}
class LaunchLocationService extends AsyncTask<Void, String, String> {
HTTPConnection httpConnection = new HTTPConnection();
String url;
String[] parametersToPass;
ProgressDialog progress;
LaunchLocationService(String... params) {
url = params[0];
parametersToPass = new String[params.length-1];
for(int i=1; i<params.length; i++) {
parametersToPass[i-1] = params[i];
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
}
locServiceIntent.putExtra("userId", userId);
locServiceIntent.putExtra("tripId", tripId);
startService(locServiceIntent);
setColorOfToggleButton(Color.GREEN);
} else {
//Throw error cannot start tracking
setToggleButtonStateToOFF();
ems.handleError(2,null,dom);
}
catch (ParserConfigurationException e) {
ems.handleError(1,e, null);
catch (SAXException e) {
ems.handleError(1, e, null);
catch (IOException e) {
ems.handleError(1, e, null);
catch (XPathExpressionException e) {
ems.handleError(1,e,null);
}
}
}
}
private void setColorOfToggleButton(int color) {
((ToggleButton) findViewById(R.id.locServiceToggle)).setBackgroundColor(
color);
}
} catch (ParserConfigurationException e) {
ems.handleError(1,e, null);
} catch (SAXException e) {
ems.handleError(1, e, null);
} catch (IOException e) {
ems.handleError(1, e, null);
} catch (XPathExpressionException e) {
ems.handleError(1,e,null);
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_dashboard, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
addListenerToToggleButton();
if(isMyServiceRunning(LocationService.class)) {
setToggleButtonStateToON();
} else {
new AlertDialog.Builder(this)
.setTitle("Confirm Action")
.setMessage("Do you want to start Tracking ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int whichBut
ton) {
setToggleButtonStateToON();
String url = "http://abistarun.uphero.com/db_start_t
rip.php";
new LaunchLocationService(url, "LogInTime=" + sdfSQL
.format(new Date()), "UserId=" + userId).execute();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.
OnClickListener() {
public void onClick(DialogInterface dialog, int whichBut
ton) {
setToggleButtonStateToOFF();
populateDrawerInformation();
}
}).show();
}
}
private void populateDrawerInformation() {
String date = sdfSQL.format(activeDate).split(" ")[0];
String url = "http://abistarun.uphero.com/db_get_usertrips.php";
new HTTPConnectionThreadToPopulateTripdetails(url, "UserId="+userId, "Da
te="+date).execute();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmen
tById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
if (marker.getTitle() != null) {
LinearLayout info = new LinearLayout(Dashboard.this);
info.setOrientation(LinearLayout.VERTICAL);
TextView startTime = new TextView(Dashboard.this);
startTime.setTextColor(Color.BLACK);
startTime.setGravity(Gravity.CENTER);
startTime.setTypeface(null, Typeface.BOLD);
startTime.setText(marker.getTitle().toString().split("to")[0
].trim());
TextView to = new TextView(Dashboard.this);
to.setTextColor(Color.BLACK);
to.setGravity(Gravity.CENTER);
to.setTypeface(null, Typeface.BOLD);
to.setText("to");
TextView endTime = new TextView(Dashboard.this);
endTime.setTextColor(Color.BLACK);
endTime.setGravity(Gravity.CENTER);
endTime.setTypeface(null, Typeface.BOLD);
endTime.setText(marker.getTitle().toString().split("to")[1].
trim());
info.addView(startTime);
info.addView(to);
info.addView(endTime);
return info;
}
return null;
}
});
}
ss);
return httpResponse;
}
@Override
protected void onPostExecute(String httpResponse) {
super.onPostExecute(httpResponse);
progress.dismiss();
if (httpResponse != null) {
ems.storeLogs("HTTP request returned:\t" + httpResponse);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsta
nce();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(httpRespon
se));
Document dom = db.parse(is);
int tripCnt = 0;
List<String> tripNameList = new ArrayList<String>();
String status = HTTPConnection.parseXMLusingXpath(dom, "/xml
/body/status");
if (status.equals("Success")) {
( (DrawerLayout) findViewById(R.id.drawer_layout)).openD
rawer(Gravity.LEFT);
NodeList nl = dom.getElementsByTagName("tripDetails");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NOD
E) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("tripDetails")
) {
int tripId = Integer.parseInt(el.getElem
entsByTagName("tripId").item(0).getTextContent());
String tripName = el.getElementsByTagNam
e("tripName").item(0).getTextContent();
String logInTime = el.getElementsByTagNa
me("logInTime").item(0).getTextContent();
String logOutTime = el.getElementsByTagN
ame("logOutTime").item(0).getTextContent();
//int logOutReason = Integer.parseInt(el
.getElementsByTagName("logOutReason").item(0).getTextContent());
tripIdMap.put(tripCnt, tripId);
tripNameList.add("Trip "+(i+1));
//tripNameList.add(tripName);
logInMap.put(tripCnt, logInTime);
logOutMap.put(tripCnt, logOutTime);
//logOutReasonMap.put(tripCnt, logOutRea
son);
tripCnt++;
}
}
}
String[] listViewValues = Arrays.copyOf(tripNameList
.toArray(), tripNameList.size(), String[].class);
totalHours.setText("Total hours:
min : "+seconds+"sec");
} catch (ParseException e) {
ems.handleError(1,e,null);
}
if(httpResponse!=null) {
ems.storeLogs("HTTP request returned:\t" + httpResponse);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsta
nce();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(httpRespon
se));
Document dom = db.parse(is);
boolean isFirst = true;
LinearLayout legendLayout = (LinearLayout) findViewById(R.id
.contentLegend);
legendLayout.removeAllViews();
mMap.clear();
String status = HTTPConnection.parseXMLusingXpath(dom, "/xml
/body/status");
if (status.equals("Success")) {
((DrawerLayout) findViewById(R.id.drawer_layout)).closeD
rawers();
NodeList nl = dom.getElementsByTagName("locationDetails"
);
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NOD
E) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("locationDetai
ls")) {
String locId = el.getElementsByTagName("
locId").item(0).getTextContent();
String locLatitude = el.getElementsByTag
Name("locLatitude").item(0).getTextContent();
String locLongitude = el.getElementsByTa
gName("locLongitude").item(0).getTextContent();
String locAccuracy = el.getElementsByTag
Name("locAccuracy").item(0).getTextContent();
String locRecordedTime = el.getElementsB
yTagName("locRecordedTime").item(0).getTextContent();
//String locUpdateType = el.getElementsB
yTagName("locUpdateType").item(0).getTextContent();
Location tempLoc = new Location(Integer.
parseInt(locId), Double.parseDouble(locLatitude), Double.parseDouble(locLongitud
e), Double.parseDouble(locAccuracy), sdfSQL.parse(locRecordedTime));
Location filteredLoc = checkJunk(tempLoc
);
if(filteredLoc!=null) {
Location bulkFilter = checkBulk(filt
eredLoc);
if(bulkFilter!=null) {
if(isFirst) {
plotMarker(bulkFilter, 1);
isFirst = false;
} else {
plotMarker(bulkFilter, 0);
}
}
}
}
}
}
resolveBuffers();
mMap.addPolyline(pathPolyLine);
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBound
s(bounds, 100);
mMap.animateCamera(cu);
TextView totalDistTextView = (TextView) findViewById
(R.id.distInTrip);
p:
}
}
}
private Location checkBulk(Location point) {
if(bulkBuffer[0]==null) {
bulkBuffer[0]=point;
return null;
} else if(bulkBuffer[1]==null) {
bulkBuffer[1]=point;
return null;
} else {
double d = Location.getDistance(bulkBuffer[0], bulkBuffer[1]);
if(d > bulkThreshold) {
Location temp = bulkBuffer[0];
bulkBuffer[0] = bulkBuffer[1];
bulkBuffer[1] = point;
temp.setLocTimeEnd(bulkBuffer[0].getLocStartTime());
return temp;
} else {
bulkBuffer[0] = Location.calculateCentroid(bulkBuffer[0], bu
lkBuffer[1]);
bulkBuffer[1] = point;
return null;
}
}
}
private void resolveBuffers() {
if((junkBuffer[2]==null)&&(junkBuffer[1]==null)) {
junkBuffer[0].setLocTimeEnd(junkBuffer[0].getLocStartTime());
plotMarker(junkBuffer[0], 2);
return;
} else if(junkBuffer[2]==null) {
junkBuffer[0].setLocTimeEnd(junkBuffer[1].getLocStartTime());
junkBuffer[1].setLocTimeEnd(junkBuffer[1].getLocStartTime());
plotMarker(junkBuffer[0], 1);
plotMarker(junkBuffer[1], 2);
return;
}
double x = Location.getDistance(junkBuffer[0], junkBuffer[1]);
double y = Location.getDistance(junkBuffer[1], junkBuffer[2]);
if(((x+y)/2) > junkThreshold) {
junkBuffer[1] = junkBuffer[2];
junkBuffer[2] = null;
} else {
junkBuffer[0] = junkBuffer[1];
junkBuffer[1] = junkBuffer[2];
junkBuffer[2] = null;
Location filterBulk = checkBulk(junkBuffer[0]);
if(filterBulk!=null) {
plotMarker(filterBulk, 0);
}
}
x = Location.getDistance(junkBuffer[0], junkBuffer[1]);
if(x<junkThreshold) {
singleLegend.addView(color);
singleLegend.addView(to);
LinearLayout slidingPanel = (LinearLayout) findViewById(R.id.content
Legend);
slidingPanel.addView(singleLegend);
}
private void showSinglePath(int currPathId) {
mMap.clear();
PolylineOptions currPolyLine = polylineMap.get(currPathId);
LatLng firstPoint = currPolyLine.getPoints().get(0);
for(LatLng curr:currPolyLine.getPoints()) {
mMap.addMarker(new MarkerOptions().position(curr).icon(BitmapDes
criptorFactory.fromResource(R.drawable.path_icon)));
}
LatLng lastPoint = currPolyLine.getPoints().get(currPolyLine.getPoin
ts().size()-1);
mMap.addPolyline(currPolyLine);
BitmapDescriptor flagBitmapDescriptorFirst = BitmapDescriptorFactory
.fromBitmap(writeTextOnDrawable(R.drawable.stop_marker, markerMap.get(currPathId
-1) + ""));
mMap.addMarker(new MarkerOptions().position(firstPoint).icon(flagBit
mapDescriptorFirst));
BitmapDescriptor flagBitmapDescriptorLast = BitmapDescriptorFactory.
fromBitmap(writeTextOnDrawable(R.drawable.stop_marker, markerMap.get(currPathId)
+ ""));
mMap.addMarker(new MarkerOptions().position(lastPoint).icon(flagBitm
apDescriptorLast));
SlidingUpPanelLayout slidingPanel = (SlidingUpPanelLayout) findViewB
yId(R.id.sliding_layout);
slidingPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED
);
}
private void plotMarker(Location location, int isMarker) {
LatLng latLng = new LatLng(location.getLocLatitude(), location.getLo
cLongitude());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
if ((location.getLocEndTime().getTime() - location.getLocStartTime()
.getTime() >= 10*60*1000)||(isMarker>=1)) {
if(isMarker!=1) {
//if(pathPolyLine!=null) {
polylineMap.put(legendId, pathPolyLine);
markerMap.put(legendId, markerCount);
mMap.addPolyline(pathPolyLine);
if (markerCount != 1) {
addToLegend(markerCount, randColor.getDescentColor(m
arkerCount), legendId);
totalDistance += Location.getDistance(location, prev
Loc);
//System.out.println(location.getLocId() + " to " +
prevLoc.getLocId());
}
prevLoc = location;
legendId++;
//}