getting gps location, calculating speed and showing on a map

Put problem concerning MapActivities, MapViews, Overlays and GPS in this forum.

getting gps location, calculating speed and showing on a map

Postby da3dalu5 » Fri Jun 03, 2011 11:24 am

favorite


Basically, I'm trying to write a simple app to locate where I am and update my position every fixed time interval.

I followed this:http://foo.jasonhudgins.com/2007/12/cruising-around-with-android.html tutorial and managed to obtain a value for my position. However, for the life of me I cannot get it to work in an endless loop. I just want it to keep going until I quit the application (by pressing the back button for the time being).

The reason I want to have a loop like this is because I want to calculate my speed. I was going to do it like this:

Code: Select all
loop{

   get Location and store it
   wait One Second
   get Location and store it
   wait One Second
   get Location and store it
   wait One Second
   get Location and store it
   wait One Second
   get Location and store it
   wait One Second

   calculate distance traveled and divide by 5 to get average speed
   print latest location and speed

}


Now, this is just the VERY basic version of what I would like to do. Idealy I would like to have a thread handle the timer and another get the locations (to ensure that the location is taken PRECISELY on one second intervals by locking the other thread out of getting the location until "timer % 1000 milliseconds == 0" or something like that), then have another thread for the computation of current speed.

I am new at android programming however, so I'm not sure if im going in the right direction to do this, or even if this is the correct way to go about solving this problem, I'm not necessarily looking for the code, but if you guys could help me in the right direction, suggest how to obtain the data in a more accurate/efficent way, or even suggestions about how I should change the logic of my code that would be great!... BUUUUT if you DO want to help me out with some code I would be very thankful! :D

Also, I was wondering if this might be a better way to calculate the speed, would I get a more accurate reading if I, say:

Code: Select all
get location
add to arrayList

...fill list with 5 items and enter loop of...

calculate speed with items from list  <---
                                         |
remove oldest item from list             |
add current location to list             |
                                         |
loop -------------------------------------


this way I could have a new speed value every second, but still have the accuracy of calculating the average speed of the last 5 seconds... or is there something that I'm not factoring in here? (bear in mind that I may reduce the interval time to 1/5th of a second, and take 5 readings a second, theoretically being able to update the speed 5 times a second...or would this have detrimental effects)

Any feed back would be GREATLY appreciated!
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Top

Re: getting gps location, calculating speed and showing on a

Postby abhijitphatak28 » Mon Jun 06, 2011 7:21 am

You can look for the following blog. It also have source code for that.

http://www.krvarma.com/posts/android/ge ... n-android/

Thanks

Regards
-Abhijit
User avatar
abhijitphatak28
Senior Developer
Senior Developer
 
Posts: 102
Joined: Sat Feb 12, 2011 1:18 pm
Location: Indore

Re: getting gps location, calculating speed and showing on a

Postby da3dalu5 » Tue Jun 07, 2011 10:29 am

abhijitphatak28 wrote:You can look for the following blog. It also have source code for that.

http://www.krvarma.com/posts/android/ge ... n-android/

Thanks

Regards
-Abhijit


Thanks for the reply, I have been looking throught the source code and it is helping a lot! :D

I have managed to get a good bit more coding done this morning, my progress is this.

Code: Select all
package Hartford.gps;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class GPSMain extends Activity {

   //text views to display latitude and longitude
   private TextView latituteField;
   private TextView longitudeField;
   
   //object to store previous location data
   protected Location oldLocation = null;
   
   //object to define 2 minutes of time
   private static final int TWO_MINUTES = 1000 * 60 * 2;
   
   //object to store value for current speed
   protected int currentSpeed = 0;
   
   //boolean value used to compare new location with previous location
   protected boolean betterLocation;
   
   //list of locations to be used when calculating currentSpeed
   protected List<Location> locations = new ArrayList<Location>();

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      //sets up text views
      latituteField = (TextView) findViewById(R.id.thisisanid2);
      longitudeField = (TextView) findViewById(R.id.thisisanid3);
      
      run();

   }
   
   private void run(){
      
      //Acquire a reference to the system Location Manager
      LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
      
      // Define a listener that responds to location updates
      LocationListener locationListener = new LocationListener() {
         
         public void onLocationChanged(Location newLocation) {

            // Called when a new location is found by the network location provider.
            betterLocation = isBetterLocation(newLocation, oldLocation);

            //if new location is better than old location
            if (betterLocation == true){
               
               //if locations list already has 5 values
               if (locations.size()==4){
                  
                  //call update list method with newLocation
                  updateLocations(newLocation);
                  
                  //calculate current speed and apply the resulting value to currentSpeed
                  currentSpeed = calculateSpeed(locations);
               
               //if locations list does not have 5 values
               }else{
                  
                  //add new location to locations list
                  locations.add(newLocation);
               }
               
            //display the values of the old and new location
            int lat = (int) (oldLocation.getLatitude());
            int lng = (int) (newLocation.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));
            
            //update the oldLocation for the next loop
            oldLocation = newLocation;
            
            //if new location is no good
            }else{
               
               //if locations list already has 5 values
               if (locations.size()==4){
                  
                  //call update list method with oldLocation
                  updateLocations(oldLocation);
                  
                  //calculate current speed and apply the resulting value to currentSpeed
                  currentSpeed = calculateSpeed(locations);
                  
               //if locations list does not have 5 values
               }else{
                  
                  //add oldLocation to the list
                  locations.add(oldLocation);
               }
            }
            
            //display the
            int lat = (int) (oldLocation.getLatitude());
            int lng = (int) (oldLocation.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));
            
         }
         
         //not entirely sure what these do yet
         public void onStatusChanged(String provider, int status, Bundle extras) {}
         public void onProviderEnabled(String provider) {}
         public void onProviderDisabled(String provider) {}
      };

      // Register the listener with the Location Manager to receive location updates
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener);
   }

   //update the locations list
   private void updateLocations(Location newLocation){
      
      //create buffer
      Location buff = null;
      
      //loop that executes 5 times
      for(int i = 4; i > 0; i--){
         
         //remove the oldest location from the list and shift the remaining 4 down
         buff = locations.get(i-1);
         locations.set(i, buff);
      }
      
      //ad the newest location to the beginning of the list
      locations.set(0, newLocation);
   }

   //method to calculate speed
   private int calculateSpeed(List<Location> locations){
      final int speed = 0;
      return speed;
   }

   /** Determines whether one Location reading is better than the current Location fix
    * @param location  The new Location that you want to evaluate
    * @param currentBestLocation  The current Location fix, to which you want to compare the new one
    */
   protected boolean isBetterLocation(Location location, Location currentBestLocation) {

      if (currentBestLocation == null) {
         
         // A new location is always better than no location
         return true;
         
      }

      // Check whether the new location fix is newer or older
      long timeDelta = location.getTime() - currentBestLocation.getTime();
      boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
      boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
      boolean isNewer = timeDelta > 0;

      // If it's been more than two minutes since the current location, use the new location
      // because the user has likely moved
      if (isSignificantlyNewer) {

         // If the new location is more than two minutes older, it must be worse
         return true;         
      
      } else if (isSignificantlyOlder) {
         
         return false;
      
      }

      // Check whether the new location fix is more or less accurate
      int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
      boolean isLessAccurate = accuracyDelta > 0;
      boolean isMoreAccurate = accuracyDelta < 0;
      boolean isSignificantlyLessAccurate = accuracyDelta > 200;

      // Check if the old and new location are from the same provider
      boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

      // Determine location quality using a combination of timeliness and accuracy
      if (isMoreAccurate) {
         
         return true;
      
      } else if (isNewer && !isLessAccurate) {
         
         return true;
      
      } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
         
         return true;
      
      }
      
      return false;
   }

   /** Checks whether two providers are the same */
   private boolean isSameProvider(String provider1, String provider2) {
      
      if (provider1 == null) {
      
         return provider2 == null;
      
      }
      
      return provider1.equals(provider2);
   
   }
   
}



I have commented most of the code in it to try explain what (I think) each line of code is doing. However, when I run the app indoors, it runs and runs and tries to connect (as one would expect) with no avail. BUt when i go outside, within a second or two it crashes. (im guessing upon connection) So I must be doing something wrong here. If anybody can have a quick look at the code and see if I am making any silly mistakes that would be great. I will post up the working code if I fugure it out myself.
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Re: getting gps location, calculating speed and showing on a

