Sometime we need to get
GPS coordinates in android. so today i am going to write step by step simple tutorial How can we get location coordinates using GPS in android mobile.
also through coordinate we can calculate current location more details like City Name.
Note: I have tested this app on My Android Mobile and its working fine.
But when you test this app, enable your gps settings in mobile, you need to change current location like 10-20 meter so you will get the coordinates, so need to move with the installed app mobile device.
What this app does?
-------------------------------------------
App Name: GetCurrentLocation
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: GetCurrentLocation
-------------------------------------------
GetCurrentLocation.java
main.xml
AndroidManifest.xml
The output Screen will be like this..
You can download the complete source code zip file here : GetCurrentLocation
cheers!!
I'd love to hear your thoughts!
also through coordinate we can calculate current location more details like City Name.
Note: I have tested this app on My Android Mobile and its working fine.
But when you test this app, enable your gps settings in mobile, you need to change current location like 10-20 meter so you will get the coordinates, so need to move with the installed app mobile device.
What this app does?
- Check gps is enable or disable.
- Get gps coordinates.
- Get the current city name.
-------------------------------------------
App Name: GetCurrentLocation
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: GetCurrentLocation
-------------------------------------------
GetCurrentLocation.java
package com.rdc; import java.io.IOException; import java.util.List; import java.util.Locale; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; public class GetCurrentLocation extends Activity implements OnClickListener { private LocationManager locationMangaer=null; private LocationListener locationListener=null; private Button btnGetLocation = null; private EditText editLocation = null; private ProgressBar pb =null; private static final String TAG = "Debug"; private Boolean flag = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //if you want to lock screen for always Portrait mode setRequestedOrientation(ActivityInfo .SCREEN_ORIENTATION_PORTRAIT); pb = (ProgressBar) findViewById(R.id.progressBar1); pb.setVisibility(View.INVISIBLE); editLocation = (EditText) findViewById(R.id.editTextLocation); btnGetLocation = (Button) findViewById(R.id.btnLocation); btnGetLocation.setOnClickListener(this); locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } @Override public void onClick(View v) { flag = displayGpsStatus(); if (flag) { Log.v(TAG, "onClick"); editLocation.setText("Please!! move your device to"+ " see the changes in coordinates."+"\nWait.."); pb.setVisibility(View.VISIBLE); locationListener = new MyLocationListener(); locationMangaer.requestLocationUpdates(LocationManager .GPS_PROVIDER, 5000, 10,locationListener); } else { alertbox("Gps Status!!", "Your GPS is: OFF"); } } /*----Method to Check GPS is enable or disable ----- */ private Boolean displayGpsStatus() { ContentResolver contentResolver = getBaseContext() .getContentResolver(); boolean gpsStatus = Settings.Secure .isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER); if (gpsStatus) { return true; } else { return false; } } /*----------Method to create an AlertBox ------------- */ protected void alertbox(String title, String mymessage) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Your Device's GPS is Disable") .setCancelable(false) .setTitle("** Gps Status **") .setPositiveButton("Gps On", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // finish the current activity // AlertBoxAdvance.this.finish(); Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS); startActivity(myIntent); dialog.cancel(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // cancel the dialog box dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } /*----------Listener class to get coordinates ------------- */ private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { editLocation.setText(""); pb.setVisibility(View.INVISIBLE); Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()+ " Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show(); String longitude = "Longitude: " +loc.getLongitude(); Log.v(TAG, longitude); String latitude = "Latitude: " +loc.getLatitude(); Log.v(TAG, latitude); /*----------to get City-Name from coordinates ------------- */ String cityName=null; Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); List<Address> addresses; try { addresses = gcd.getFromLocation(loc.getLatitude(), loc .getLongitude(), 1); if (addresses.size() > 0) System.out.println(addresses.get(0).getLocality()); cityName=addresses.get(0).getLocality(); } catch (IOException e) { e.printStackTrace(); } String s = longitude+"\n"+latitude + "\n\nMy Currrent City is: "+cityName; editLocation.setText(s); } @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
<?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" android:weightSum="1"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Get Current Location and City Name" android:layout_weight="0.20" android:gravity="center" android:textSize="20sp" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.33" android:id="@+id/editTextLocation" android:editable="false"> <requestFocus></requestFocus> </EditText> <LinearLayout android:id="@+id/layButtonH" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center" android:layout_weight="0.15"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get Location" android:id="@+id/btnLocation"></Button> </LinearLayout> <LinearLayout android:id="@+id/layloadingH" android:layout_height="wrap_content" android:layout_weight="0.20" android:layout_width="fill_parent" android:gravity="center"> <ProgressBar android:layout_width="wrap_content" android:id="@+id/progressBar1" android:layout_height="wrap_content"></ProgressBar> </LinearLayout> </LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rdc" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"> </uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".GetCurrentLocation" 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>
The output Screen will be like this..
You can download the complete source code zip file here : GetCurrentLocation
cheers!!
I'd love to hear your thoughts!
Kindly, Where is the layout file ?
ReplyDeleteya updated the code and also added complete source code zip file. hope it will help :)
Deletegreat work thanxs. try to implement map view too.
ReplyDeleteyour welcome rajkumar :), well.. last week i wrote Google Map tutorials. you can check http://rdcworld-android.blogspot.in/2012/07/google-map-tutorial-android-advance.html
Deletehow to test this code in the emulator??
DeleteThanks alot fa ur tutorial...:) Great work...!Cheers...!!
ReplyDeleteyour most welcome AB :)
Deletehey am getting an error.
ReplyDeleteThe method onProviderEnabled(String) of type GetCurrentLocation.MyLocationListener must override a superclass method
are you getting error in Listener class? then it happens some times because IDE doesn't load code properly, you should remove listener class code and write "private class MyLocationListener implements LocationListener " then click for implement UN-implemented methods then put the above code inside... let me know still if you have any trouble... or you may like to download complete zip code attached
DeleteWhere will the latitude/longitude and the current city name be displayed in? Is it in TextView? & why I can't get the values when tested in the phone?
ReplyDeleteThank you.
Yes! in "Edit Text" above "Get Location" button.. I was testing on mobile so couldn't manage to get Screen Shot, btw shortly I'll try to post one more image.
DeleteThank you very much.. Your code worked well
ReplyDeleteThank you so much.. Your code worked
ReplyDeleteMy pleasure :)
DeletePlease tell me how to give the long and lat manually in eclipse. I tried using emulator control to do this thing. but not working. Please tell me when to pass the lat and long in the eclipse or a video link about it. Please I'm in a very need of it.
ReplyDeleteI tried to run it in eclipse but don't know when to give the long and lat manually. Please tell me when should I give the value for it. before or while running the code in the emulator
ReplyDeletethankz for your code..............
ReplyDeleteHow can i send this location co ordinates to my mysql database...
ReplyDeleteYou may need to make request to server, Please look on google for HttpRequest or similar post in android
DeleteHey Rdc nice tutorial man,
ReplyDeletebut i need to use gps in background like if user's location get changed, then he will get a notification, even when the app is not running or he is using some other activity.
Help appreciated
Thanks
Sorry for late reply but For your need you should create background service and register Location manager with service so whenever you will get different location, you will get notification (toast)
Deletegreat work really awesome. Thanks A Lot
ReplyDeleteReally wonderful work. Thanks a lot.....:)
ReplyDeleteMy pleasure dear!! it helps you :)
Deletenice tutorial sir.. accidentally i opened this blog n felt very happy to see this. m also working on android platform.
ReplyDeleteThank you Avinash,, now-days I am trying to post more tutorials, Btw if you need any help just let me know dear :)
DeleteGood tutorial. I have question on this? You have used GPS provider always. What if I am under the roof. I am not able get the value. I would like to move to Network provider automatically and fetch the details. How do I do this?
ReplyDeleteGood tutorial. I have question on this? You have used GPS provider always. What if I am under the roof. I am not able get the value. I would like to move to Network provider automatically and fetch the details. How do I do this?
ReplyDeleteThank you Raam!! well I would say when you are under the roof, you can check whether provider is available or not and as per the result notification you can request for GPS data.
Deletethanks
ReplyDeletethanks and good tutorial.will u publish the tutorial of location based reminder??
ReplyDeleteYou'r welcome Ankita.. yes I am doing R & D on GPS reminder shortly I'll post here, now-days I am spending time on posting iPhone tutorials also, Greetings!! from RDC. for your valuable feedback.
DeleteAwesome! Thank you very much... works perfectly!
ReplyDeleteYour most welcome Sunil..
DeleteThis code is great its running very well,bt i want to check my current location only ones.hw to fat ??
ReplyDeleteThank you very much.. Your code worked well,i want chk my location only ones ,hw to do dat ??
ReplyDeleteHi, do you know if this is working with Android SDK 2.2 / API 8? Thank you in advanced.
ReplyDeleteyes It works fine with ndroid SDK 2.2 / API 8, I have tested on Android devices.
Deletethat works excellent.. thanks so much because also checked if the GPS is ON and GO to the configuration .. the only trouble I had, was that I had to change
ReplyDeletethe line number 91 in GetCurrentLocation.java
this:
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver,LocationManager.GPS_PROVIDER);
for this one:
boolean gpsSatus = android.provider.Settings.Secure.isLocationProviderEnabled(contRes, LocationManager.GPS_PROVIDER);
***
and line number 114 in GetCurrentLocation.java
Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
for this one:
Intent myIntent = new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
But both changes were because I'm programming under android 3.03 (API 15) I think.
****
so I check the code inside protected void alertbox(String title, String mymessage)
and I can't see where or when you use String title, String mymessage ?? or there are never used?. so THANKS a lot.
Thank you a lot for your Valuable feedback.. FYI, I used result string at line no 160.
DeletePlease! check the code
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
Yeah, that's right, I understood it... I refer to the method protected void alertbox(String title, String mymessage) at line 103.... that received the parameters title and mymessage , but these variables there never mention inside the method.. jeje but don't worry it's doesn't matter .. in fact the code works perfect.. so thanks again from Ecuador and forgive me for my english (it's not too good)
Delete¡gracias :) glad to know that it help you,, btw one day I'll come to Ecuador with My Guitar and will play some spicy and then I'll ask you "give me a treat".
Deletehelloo rd i am running this code in my simulator but was not able to get the location cordinates and city name. Should i have to send it manually from emulator control. please help...
ReplyDeleteHelloo Rd I am running this code in my eclipse simulator but I am not able to get the current location should I have to send it manually from emulator control.please help...
ReplyDeleteAnish, Yeah! if you are testing this app in Emulator then you have to pass co-ordinates in Emulator Controller using GPX or KML file.
DeleteHI RDC,
ReplyDeleteI am trying to run this code on android 4.2. After turn on GPS, when i press Get Location button a progress dialog is shown but happen nothing means i am not able to get desired result. Can you help out please?
Vikash after install app and you click button to get location you need to move device to another location then only onChangeLocation method gets called and we will get new location information. Plz! let me know still you have problem.
Deletew pogłowiu owiec a bydła nieоdmiennie
ReplyDeleteoѕkarżanο ωilki a http://fajniejest.keed.pl/ złodziei.
Sіr Roger słuchаł zdumiony. - Nie uwierzуcie, κobiety - wуskandował Αrnolԁ
przyсіszonym głosem,
rozglądając się powątpiewаjąсo na jako że.
thanks u are so gentil man ;)
ReplyDeletethanks !! u are so gentil man ;)
ReplyDeletehehe.. Ameni Thank you for your kind worlds :)
Deleteworking awsome dude.... thanks for the share (y)
ReplyDeletei use this to turn gps on/off programmatically
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")) {
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}
}
private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")) {
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}
}
Arun, Great to here that!! :) keep rocking \m/
DeleteA great blog indeed......I want to update these gps points to a database...hope u can help
ReplyDeletehey i tested this on my phone it gave me longitude and latitude bt dint give me current city??? what to do please help me bro :)
ReplyDeleteSunil, well i tested, it gives GPS coordinates and city name as well, but I would you say for getting city name we do request for Geocoder so sometime if we don't get response from geo then may be this happen
Delete[Reason: We can't get all address. No one promised every set of coordinates will return an address ]
I run it on my tablet. I can see coordinate but city name is null. how can i fix it?
ReplyDeleteHello RDC, Thanks for your tutorial.But i want to know that can we get location and status manually,means without righting listener class.Hope you will help me.
ReplyDeleteActually i have created a timer.Which will run on every 10 seconds time interval. I want to get the location as well as status of in every 10 seconds time interval.
I used listener but it didnt work as per my requirement.
Hope you will help me.
Wow Awesome really great...... Im searching for this for a month.... now i got it...... Thanks Dude...... Thanks a lot.... :) :) :)
ReplyDeleteWow awesome...... Its working good..... im searching for this code for a month....
ReplyDeletenow i got it.....
Thank You Dude..... Thank you so much.... Great work....
i wanna follow your tutorial where can i find?.....
Most welcome dear!! Really glad to know that my code was helpful for you :)
DeleteIf you want to follow my blog, you need to login with your gmail account and then there is option in right side bottom, also you can read this page for more help
[ http://support.google.com/blogger/bin/answer.py?hl=en&answer=104226 ]
Regards,
RDC
Great job .... keep it up :)
ReplyDeleteyeah sure,, A Grand welcome from INDIA .. :)
Deletesalut,svp sa marche pas sur mon émulateur?
ReplyDeleteHow you test this code by using android emulator?
ReplyDeletehii...i need code to connect several android mobiles through their GPS to display their locations while calling...
ReplyDeletewow nice ;)
ReplyDeletewhat if more details of the city, such as a district or village?
Amazing...works great
ReplyDeleteToo good...
ReplyDeleteCan you also create a program to give altitude along with this?
ReplyDeleteHi ur work r great :)
ReplyDeleteHow to Find Specific Nearby Locations in android
Good work.
ReplyDeleteBut i'm wondering if i can get the coordinates without moving.
Thanks for your Great Post,i tested it on Galaxy S4 and it works well,but when you click on GPS On button it shown security setting,but in S4 security and location setting are separate,so i chenged line 106 to :
ReplyDeleteIntent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
And Solved
thank you very much
ReplyDeleteit does works
hello, i want the app to detect the GPS location of the mobile and automatically turn off the app when the mobile is moved out from a particular area. suppose i have a vast land of 400 acres. i should be able to access the app only in this area. once i come out of my land the i should not be able to access the app.. how to do this? can i get a step by step tutorial for this?? plz help me...
ReplyDeleteHi Great code.
ReplyDeleteIs it possible for you to make the code in a background service??
Nice code Thank u
ReplyDeleteThank u Very much. The code is working but i need the exact location can u give any idea. plz any one can help. send mail plz
ReplyDeleteI want to modify this code, so that I can get the location every second and store it in a file. How can I go for it?
ReplyDeleteHi, I'd like to use your code to add city name in my App.
ReplyDeleteInstead of click button, I want to call GetCurrentLocation class directly when my main class opens.
I did change class name from GetCurrentLocation to Localizacao.
Added in my main class:
Localizacao localiza = new Localizacao();
MyLocationListener dadosGPS = localiza.new MyLocationListener();
System.out.println(Localizacao.localizacaoGPS);
What could be wrong? Could give me this BIG help? Thanx!!
hi i am new to android!! i cant find the current location its just loading and showing searching for gps in notification bar!! pls help out
ReplyDeleteThank you very much for this tutorial. Can u tell me that how to get exact location with automatically turned on gps location provider and also i want that no any user can turned off their gps location provider manually..
ReplyDeletei got latitude and longitude but my current city is being shown "my current city is null"
ReplyDeleteplz help me.!
I am getting CITY as null
ReplyDeleteThanks A lot ,, please, how can I get address instead of city ( district and street )
ReplyDeleteHi RDC,
ReplyDeleteGreat Work.
But i am facing one issue, i am not getting lat n log. Activity in showing with process. Even though i am moving my device also. i am using htc one s for testing.
Please help me to resolve this issue
Thanks a lot. It worked. Great. Excellent. Keep posting.
ReplyDeleteI tried your code. It worked well. I wanna one more spec or feature. Now I can get latitude, longitude and city name. I wanna area and street name. Is it possible? Please reply.
ReplyDeletei found a TYPO: "locationMangaer" instead of "locationManager"
ReplyDelete