Wednesday, June 5, 2013

Android How to get device current speed using GPS | Get current speed using Network and GPS in Android

This simple code for getting device current speed using GPS. you can use Network Provider also..



package com.geofence.alarm;

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.Toast;

import com.example.geofenceapp.R;

public class SpeedAlarmActivity extends Activity {
	Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_speed_alarm);
		// 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 location) {
				location.getLatitude();
				Toast.makeText(context, "Current speed:" + location.getSpeed(),
						Toast.LENGTH_SHORT).show();

			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			public void onProviderEnabled(String provider) {
			}

			public void onProviderDisabled(String provider) {
			}
		};
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, locationListener);

	}

}

Thanks,

111 comments:

  1. This is good but it lacks the XML files....would you please send me the whole project to my email address (morisatwine@gmail.com)...thanks in advance...

    ReplyDelete
  2. No There is no need of any xml file just create an empty xml layout no view in this file..
    But in you manifest.xml you have to add some permission-

    android:name="android.permission.INTERNET"
    android:name="android.permission.ACCESS_NETWORK_STATE"
    android:name="android.permission.READ_PHONE_STATE"
    android:name="android.permission.ACCESS_COARSE_LOCATION"
    android:name="android.permission.ACCESS_FINE_LOCATION"

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Is this permission required???? android:name="android.permission.READ_PHONE_STATE

    ReplyDelete
  5. Now what if I wanted this code to cycle through every 5 seconds

    ReplyDelete
    Replies
    1. See this line-
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
      0, locationListener);

      Just change it according your requirement after how many time or distance you want speed.

      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
      0, locationListener);

      Hope it will help you...

      Delete
  6. Thanks you ,sir. (from Thailand.)

    ReplyDelete
  7. Thanks for this tutorial, by inspiring with this tutorial i have created a program in which GPS running in services, my program running well but my problem is whenever i am driving for few minutes its work fine its update longitude and latitude but after some time this will not updating longitude and latitude and terminate my program if you have any idea why this is happen please guide me with solution thanks in advance

    ReplyDelete
    Replies
    1. I think problem with Service provider, please use best service provider- means
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
      0, locationListener);
      and

      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
      0, locationListener);

      May be at the time of driving your device is not getting update from GPS.

      Delete
  8. So im curious..i have followed this but it stops unexpectedly? Not sure what is wrong

    ReplyDelete
    Replies
    1. Can you paste your log-cat here please? I think problem with your package name or in your manifest. Have you given permission in your manifest?-
      android:name="android.permission.INTERNET"
      android:name="android.permission.ACCESS_NETWORK_STATE"
      android:name="android.permission.READ_PHONE_STATE"
      android:name="android.permission.ACCESS_COARSE_LOCATION"
      android:name="android.permission.ACCESS_FINE_LOCATION"

      Delete
    2. I also have the same problem

      Delete
  9. no toast is displaying...! how could i calculate the speed of the device , i tried so many time using getspeed() method which is in location class but no using. any guess

    ReplyDelete
    Replies
    1. 1)Please check your manifest, have you given all permissions?
      2) Try ones GPS to Network Provider in below line-locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,0, locationListener);
      3)And some times it happen Location Listener does not provide any thing us. So no worry try on another device. Or create any other demo app first for testing first.

      :) Hope its only thing and hope you have did all but please check ones more time..
      Thanks!

      Delete
  10. Hey, I have developed one app that will calculate the distance and speed while travelling on vehicle also I am getting distance covered from one location to another but I can't get the speed while walking. What would be the problem can you suggest me?

    ReplyDelete
    Replies
    1. may be when you walking fast your GPS not working. So please enable network and GPS service provider both..

      I mean check for best service provider use what ever available. And for getting distance search on google there a API for that just pass your first and last lat,lon it will return you distance.

      Delete
    2. Hi ...Saurabh Pandya can you please post the code how to calculate the distance and speed ...

      Delete
    3. @Alampally Please see above my code for calculate speed
      location.getSpeed()
      and for distance use-
      Location.distanceBetween();
      see this link-
      http://developer.android.com/reference/android/location/Location.html

      Delete
  11. I'm a complete noob! Could you please tell me exactly where inside the manifest I should put the permissions, and what tags I should use. Thank you in advance!

    ReplyDelete
    Replies
    1. never mind, I just figured this out!Works perfect, thank you for the code!

      Delete
    2. Hi i'm a beginner of android development.i need to calculate the gps device travelling speed. and that updation on every minute, please help me...

      Delete
  12. Hi i'm a beginner of android development.i need to calculate the gps device travelling speed. and that updation on every minute, please help me....

    ReplyDelete
    Replies
    1. This post did not helped you?
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000x60,
      0, locationListener);

      it will give you toast after every 1 min.

      Delete
    2. Ehm, Did You mean 1000*60 instead 1000x60 ?
      :D

      Delete
    3. @Aditya yes it is 1000*60 :) , I just gave logic not running code so please adjust it.

      Delete
  13. Hi, i tried your code and followed all your steps including manifest permissions, but when i execute this, it is displaying only Hello world!, since i am new to android, can u please help me to know what is the problem?

    ReplyDelete
    Replies
    1. As I am using "LocationManager.GPS_PROVIDER" so please check your device should be enable GPS and you should be out side becuase in-side GPS did not work.

      Or you cane use Netwrok provider..

      Delete
    2. Actually i am checking it in emulator, does GPS is there in emulator?

      Delete
    3. No dear! you can think it your self how you can get emulator speed when in is not moving? you should use mobile phone and should walk or run for device speed.

      In case of emulator you can pass lat, long but ones only for displaying map and etc but not for getting speed.

      Delete
    4. Ya sorry..i got it! i will check it in real device.

      Delete
  14. Hi,thanks a lot it worked in android device, i need one more help from you, can u please lsend me code for how to send gps coordinates to server, because my app is crashing when i try to send it to server, please help me,i need to do it very urgent.... kulkarni.anandr100@gmail.com, thanks in advance

    ReplyDelete
  15. sir,toast is not being shown .plz help me.!

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. i have followed all the steps ,but toast is not showing . :(

    ReplyDelete
  18. Hi, Thank you for your coding. But in my application I used another class for location Manager,LocationListener and onLocationChanged function, that means all location related things are separate file from MainActivity file. So, my question is: how I can get the speed value in MainActivity.java file from that location.java file.

    Also, please let me know how I can find of device current direction as degree?

    ReplyDelete
  19. Hello sir, i am developing an apps that is the same as your example, but i want to add sound (warning sound) whenever the speed limit is reached (or exceeded). for example if the movement is above 80 km/h, a sound will be heard...what should i add? thanks ;)

    ReplyDelete
    Replies
    1. You should use Notification manager. Some thing like that-

      when you reach @ 80 km/h speed just call this method and pass a message what you want to show-

      /**
      * Issues a notification to inform the user that server has sent a message.
      */
      private static void generateNotification(Context context, String message) {
      int icon = R.drawable.ic_launcher;
      long when = System.currentTimeMillis();
      NotificationManager notificationManager = (NotificationManager) context
      .getSystemService(Context.NOTIFICATION_SERVICE);
      Notification notification = new Notification(icon, message, when);
      String title = context.getString(R.string.app_name);
      Intent notificationIntent = new Intent(context, MainActivity.class);
      notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
      | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      PendingIntent intent = PendingIntent.getActivity(context, 0,
      notificationIntent, 0);
      notification.setLatestEventInfo(context, title, message, intent);
      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      notificationManager.notify(0, notification);
      }
      }

      Read more: http://www.androidhub4you.com/2013/04/google-cloud-messaging-example-in.html#ixzz2wguh3Nl8

      Delete
    2. Hello,
      I am trying to doing the same as your example but i want to send notification whenever the speed exceeds 60 km/h. so plz send me the code of doing so on my id- dubeydeepti8@gmail.com.

      Thanks
      Deepti

      Delete
    3. Hi Deepti, the above comment did not work for you? Just add a condition there if speed>60 call the notification method.

      Delete
  20. Hello,
    I just started develeping in android so i'm basically just a beginer but for my project i need to realise an application that sends email automatically every like 5 minutes or every given parametre (like those 5 minutes can be changed to 10 munutes or something ) Can you help me ?

    ReplyDelete
  21. You can use Alarm Manager for this. Check this article-
    http://www.androidhub4you.com/2013/12/android-alarm-manager-example-how-to.html

    ReplyDelete
  22. I have planned to make application having the feature of measuring speed of car using android phone to warn when speed limit exceeded.
    I think your code will be very much helpful for me.
    Thanks in advance

    ReplyDelete
  23. hey can uplz tell me how to find friend location exactly using gps and it should show the way to reach the friend ,where he is standing at some point........mi id- sravanipractice@gmail.com

    ReplyDelete
  24. Sir! can u mail source code to moghilisairam@gmail.com. thanks in advance :)

    ReplyDelete
  25. Hi i am trying to install the above app in my Galaxy S4. I keep getting unfortunately app has stopped. Could you please help me?

    ReplyDelete
  26. Sir! can u mail source code to sardartashaf@gmail.com
    . thanks in advance :)

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Sir, can you please explain the SpeedAlarmActivity as a Service for an application? please

    ReplyDelete
  29. How can i track speed and distance in my application and please be open show the interface for this also. Thanks

    ReplyDelete
    Replies
    1. For the distence here google APIs just pass the starting and end point lat/lon.

      Delete
  30. hello sir...
    in google map, i pointed two locations.. say A and B.. Now i travelled some distance.. i want to know how much i travelled at every gps locations changes.. say every 30 secs...

    ReplyDelete
  31. Hi,how can i set current speed on Image view or Text view please reply .

    ReplyDelete
  32. Someone post the screenshots of this app while the speed is displayed....
    Thank you!!!!

    ReplyDelete
  33. Hi, how does this code impact battery if the service is always left running in the background?
    Thanks

    ReplyDelete
  34. Hi, Is it work in lower version devices (below 2.3 version). Because i tried in the 2.2 it's not working.

    ReplyDelete
    Replies
    1. I am not sure but is should work to API Level-8, kindly check it with GPS/Network/WIFI may be some thing work for you. Sometime device does not provide location so please try it later or try many time.

      Delete
  35. Is this line required for the application to work?
    import com.example.geofenceapp.R;
    If yes, where is it located? (it looks like an application you once created)

    ReplyDelete
  36. sir i am new in android..i want to make an app vehicle tracking system offline project..in which user can input bike name, how much current distance he/she covered, and expected mileage. when login there is a option or button for filling fuel which starts to track vehicle from filling station and track how much distance covered in fuel(quantity)....please help sir ..how to code

    ReplyDelete
    Replies
    1. please send it to me at danishalam6@gmail.com.....it will help to understand a lot..
      please sir humble request...................ASAP if it possible

      Delete
    2. Danish, I don't have any code for your specific requirement but I can guide you to make your project done. follow below step to make it done-
      1)Create your UI according to your requirement.
      2)Make input box to take input like distance and mileage.
      3)For calculating the speed and distance use above code.
      4)Now you can indicate to user if fuel is low using notification.

      Nothing challenging here you can do it easily and keep in mind GPS is never accurate so please don't depend on it.

      Delete
  37. hi sir, i get the speed from your tutorials but it giving speed not accurate one...5 sec span is given to location updater then also it does not giving correctly so any suggestions....?

    ReplyDelete
  38. I am really new to android studio and I have these several problems below
    -I got a red underline for "locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);"
    -do I have to import this? "import com.example.geofenceapp.R;"
    -the "activity_speed_alarm" is shown in red and it says cannot resolve symbol 'activity_speed_alarm'
    -Where exactly do I put the permission codes in manifests?
    Thank you for your sharing

    ReplyDelete
  39. how display update speed current speed

    ReplyDelete
    Replies
    1. That toast is current updated speed. You can put it inside textview.

      Delete
  40. sir please send textview coding

    ReplyDelete
    Replies
    1. TextView text=(TextView)findviewbyId(R.id.textView1);
      text.setText(String.valueOf(location.getLocation());

      Delete
  41. Hi sir,

    I have the same problems as "Herman Tam" -August 6, 2015 at 5:35 AM.
    I am using android studio and the problem are in the lines:
    "
    import com.example.geofenceapp.R;
    "
    "
    setContentView(R.layout.activity_speed_alarm);
    "
    "
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    "
    the first two errors say"cannot resolve symbol".
    the last error seems to persist even after implementing your permissions in manifest.xml

    please reply even if you cant help us.
    thanks for sharing

    ReplyDelete
  42. Manish,
    First of all thank you for the code.
    I have mine displaying in a TextView and it works fine, however speed is shown as a decimal (e.g, 20.345678). Also, when I am doing 80km/h, speed is showing as 20.nnnnn.

    Can you please shed some light on how to display the correct speed in km/h?

    Regards,
    Michael C.

    ReplyDelete
    Replies
    1. Fixed...
      I used Math.round and multiplied getSpeed() * 3.6

      Android Studio complained about how I have constructed the string but it works for me.

      TextView text = (TextView) findViewById(R.id.txtSpeed);
      text.setText(String.valueOf(Math.round(location.getSpeed() * 3.6))+ " Km/h");

      Delete
  43. please send me all project code on my email:-androidapp.developer.in@gmail.com

    ReplyDelete
    Replies
    1. Sorry dear, I lost my workspace. Copy paste from above.

      Delete
  44. Hi Manish - Thanks for the code. Is it possible to get the speed value every second using your code.

    ReplyDelete
    Replies
    1. make changes at below line-

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

      Note: The first 0 is stand for distance in miles and 1000 is stand for time to update location in every 1 second.

      Delete
  45. Hello Manish,
    I try your app, but does not work. Can you help me please?
    My logcat:
    02-21 20:01:01.088 3773-3773/com.tomasruml.mysm I/art: Not late-enabling -Xcheck:jni (already on)
    02-21 20:01:01.402 3773-3773/com.tomasruml.mysm W/System: ClassLoader referenced unknown path: /data/app/com.tomasruml.mysm-2/lib/x86
    02-21 20:01:01.624 3773-3773/com.tomasruml.mysm D/AndroidRuntime: Shutting down VM
    02-21 20:01:01.653 3773-3773/com.tomasruml.mysm E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tomasruml.mysm, PID: 3773
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tomasruml.mysm/com.tomasruml.mysm.MainActivity}: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at ... 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
    02-21 20:01:08.724 3773-3773/com.tomasruml.mysm I/Process: Sending signal. PID: 3773 SIG: 9

    Best regards,
    Tomas

    ReplyDelete
    Replies
    1. Add ACCESS_FINE_LOCATION in manifest.xml.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. My AndoridManifest.xml:

      ?xml version="1.0" encoding="utf-8"?>
      manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.tomasruml.mysm">

      application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      activity android:name=".MainActivity">
      intent-filter>
      action android:name="android.intent.action.MAIN" />

      permission android:name="android.permission.INTERNET" />
      permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      permission android:name="android.permission.READ_PHONE_STATE" />
      permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      permission android:name="android.permission.ACCESS_FINE_LOCATION" />

      category android:name="android.intent.category.LAUNCHER" />
      /intent-filter>
      /activity>
      /application>



      /manifest>


      With < at the begin line of course, but this page does not showing code with < at the begin.
      It does not work. How can I fix it?
      Best regards,
      Tomas

      Delete
  46. Take all the permissions above to application tag-

    permission android:name="android.permission.INTERNET" />
    permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    permission android:name="android.permission.READ_PHONE_STATE" />
    permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    activity android:name=".MainActivity">
    intent-filter>
    action android:name="android.intent.action.MAIN" />


    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hello Manish,

      ok great it is work on my device, but I can not see current speed. Only text Hello world.
      How can I fix it?
      Can you help me please?

      Best regards,
      Tomas

      Delete
  47. Hello sir, I am a beginner in android development and I am making a similar app like yours. But here I am calculating Distance covered and speed together under one button click. I have to show these as textviews. My app will show speed nd distance covered while on move as button is pressed. A stopwatch was also their. Please help me out how can i calculate both simultaneously in a single button click. Waiting for your reply.

    ReplyDelete
    Replies
    1. I think you can store speed and distance into any List or Array and on button press calculate and display the result.

      Delete
  48. sorry does this app require an internet connection or just enable the gps ??

    ReplyDelete
    Replies
    1. There are 2 option 1 is using GPS and another is your network provider. You can see below line of code, it is required your GPS-
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
      0, locationListener);

      You can change it to Network provider if needed.

      Delete
  49. hello sir.
    I need to know how to get the calories burned from the distance he or she walk. is it possible. if, can you pls add the code here or do I need to send my email. thanks...

    ReplyDelete
    Replies
    1. There must be some algorithm to calculate burn calories. You can see gym machines they display burn calories according to your speed and distance covered. Please contact to any specialist regarding this.

      Delete
  50. hello sir,
    I am new in this.i created user login page and after that it is showing current location.i created mainactivity and maps activity.i want to track speed under maps.where do i insert this code.

    ReplyDelete
    Replies
    1. sir,
      where do i insert this code.My maps activity code is-
      public class MapsActivity extends FragmentActivity {

      private GoogleMap mMap; // Might be null if Google Play services APK is not available.

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_maps);
      setUpMapIfNeeded();

      }

      @Override
      protected void onResume() {
      super.onResume();
      setUpMapIfNeeded();
      }


      private void setUpMapIfNeeded() {
      // Do a null check to confirm that we have not already instantiated the map.
      if (mMap == null) {
      // Try to obtain the map from the SupportMapFragment.
      mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
      .getMap();
      // Check if we were successful in obtaining the map.
      if (mMap != null) {
      setUpMap();
      }
      }
      }


      private void setUpMap() {
      mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
      mMap.setMyLocationEnabled(true);
      }


      }

      Delete
  51. sir,i am not getting speed.my code is-


    public class MapsActivity extends FragmentActivity {
    Context context;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    LocationManager locationManager = (LocationManager) this
    .getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener()
    { public void onLocationChanged(Location location)
    { location.getLatitude(); Toast.makeText(context, "Current speed:" + location.getSpeed(), Toast.LENGTH_SHORT).show(); }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    } public void onProviderEnabled(String provider) {
    } public void onProviderDisabled(String provider) {
    } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    TextView txtCurrentSpeed = (TextView) this.findViewById(R.id.textView3);

    txtCurrentSpeed.setText("Current speed:");
    }

    please suggest me.

    ReplyDelete
  52. Sir I want that speed is set by user and after that alarm beeps
    How to do this.
    Can u please help me

    ReplyDelete
    Replies
    1. Do Something like-

      1)// Define a listener that responds to location updates
      LocationListener locationListener = new LocationListener() {
      public void onLocationChanged(Location location) {
      location.getLatitude();
      if(location.getSpeed()>50){

      NotifyToUser();
      }
      }


      2)public void NotifyToUser(){
      //write Notification Code using notification builder

      }

      Delete
    2. sir,can you please give a code for notifytouser

      Delete
    3. You can follow below link-
      Read more: http://www.androidhub4you.com/2013/04/google-cloud-messaging-example-in.html#ixzz4B9BGGaTm


      /**
      * Issues a notification to inform the user that server has sent a message.
      */
      private static void generateNotification(Context context, String message) {
      int icon = R.drawable.ic_launcher;
      long when = System.currentTimeMillis();
      NotificationManager notificationManager = (NotificationManager) context
      .getSystemService(Context.NOTIFICATION_SERVICE);
      Notification notification = new Notification(icon, message, when);
      String title = context.getString(R.string.app_name);
      Intent notificationIntent = new Intent(context, MainActivity.class);
      notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
      | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      PendingIntent intent = PendingIntent.getActivity(context, 0,
      notificationIntent, 0);
      notification.setLatestEventInfo(context, title, message, intent);
      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      notificationManager.notify(0, notification);
      }
      }

      Delete
  53. hi manish, thanks for the code tips, i just started android, and most helpful has been your site, could i have a copy of the full code for the speed display in google maps, all else works fine, except not display speed, will read it before bothering you.
    cheers carl ranalli

    ReplyDelete
  54. Hi, do I still get speed if I change provider to network?

    ReplyDelete
  55. on walking location.getSpeed() get speed when we walk above 5 mph..please suggest any other idea to get speed when we walk 2mph..

    ReplyDelete
  56. can you give me the code for activity_speed_alarm please

    ReplyDelete
  57. Hi
    I have one array which contain number of lat long in sequence which i travel
    Based on this how to get travel distance average speed.

    suggest me any example

    Thanks

    ReplyDelete