Postby abhijitphatak28 » Wed Jun 08, 2011 5:58 am

Do device debugging so that you would know the exact point where it is crashing.

Also as you said, it is crashing when you are going outside, this means that your LocationChangedListerner is called and that is crashing some where inside it.

Thanks

Regards
-Abhijit
User avatar
abhijitphatak28
Senior Developer
Senior Developer
 
Posts: 102
Joined: Sat Feb 12, 2011 1:18 pm
Location: Indore

Re: getting gps location, calculating speed and showing on a

Postby da3dalu5 » Wed Jun 08, 2011 11:08 am

abhijitphatak28 wrote:Do device debugging so that you would know the exact point where it is crashing.


Would love to but this is a project that I am working on for my work and they have blocked all of the usb ports on our machines. I have requested one to be opened on my machine so as I could do device depuging but as we are just a sister company of a bigger company in america (who overlook out network infastructure and the like) I cant get it opened. I have also requested that I be allowed debug on my personal laptop, but I was told that it would be against company policy as it is not a company machine located on the secure network.... so everytime i want to run the application on my device I have to do a signed export and email it to myself... and yes, it's quite tedious XD .

Also as you said, it is crashing when you are going outside, this means that your LocationChangedListerner is called and that is crashing some where inside it.

Thanks

Regards
-Abhijit


Yeah I have managed to find the culprate for that problem, and have changed the code significantly since, will update in a post after I submit this reply.

Thanks for your suggestions and advice tho :)
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Re: getting gps location, calculating speed and showing on a

Postby da3dalu5 » Wed Jun 08, 2011 11:20 am

OK, so now I have a bit of an update for you.

The code has been significantly changed. I have devided it up into seperate class files.

The program now runs and gets it's current position, but dispite how long I wait, or move, or move and wait, it does not update. Now I know that this is probably just me doing something wrong but it's my understanding that the values provided in this line (highlighted in red) that determine the update frequency, amirite??

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);

the main

GPSMain.java

Code: Select all
package Hartford.gps;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class GPSMain extends Activity {
   
   //text views to display latitude and longitude
   TextView latituteField;
   TextView longitudeField;
   TextView currentSpeedField;
   
   protected double lat;
   protected double lon;
   
   //object to store previous location data
   protected Location oldLocation = null;
   
   //object to define 2 minutes of time
   static final int TWO_MINUTES = 1000 * 60 * 2;
   
   //object to store value for current speed
   protected int currentSpeed = 0;
   
   //boolean value used to compare new location with previous location
   protected boolean betterLocation;
   
   //list of locations to be used when calculating currentSpeed
   private List<Location> locations = new ArrayList<Location>();   

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      run();

   }
   
   private void run(){
      //Acquire a reference to the system Location Manager
      LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            
      // Define a listener that responds to location updates
      LocationListener locationListener = new LocationListener() {
         
         public void onLocationChanged(Location newLocation) {
            
            //temporarily store newLocation
            oldLocation = newLocation;
            
            //add the newLocation to the list
            locations = Calculations.updateLocations(locations, newLocation);
            currentSpeed = Calculations.calculateSpeed(locations, currentSpeed);

            lat = (double) (newLocation.getLatitude());
            lon = (double) (newLocation.getLongitude());
            
            latituteField = (TextView) findViewById(R.id.lat);
            longitudeField = (TextView) findViewById(R.id.lon);
            currentSpeedField = (TextView) findViewById(R.id.speed);
            
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lon));
            currentSpeedField.setText(String.valueOf(currentSpeed));
            
         }
         
         //not entirely sure what these do yet
         public void onStatusChanged(String provider, int status, Bundle extras) {}
         public void onProviderEnabled(String provider) {}
         public void onProviderDisabled(String provider) {}
      
      };

      // Register the listener with the Location Manager to receive location updates every second or kilometer
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
   }

}


the calculations class

Calculations.java

Code: Select all
package Hartford.gps;

import java.util.List;

import android.location.Location;

public class Calculations {

