Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.61 KB | None | 0 0
  1. package com.seniorproject.trafton.trackrecordrace;
  2.  
  3. //Import statements not shown for readability
  4. import...
  5.  
  6. public class MapsActivity extends AppCompatActivity implements LocationProvider.LocationCallback {
  7.  
  8. public static final String TAG = "cloudsTraf";
  9. //MapsActivity.class.getSimpleName();
  10.  
  11. private GoogleMap mMap; // Might be null if Google Play services APK is not available.
  12.  
  13. private LocationProvider mLocationProvider;
  14.  
  15. //variable for toggle buttons
  16. private boolean isRunning = false;
  17.  
  18. //ArrayList to store geopoints for current run
  19. private ArrayList<LatLng> geoPoints;
  20.  
  21. //Array of distances
  22. private ArrayList<Float> distances;
  23.  
  24. //total distance
  25. private float totalDistance;
  26.  
  27. //polyline that represented the route
  28. Polyline tracker;
  29.  
  30. /*Load up widgets for tracking */
  31. private ImageButton mPlayButton;
  32. private ImageButton mPauseButton;
  33.  
  34. private TextView mRunTimeText;
  35. private TextView mRunSpeedText;
  36. private TextView mRunDistText;
  37. private TextView mRunCalsText;
  38.  
  39. private Boolean mIsPlayButtonClicked;
  40.  
  41. //Handler to control timer tracking
  42. //Thank you to Nikos Maravitsas for the tutorial on timers
  43.  
  44. private Handler timeHandler = new Handler();
  45.  
  46. private long startTime = 0L;
  47. long timeInMillis = 0L;
  48. long timeSwapBuffer = 0L;
  49. long updatedTime = 0L;
  50.  
  51.  
  52.  
  53.  
  54.  
  55. @Override
  56. protected void onCreate(Bundle savedInstanceState) {
  57. super.onCreate(savedInstanceState);
  58. setContentView(R.layout.activity_maps);
  59. setUpMapIfNeeded();
  60.  
  61. mLocationProvider = new LocationProvider(this, this);
  62. geoPoints = new ArrayList<LatLng>(); //added
  63.  
  64. //Add in code to inflate the tracking modules
  65. mRunTimeText = (TextView) findViewById(R.id.run_time_text);
  66. mRunDistText = (TextView) findViewById(R.id.run_dist_text);
  67. mRunSpeedText = (TextView) findViewById(R.id.run_speed_text);
  68.  
  69. Toolbar runToolbar= (Toolbar) findViewById(R.id.toolbar_run);
  70. runToolbar.setTitle("Run on " + getDate());
  71. runToolbar.setTitleTextColor(Color.WHITE);
  72. setSupportActionBar(runToolbar);
  73.  
  74. }
  75.  
  76. //Inflate the menu for the toolbar
  77. public boolean onCreateOptionsMenu(Menu menu) {
  78. Log.e("XXX", "Menu created");
  79. MenuInflater inflater = getMenuInflater();
  80. inflater.inflate(R.menu.menu_maps_run, menu);
  81. return super.onCreateOptionsMenu(menu);
  82. }
  83.  
  84. //Handles possibilities of menu items being selected.
  85. @Override
  86. public boolean onOptionsItemSelected(MenuItem item) {
  87. // Handle item selection
  88. switch (item.getItemId()) {
  89. case R.id.action_begin_run:
  90. if (!isRunning) {
  91. startTime = SystemClock.uptimeMillis();
  92. timeHandler.postDelayed(updateTimerThread,0);
  93. item.setIcon(R.drawable.ic_pause_white_24dp);
  94. isRunning = true;
  95. }
  96. else {
  97. timeSwapBuffer += timeInMillis;
  98. timeHandler.removeCallbacks(updateTimerThread);
  99. item.setIcon(R.drawable.ic_play_arrow_white_24dp);
  100. isRunning = false;
  101.  
  102. }
  103. return true;
  104.  
  105. case R.id.action_stop_run:
  106. //stop run, save run, and transport user to the stats for that run
  107.  
  108. return true;
  109. default:
  110. return super.onOptionsItemSelected(item);
  111. }
  112. }
  113.  
  114. /*Code to update the timer, begins a new timer thread.*/
  115. private Runnable updateTimerThread = new Runnable() {
  116. public void run(){
  117. timeInMillis = SystemClock.uptimeMillis() - startTime;
  118. updatedTime = timeSwapBuffer + timeInMillis;
  119.  
  120. //Get integer value from time update and put into textView
  121. int seconds = (int) (updatedTime/1000);
  122. //need two seconds variables for formatting purposes.
  123. int secs = seconds % 60;
  124. int mins = (seconds / 60);
  125. int hours = (mins / 60);
  126.  
  127. mRunTimeText.setText("" + hours + ":" +
  128. String.format("%02d", mins) + ":" +
  129. String.format("%02d", secs));
  130. timeHandler.postDelayed(this, 0);
  131. }
  132.  
  133. };
  134.  
  135. /* */
  136.  
  137. @Override
  138. protected void onResume() {
  139. super.onResume();
  140. setUpMapIfNeeded();
  141. mLocationProvider.connect();
  142. }
  143.  
  144. @Override
  145. protected void onPause() {
  146. super.onPause();
  147. mLocationProvider.disconnect();
  148. }
  149.  
  150. /**
  151. * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
  152. * installed) and the map has not already been instantiated.. This will ensure that we only ever
  153. * call {@link #setUpMap()} once when {@link #mMap} is not null.
  154. * <p/>
  155. * If it isn't installed {@link SupportMapFragment} (and
  156. * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
  157. * install/update the Google Play services APK on their device.
  158. * <p/>
  159. * A user can return to this FragmentActivity after following the prompt and correctly
  160. * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
  161. * have been completely destroyed during this process (it is likely that it would only be
  162. * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
  163. * method in {@link #onResume()} to guarantee that it will be called.
  164. */
  165. private void setUpMapIfNeeded() {
  166. // Do a null check to confirm that we have not already instantiated the map.
  167. if (mMap == null) {
  168. // Try to obtain the map from the SupportMapFragment.
  169. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
  170. .getMap();
  171. // Check if we were successful in obtaining the map.
  172. if (mMap != null) {
  173. setUpMap();
  174. }
  175. }
  176. }
  177.  
  178. /**
  179. * This should only be called once and when we are sure that {@link #mMap} is not null.
  180. */
  181. private void setUpMap() {
  182. //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
  183. }
  184.  
  185. //handle new location
  186. public void handleNewLocation(Location location) {
  187. Log.d(TAG, location.toString());
  188.  
  189. double currentLatitude = location.getLatitude();
  190. double currentLongitude = location.getLongitude();
  191. LatLng latLng = new LatLng(currentLatitude, currentLongitude);
  192.  
  193. //Get the new geopoints to redraw the line on each iteration
  194. geoPoints.add(latLng);
  195. //get the latest distance update
  196. if (geoPoints.size() > 2) {
  197. calculateDistance();
  198. }
  199. //set the distance test
  200. mRunDistText.setText(Float.toString(totalDistance) + " Meters");
  201. mRunSpeedText.setText((location.getSpeed() + " m/s"));
  202.  
  203. //draw the polyline
  204. drawRoute();
  205. MarkerOptions options = new MarkerOptions()
  206. .position(latLng)
  207. .title("I am here!");
  208. mMap.addMarker(options);
  209. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
  210. }
  211.  
  212. /*
  213. *Methods to calculate metrics. All measurements returned are approximations.
  214. */
  215. //returns the latest distance between geoPoints. Append to total number
  216. public void calculateDistance(){
  217. Location newLoc = new Location("Latest Location");
  218. Location oldLoc = new Location("Last known Location");
  219. LatLng newPt = geoPoints.get(geoPoints.size()- 1);
  220. LatLng oldPt = geoPoints.get(geoPoints.size()-2);
  221. distances.add(oldLoc.distanceTo(newLoc));
  222. //add to the distance variable
  223. totalDistance = totalDistance + oldLoc.distanceTo(newLoc);
  224. Log.d(TAG, "distance between points is: " + oldLoc.distanceTo(newLoc));
  225. }
  226.  
  227. //calculates the current KCals being burned
  228. public void calculateKcals(){
  229.  
  230. }
  231.  
  232. //get today's date in a simple format
  233. public String getDate(){
  234. Date today = Calendar.getInstance().getTime();
  235. SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd");
  236. String todaysDate = formatter.format(today);
  237. return todaysDate;
  238. }
  239.  
  240. //method to draw polyline. Uses the recorded geopoints.
  241. public void drawRoute(){
  242. mMap.clear();
  243. PolylineOptions options = new PolylineOptions().width(5).color(android.R.color.holo_blue_dark).geodesic(true).visible(true);
  244. for(int i = 0; i < geoPoints.size(); i++){
  245. LatLng pt = geoPoints.get(i);
  246. options.add(pt);
  247. }
  248. Log.d(TAG,"GeoPoints recorded: " + geoPoints);
  249. mMap.addPolyline(options);
  250. }
  251.  
  252. package com.seniorproject.trafton.trackrecordrace;
  253.  
  254. import android.app.Activity;
  255. import android.content.Context;
  256. import android.content.IntentSender;
  257. import android.location.Location;
  258. import android.os.Bundle;
  259. import android.util.Log;
  260.  
  261. import com.google.android.gms.common.ConnectionResult;
  262. import com.google.android.gms.common.api.GoogleApiClient;
  263. import com.google.android.gms.location.LocationListener;
  264. import com.google.android.gms.location.LocationRequest;
  265. import com.google.android.gms.location.LocationServices;
  266.  
  267.  
  268. public class LocationProvider implements
  269. GoogleApiClient.ConnectionCallbacks,
  270. GoogleApiClient.OnConnectionFailedListener,
  271. LocationListener {
  272.  
  273. public abstract interface LocationCallback {
  274. public void handleNewLocation(Location location);
  275. }
  276.  
  277. public static final String TAG = LocationProvider.class.getSimpleName();
  278.  
  279. /*
  280. * Define a request code to send to Google Play services
  281. * This code is returned in Activity.onActivityResult
  282. */
  283. private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
  284.  
  285. private LocationCallback mLocationCallback;
  286. private Context mContext;
  287. private GoogleApiClient mGoogleApiClient;
  288. private LocationRequest mLocationRequest;
  289.  
  290.  
  291. public LocationProvider(Context context, LocationCallback callback) {
  292. mGoogleApiClient = new GoogleApiClient.Builder(context)
  293. .addConnectionCallbacks(this)
  294. .addOnConnectionFailedListener(this)
  295. .addApi(LocationServices.API)
  296. .build();
  297.  
  298. mLocationCallback = callback;
  299.  
  300. // Create the LocationRequest object
  301. mLocationRequest = LocationRequest.create()
  302. .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
  303. .setInterval(3 * 1000) // 10 seconds, in milliseconds
  304. .setFastestInterval(1 * 1000); // 1 second, in milliseconds
  305.  
  306. mContext = context;
  307. }
  308.  
  309. public void connect() {
  310. mGoogleApiClient.connect();
  311. }
  312.  
  313. public void disconnect() {
  314. if (mGoogleApiClient.isConnected()) {
  315. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
  316. mGoogleApiClient.disconnect();
  317. }
  318. }
  319.  
  320. @Override
  321. public void onConnected(Bundle bundle) {
  322. Log.i(TAG, "Location services connected.");
  323.  
  324. Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  325. if (location == null) {
  326. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
  327. }
  328. else {
  329. mLocationCallback.handleNewLocation(location);
  330. }
  331. }
  332.  
  333. @Override
  334. public void onConnectionSuspended(int i) {
  335.  
  336. }
  337.  
  338. @Override
  339. public void onConnectionFailed(ConnectionResult connectionResult) {
  340. /*
  341. * Google Play services can resolve some errors it detects.
  342. * If the error has a resolution, try sending an Intent to
  343. * start a Google Play services activity that can resolve
  344. * error.
  345. */
  346. if (connectionResult.hasResolution() && mContext instanceof Activity) {
  347. try {
  348. Activity activity = (Activity)mContext;
  349. // Start an Activity that tries to resolve the error
  350. connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
  351. /*
  352. * Thrown if Google Play services canceled the original
  353. * PendingIntent
  354. */
  355. } catch (IntentSender.SendIntentException e) {
  356. // Log the error
  357. e.printStackTrace();
  358. }
  359. } else {
  360. /*
  361. * If no resolution is available, display a dialog to the
  362. * user with the error.
  363. */
  364. Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
  365. }
  366. }
  367.  
  368. @Override
  369. public void onLocationChanged(Location location) {
  370. mLocationCallback.handleNewLocation(location);
  371. Log.i(TAG, "New location received ");
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement