This simple code for getting device current speed using GPS. you can use Network Provider also..
Thanks,
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,
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...
ReplyDeleteNo There is no need of any xml file just create an empty xml layout no view in this file..
ReplyDeleteBut 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"
wow, thanks
ReplyDeleteThanks for your nice comment.
DeleteThis comment has been removed by the author.
ReplyDeleteIs this permission required???? android:name="android.permission.READ_PHONE_STATE
ReplyDeleteYes it is required!
DeleteNice code, very clear. Tks
ReplyDeletenice sir!!!!
ReplyDeleteYour welcome!
DeleteNow what if I wanted this code to cycle through every 5 seconds
ReplyDeleteSee this line-
DeletelocationManager.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...
Thanks you ,sir. (from Thailand.)
ReplyDeleteYour Welcome & Thanks(from India :))
DeleteThanks 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
ReplyDeleteI think problem with Service provider, please use best service provider- means
DeletelocationManager.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.
So im curious..i have followed this but it stops unexpectedly? Not sure what is wrong
ReplyDeleteCan 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?-
Deleteandroid: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"
I also have the same problem
Deleteno 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
ReplyDelete1)Please check your manifest, have you given all permissions?
Delete2) 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!
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?
ReplyDeletemay be when you walking fast your GPS not working. So please enable network and GPS service provider both..
DeleteI 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.
Hi ...Saurabh Pandya can you please post the code how to calculate the distance and speed ...
Delete@Alampally Please see above my code for calculate speed
Deletelocation.getSpeed()
and for distance use-
Location.distanceBetween();
see this link-
http://developer.android.com/reference/android/location/Location.html
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!
ReplyDeletenever mind, I just figured this out!Works perfect, thank you for the code!
DeleteGrate!
DeleteHi 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...
DeleteHi 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....
ReplyDeleteThis post did not helped you?
DeletelocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000x60,
0, locationListener);
it will give you toast after every 1 min.
Ehm, Did You mean 1000*60 instead 1000x60 ?
Delete:D
@Aditya yes it is 1000*60 :) , I just gave logic not running code so please adjust it.
DeleteHi, 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?
ReplyDeleteAs 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.
DeleteOr you cane use Netwrok provider..
Actually i am checking it in emulator, does GPS is there in emulator?
DeleteNo 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.
DeleteIn case of emulator you can pass lat, long but ones only for displaying map and etc but not for getting speed.
Ya sorry..i got it! i will check it in real device.
DeleteHi,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
ReplyDeleteGot the great help thanks...
ReplyDeletesir,toast is not being shown .plz help me.!
ReplyDeleteThis comment has been removed by the author.
ReplyDeletei have followed all the steps ,but toast is not showing . :(
ReplyDeleteHi, 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.
ReplyDeleteAlso, please let me know how I can find of device current direction as degree?
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 ;)
ReplyDeleteYou should use Notification manager. Some thing like that-
Deletewhen 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
Hello,
DeleteI 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
Hi Deepti, the above comment did not work for you? Just add a condition there if speed>60 call the notification method.
DeleteHello,
ReplyDeleteI 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 ?
You can use Alarm Manager for this. Check this article-
ReplyDeletehttp://www.androidhub4you.com/2013/12/android-alarm-manager-example-how-to.html
I have planned to make application having the feature of measuring speed of car using android phone to warn when speed limit exceeded.
ReplyDeleteI think your code will be very much helpful for me.
Thanks in advance
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
ReplyDeleteSir! can u mail source code to moghilisairam@gmail.com. thanks in advance :)
ReplyDeleteHi i am trying to install the above app in my Galaxy S4. I keep getting unfortunately app has stopped. Could you please help me?
ReplyDeleteSir! can u mail source code to sardartashaf@gmail.com
ReplyDelete. thanks in advance :)
This comment has been removed by the author.
ReplyDeleteSir, can you please explain the SpeedAlarmActivity as a Service for an application? please
ReplyDeleteHow can i track speed and distance in my application and please be open show the interface for this also. Thanks
ReplyDeleteFor the distence here google APIs just pass the starting and end point lat/lon.
Deletehello sir...
ReplyDeletein 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...
Hi,how can i set current speed on Image view or Text view please reply .
ReplyDeleteSomeone post the screenshots of this app while the speed is displayed....
ReplyDeleteThank you!!!!
Hi, how does this code impact battery if the service is always left running in the background?
ReplyDeleteThanks
Hi, Is it work in lower version devices (below 2.3 version). Because i tried in the 2.2 it's not working.
ReplyDeleteI 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.
DeleteIs this line required for the application to work?
ReplyDeleteimport com.example.geofenceapp.R;
If yes, where is it located? (it looks like an application you once created)
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
ReplyDeleteplease send it to me at danishalam6@gmail.com.....it will help to understand a lot..
Deleteplease sir humble request...................ASAP if it possible
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-
Delete1)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.
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....?
ReplyDeleteI am really new to android studio and I have these several problems below
ReplyDelete-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
how display update speed current speed
ReplyDeleteThat toast is current updated speed. You can put it inside textview.
Deletesir please send textview coding
ReplyDeleteTextView text=(TextView)findviewbyId(R.id.textView1);
Deletetext.setText(String.valueOf(location.getLocation());
Hi sir,
ReplyDeleteI 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
Manish,
ReplyDeleteFirst 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.
Fixed...
DeleteI 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");
Cool!!!
Deleteplease send me all project code on my email:-androidapp.developer.in@gmail.com
ReplyDeleteSorry dear, I lost my workspace. Copy paste from above.
DeleteHi Manish - Thanks for the code. Is it possible to get the speed value every second using your code.
ReplyDeletemake changes at below line-
DeletelocationManager.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.
Thanks Manish.
ReplyDeleteyour welcome!
DeleteHello Manish,
ReplyDeleteI 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
Add ACCESS_FINE_LOCATION in manifest.xml.
DeleteThis comment has been removed by the author.
DeleteMy AndoridManifest.xml:
Delete?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
Take all the permissions above to application tag-
ReplyDeletepermission 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" />
This comment has been removed by the author.
DeleteHello Manish,
Deleteok 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
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.
ReplyDeleteI think you can store speed and distance into any List or Array and on button press calculate and display the result.
Deletesorry does this app require an internet connection or just enable the gps ??
ReplyDeleteThere 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-
DeletelocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,
0, locationListener);
You can change it to Network provider if needed.
hello sir.
ReplyDeleteI 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...
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.
Deletehello sir,
ReplyDeleteI 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.
You can do it on Map Activity.
Deletesir,
Deletewhere 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);
}
}
sir,i am not getting speed.my code is-
ReplyDeletepublic 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.
Sir I want that speed is set by user and after that alarm beeps
ReplyDeleteHow to do this.
Can u please help me
Do Something like-
Delete1)// 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
}
sir,can you please give a code for notifytouser
DeleteYou can follow below link-
DeleteRead 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);
}
}
Hi, do I still get speed if I change provider to network?
ReplyDeleteon walking location.getSpeed() get speed when we walk above 5 mph..please suggest any other idea to get speed when we walk 2mph..
ReplyDeletecan you give me the code for activity_speed_alarm please
ReplyDeleteHi
ReplyDeleteI 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