   //update the locations list
   static List <Location> updateLocations(List <Location> locations, Location newLocation){

      List<Location> updatedLocations = locations;
      
      //create buffer
      Location buff = null;

      //if there are already 5 elements in the array
      if (updatedLocations.size()==5) {

         //remove the oldest location from the list and shift the remaining 4 down
         int i;
         //loop that executes 5 times
         for(i = 0; i > 4; i++){

            //store the value of the "i"th value in the array
            buff = updatedLocations.get(i+1);
            
            //replace the "i"th value with the "i-1"th
            //(effectively push the last element off and move the rest up)
            updatedLocations.set(i, buff);
         }

         //add the newest location to the beginning of the list
         updatedLocations.set(i, newLocation);
         
      //if there are less than 5 elements already in the array
      }else{
         
         //just add the newest location to the end
         updatedLocations.add(newLocation);
         
      }
      return updatedLocations;
      
   }


   
   //method to calculate speed
   static int calculateSpeed(List<Location> locations, int speed){
      
      List <Location> speedList = locations;
      
      int totalSpeed = speed;
      
      while(speedList.contains(true)){
      
         totalSpeed++;
         
      }
      
      return totalSpeed;
   }


}
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Top

Re: getting gps location, calculating speed and showing on a

Postby da3dalu5 » Thu Jun 09, 2011 10:36 am

Ok, I did a little research and discovered that alot of what i was trying to do had already been done (don't know why i didnt think to check sooned lol).

Anyway I got the basic functionality working. It tells you where you are, gives you your currnet speed and average speed in m/s and kmph and updates as frequently as it can.

Here is ALL the code:

GPSMain.java:

Code: Select all
package Hartford.gps;

import java.math.BigDecimal;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class GPSMain extends Activity implements LocationListener {
   
   LocationManager locationManager;
   LocationListener locationListener;
   
   //text views to display latitude and longitude
   TextView latituteField;
   TextView longitudeField;
   TextView currentSpeedField;
   TextView kmphSpeedField;
   TextView avgSpeedField;
   TextView avgKmphField;
   
   //objects to store positional information
   protected double lat;
   protected double lon;
      
   //objects to store values for current and average speed
   protected double currentSpeed;
   protected double kmphSpeed;
   protected double avgSpeed;
   protected double avgKmph;
   protected double totalSpeed;
   protected double totalKmph;
   
   //counter that is incremented every time a new position is received, used to calculate average speed
   int counter = 0;
   
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      run();
   }
   
   @Override
    public void onResume() {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
        super.onResume();
    }

   @Override
    public void onPause() {
        locationManager.removeUpdates(this);
        super.onPause();
    }
   
   private void run(){
      
      final Criteria criteria = new Criteria();
       
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setSpeedRequired(true);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
      //Acquire a reference to the system Location Manager
      
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            
      // Define a listener that responds to location updates
      locationListener = new LocationListener() {
         
         public void onLocationChanged(Location newLocation) {
            
            counter++;
            
            //current speed fo the gps device
            currentSpeed = round(newLocation.getSpeed(),3,BigDecimal.ROUND_HALF_UP);
            kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
            
            //all speeds added together
            totalSpeed = totalSpeed + currentSpeed;
            totalKmph = totalKmph + kmphSpeed;
            
            //calculates average speed
            avgSpeed = round(totalSpeed/counter,3,BigDecimal.ROUND_HALF_UP);
            avgKmph = round(totalKmph/counter,3,BigDecimal.ROUND_HALF_UP);
            
            //gets position
            lat = round(((double) (newLocation.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
            lon = round(((double) (newLocation.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
            
            latituteField = (TextView) findViewById(R.id.lat);
            longitudeField = (TextView) findViewById(R.id.lon);            
            currentSpeedField = (TextView) findViewById(R.id.speed);
            kmphSpeedField = (TextView) findViewById(R.id.kmph);
            avgSpeedField = (TextView) findViewById(R.id.avgspeed);
            avgKmphField = (TextView) findViewById(R.id.avgkmph);
            
            latituteField.setText("Current Latitude:      "+String.valueOf(lat));
            longitudeField.setText("Current Longitude:      "+String.valueOf(lon));
            currentSpeedField.setText("Current Speed (m/s):      "+String.valueOf(currentSpeed));
            kmphSpeedField.setText("Cuttent Speed (kmph):      "+String.valueOf(kmphSpeed));
            avgSpeedField.setText("Average Speed (m/s):      "+String.valueOf(avgSpeed));
            avgKmphField.setText("Average Speed (kmph):      "+String.valueOf(avgKmph));
            
         }
         
         //not entirely sure what these do yet
         public void onStatusChanged(String provider, int status, Bundle extras) {}
         public void onProviderEnabled(String provider) {}
         public void onProviderDisabled(String provider) {}
      
      };

      // Register the listener with the Location Manager to receive location updates
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);
   }
   
   //Method to round the doubles to a max of 3 decimal places
   public static double round(double unrounded, int precision, int roundingMode)
   {
       BigDecimal bd = new BigDecimal(unrounded);
       BigDecimal rounded = bd.setScale(precision, roundingMode);
       return rounded.doubleValue();
   }

   
   @Override
   public void onLocationChanged(Location location) {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void onProviderDisabled(String provider) {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void onProviderEnabled(String provider) {
      // TODO Auto-generated method stub
      
   }

   @Override
   public void onStatusChanged(String provider, int status, Bundle extras) {
      // TODO Auto-generated method stub
      
   }

}


main.xml:

Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
   android:id="@+id/hello"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<TextView 
   android:id="@+id/lat"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Current Latitude:      unknown"
    />
<TextView 
   android:id="@+id/lon"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Current Longitude:      unknown"
    />
<TextView
   android:id="@+id/speed" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Current Speed (m/s):      unknown"
    />
<TextView
   android:id="@+id/kmph" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Current Speed (kmph):      unknown"
    />
<TextView
   android:id="@+id/avgspeed" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Average Speed (m/s):      unknown"
    />
<TextView
   android:id="@+id/avgkmph" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Average Speed (kmph):      unknown"
    />

</LinearLayout>


strings.xml:

Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">HartfordGPS</string>
    <string name="app_name">HartfordGPS</string>
</resources>


AndroidManifest.xml:

Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Hartford.gps"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GPSMain"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Re: getting gps location, calculating speed and showing on a

Postby da3dalu5 » Thu Jun 09, 2011 4:04 pm

New Code Update, Now uses a service for all the calculations and the main method is reserved for refreshing the display. I have also implimented a "WakeLock" to prevent the screen from turning off when the application is being displayed on the screen.

GPSMain.java:

Code: Select all
package Hartford.gps;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.widget.TextView;

public class GPSMain extends Activity   {

   //text views to display latitude and longitude
   static TextView latituteField;
   static TextView longitudeField;
   static TextView currentSpeedField;
   static TextView kmphSpeedField;
   static TextView avgSpeedField;
   static TextView avgKmphField;
   static TextView topSpeedField;
   static TextView topKmphField;

   //objects to store positional information
   protected static double lat;
   protected static double lon;

   //objects to store values for current and average speed
   protected static double currentSpeed;
   protected static double kmphSpeed;
   protected static double avgSpeed;
   protected static double avgKmph;
   protected static double totalSpeed;
   protected static double totalKmph;
   protected static double topSpeed=0;
   protected static double topKmph=0;

   //counter that is incremented every time a new position is received, used to calculate average speed
   static int counter = 0;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
      PowerManager.WakeLock wL = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"My Tag");

      wL.acquire();

      startService(new Intent(this, Calculations.class));

      latituteField = (TextView) findViewById(R.id.lat);
      longitudeField = (TextView) findViewById(R.id.lon);            
      currentSpeedField = (TextView) findViewById(R.id.speed);
      kmphSpeedField = (TextView) findViewById(R.id.kmph);
      avgSpeedField = (TextView) findViewById(R.id.avgspeed);
      avgKmphField = (TextView) findViewById(R.id.avgkmph);
      topSpeedField = (TextView) findViewById(R.id.topspeed);
      topKmphField = (TextView) findViewById(R.id.topkmph);

   }

   static void run(){

      latituteField.setText("Current Latitude:      "+String.valueOf(lat));
      longitudeField.setText("Current Longitude:      "+String.valueOf(lon));
      currentSpeedField.setText("Current Speed (m/s):      "+String.valueOf(currentSpeed));
      kmphSpeedField.setText("Cuttent Speed (kmph):      "+String.valueOf(kmphSpeed));
      avgSpeedField.setText("Average Speed (m/s):      "+String.valueOf(avgSpeed));
      avgKmphField.setText("Average Speed (kmph):      "+String.valueOf(avgKmph));
      topSpeedField.setText("Top Speed (m/s):      "+String.valueOf(topSpeed));
      topKmphField.setText("Top Speed (kmph):      "+String.valueOf(topKmph));

   }

}


Calculations.java:

Code: Select all
package Hartford.gps;

import java.math.BigDecimal;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class Calculations extends Service implements LocationListener  {

   static LocationManager locationManager;
   LocationListener locationListener;

   private static final String TAG = "Calculations";

   @Override
   public IBinder onBind(Intent intent) {
      // TODO Auto-generated method stub
      return null;
   }

   @Override
   public void onCreate() {
      Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
      Log.d(TAG, "onCreate");

      run();

   }

   private void run(){

      final Criteria criteria = new Criteria();

      criteria.setAccuracy(Criteria.ACCURACY_FINE);
      criteria.setSpeedRequired(true);
      criteria.setAltitudeRequired(false);
      criteria.setBearingRequired(false);
      criteria.setCostAllowed(true);
      criteria.setPowerRequirement(Criteria.POWER_LOW);
      //Acquire a reference to the system Location Manager

      locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

      // Define a listener that responds to location updates
      locationListener = new LocationListener() {

         public void onLocationChanged(Location newLocation) {

            GPSMain.counter++;

            //current speed for the GPS device
            GPSMain.currentSpeed = round(newLocation.getSpeed(),3,BigDecimal.ROUND_HALF_UP);
            GPSMain.kmphSpeed = round((GPSMain.currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);

            if (GPSMain.currentSpeed>GPSMain.topSpeed) {
               GPSMain.topSpeed=GPSMain.currentSpeed;
            }
            if (GPSMain.kmphSpeed>GPSMain.topKmph) {
               GPSMain.topKmph=GPSMain.kmphSpeed;
            }

            //all speeds added together
            GPSMain.totalSpeed = GPSMain.totalSpeed + GPSMain.currentSpeed;
            GPSMain.totalKmph = GPSMain.totalKmph + GPSMain.kmphSpeed;

            //calculates average speed
            GPSMain.avgSpeed = round(GPSMain.totalSpeed/GPSMain.counter,3,BigDecimal.ROUND_HALF_UP);
            GPSMain.avgKmph = round(GPSMain.totalKmph/GPSMain.counter,3,BigDecimal.ROUND_HALF_UP);

            //gets position
            GPSMain.lat = round(((double) (newLocation.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
            GPSMain.lon = round(((double) (newLocation.getLongitude())),3,BigDecimal.ROUND_HALF_UP);

            GPSMain.run();
         }

         //not entirely sure what these do yet
         public void onStatusChanged(String provider, int status, Bundle extras) {}
         public void onProviderEnabled(String provider) {}
         public void onProviderDisabled(String provider) {}

      };

      // Register the listener with the Location Manager to receive location updates
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);

   }



   //Method to round the doubles to a max of 3 decimal places
   public static double round(double unrounded, int precision, int roundingMode)
   {
      BigDecimal bd = new BigDecimal(unrounded);
      BigDecimal rounded = bd.setScale(precision, roundingMode);
      return rounded.doubleValue();
   }


   public void onLocationChanged(Location location) {
      // TODO Auto-generated method stub

   }

   public void onProviderDisabled(String provider) {
      // TODO Auto-generated method stub

   }

   public void onProviderEnabled(String provider) {
      // TODO Auto-generated method stub

   }

   public void onStatusChanged(String provider, int status, Bundle extras) {
      // TODO Auto-generated method stub

   }

}


AndroidManifest.xml:
(I have spaced out the code where new lines have been added (2 in total))

Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Hartford.gps"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>



    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>




    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GPSMain"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



   <service android:enabled="true" android:name=".Calculations" />



    </application>
</manifest>


strings.xml: same as before

main.xml: same as before
~D

“If you only do what you know you can do- you never do very much.”
da3dalu5
Junior Developer
Junior Developer
 
Posts: 13
Joined: Tue Apr 05, 2011 10:52 am

Top

Return to Map Problems

Who is online

Users browsing this forum: No registered users and 5 guests