How can I get my current location in Android using GPS?
Solution 1
In your AndroidManifest.xml, you have to put this above or below the application tag.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Because you did not show your code what you have been doing, so I have no clue how to resolve your problems. But the below code is the code I use for my application to get the current country of users.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
Location gps_loc;
Location network_loc;
Location final_loc;
double longitude;
double latitude;
String userCountry, userAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = findViewById(R.id.text_view);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
network_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
e.printStackTrace();
}
if (gps_loc != null) {
final_loc = gps_loc;
latitude = final_loc.getLatitude();
longitude = final_loc.getLongitude();
}
else if (network_loc != null) {
final_loc = network_loc;
latitude = final_loc.getLatitude();
longitude = final_loc.getLongitude();
}
else {
latitude = 0.0;
longitude = 0.0;
}
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE}, 1);
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
userCountry = addresses.get(0).getCountryName();
userAddress = addresses.get(0).getAddressLine(0);
tv.setText(userCountry + ", " + userAddress);
}
else {
userCountry = "Unknown";
tv.setText(userCountry);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You will have to understand this code. One more thing, if you run your application on an emulator, it will keep showing "United States" or more specifically, Googleplex's location. Just run it on a real device to make it return your current location.
To return your current location other than just country itself, you can replace the
addresses.get(0).getCountryName()
with something like
addresses.get(0).getPostalCode()
or
addresses.get(0).getAdminArea()
and so on.
You can too concatenate the values as a string to show your current location in detail.
Please have a look at this
Solution 2
You can use Google's Fused Location Profivider API library to get and access your current location (given that your GPS service is turned on)
Also don't forget to add this to your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
For a more detailed tutorial you can refer at this Medium GPS Tutorial
Cheers
Solution 3
Please try the below way here you can get location using the gps and network both
public class LocationTracker {
public static String TAG = LocationTracker.class.getName();
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000;
protected LocationManager locationManager;
static Context mcontext;
private static LocationTracker instance;
public static synchronized LocationTracker getInstance(Context ctx) {
mcontext = ctx;
if (instance == null) {
instance = new LocationTracker();
}
return instance;
}
myListener listener;
public void connectToLocation(myListener listener) {
this.listener=listener;
stopLocationUpdates();
displayLocation();
}
private void displayLocation() {
try {
Logger.i(TAG,"displayLocation");
Location location = getLocation();
if (location != null) {
updateLattitudeLongitude(location.getLatitude(), location.getLongitude());
}
} catch (SecurityException e) {
ExceptionHandler.printStackTrace(e);
} catch (Exception e) {
ExceptionHandler.printStackTrace(e);
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mcontext
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
this.canGetLocation = false;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
Logger.d(TAG + "-->Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationProviderListener);
return location;
}
} else if (isGPSEnabled) {
Logger.d(TAG + "-->GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationProviderListener);
return location;
}
}
}
} catch (SecurityException e) {
ExceptionHandler.printStackTrace(e);
} catch (Exception e) {
ExceptionHandler.printStackTrace(e);
}
return location;
}
public void updateLattitudeLongitude(double latitude, double longitude) {
Logger.i(TAG, "updated Lat == " + latitude + " updated long == " + longitude);
SharedPreferenceManager sharedPreferenceManager = SharedPreferenceManager.getInstance();
sharedPreferenceManager.updateUserDeviceLatLong(latitude, longitude);
listener.onUpdate(latitude, longitude);
}
public void stopLocationUpdates(){
try {
if (locationManager != null) {
Logger.i(TAG,"stopLocationUpdates");
locationManager.removeUpdates(locationProviderListener);
locationManager = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
public LocationListener locationProviderListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
try {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
updateLattitudeLongitude(latitude, longitude);
} catch (Exception e) {
ExceptionHandler.printStackTrace(e);
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
Public interface myListener{
onUpdate(double latt,double longg)
}
}
From Activity
class MyActivity extends Activity{
void startLication(){
LocationTracker.getInstance(this).connectToLocation(new myListener(){
@override
void onUpdate(double latt,double longg){
//Here you can get
}
});
}
}
Related videos on Youtube
SudeepaNoble
Updated on June 11, 2022Comments
-
SudeepaNoble almost 2 years
I want to get my current location in the form of an address by GPS. I am using the android studio. It is saying that my application stops working. What is the error in it? Can someone help me to get out of this, please?
My Code in activity_main.xml file is
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />
My code in MainActivity.java is
package com.example.showlatlong; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity { Location gps_loc, network_loc, final_loc; double longitude; double latitude; String userCountry, userAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = findViewById(R.id.text_view); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) { return; } try { gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); network_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } catch (Exception e) { e.printStackTrace(); } if (gps_loc != null) { final_loc = gps_loc; latitude = final_loc.getLatitude(); longitude = final_loc.getLongitude(); } else if (network_loc != null) { final_loc = network_loc; latitude = final_loc.getLatitude(); longitude = final_loc.getLongitude(); } else { latitude = 0.0; longitude = 0.0; } ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE}, 1); try { Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) { userCountry = addresses.get(0).getCountryName(); userAddress = addresses.get(0).getAddressLine(0); tv.setText(userCountry + ", " + userAddress); } else { userCountry = "Unknown"; tv.setText(userCountry); } } catch (Exception e) { e.printStackTrace(); } }
}
My code in manifest.xml is
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
The entire code is this. It is opening the app and in less than a second, it is closing by throwing an error message that "app keeps stopping" on my android application. This is what I got in the logcat is
2019-09-11 12:58:45.344 15400-15400/com.example.showlatlong E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.showlatlong, PID: 15400 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.showlatlong/com.example.showlatlong.MainActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6238) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.constraint.ConstraintLayout" on path: DexPathList[[zip file "/data/app/com.example.showlatlong-1/base.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.showlatlong-1/lib/arm64, /system/lib64, /vendor/lib64]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:380) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at android.view.LayoutInflater.createView(LayoutInflater.java:613) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:812) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:752) at android.view.LayoutInflater.inflate(LayoutInflater.java:499) at android.view.LayoutInflater.inflate(LayoutInflater.java:430) at android.view.LayoutInflater.inflate(LayoutInflater.java:377) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161) at com.example.showlatlong.MainActivity.onCreate(MainActivity.java:29) at android.app.Activity.performCreate(Activity.java:6857) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6238) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit. java:933) 2019-09-11 12:58:45.344 15400-15400/com.example.showlatlong E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
-
Cyrille Con Morales over 4 yearsPlease show some code also what you have been tried so far
-
Arpit J. over 4 yearsNatively you can only get coordinates using gps. You want to get Address like google maps?
-
SudeepaNoble over 4 years@ArpitJ. I think it is possible to convert coordinates to show the location in google maps using reverse geocoding.
-
SudeepaNoble over 4 years@CyrilleConMorales All the codes I have tried are not the recent versions and they are posted 3 years ago. So, I did not post the code. I am still a beginner and that made me ask you the process. Thankyou
-
Kalpesh Wadekar almost 4 yearsFor those who are looking out for simple implementation to get the current/last known location, check this out: stackoverflow.com/a/62761897/3908895
-
-
John Lord over 4 yearsdepending on device, this may not be the best idea. My work manages 600 tablets that don't get software through the play store,and fused location provider relies on play services, which google forces you to update often. If you don't, you lose play services which breaks fuse location provider. We had to manually update 600 tablets.
-
ralphgabb over 4 yearsYes. But in most cases this is a best plan if you are developing the norm. In your case you can use the native LocationManager to access GPS data
-
John Lord over 4 yearslike i said, depends on device. Note that i've also seen a tablet (specifically the new tab a from samsung) that we had to disable every location source besides gps because it was screwing it up. Your mileage may vary.
-
SudeepaNoble over 4 yearsthankyou so much for that prompt reply. error: cannot find symbol variable countryAdapter error: cannot find symbol variable countryAdapter error: cannot find symbol variable countryEdit error: cannot find symbol variable countryEdit, I am getting these errors. Can you help me out please.
-
Suri over 4 yearsLook, my countryEdit variable is a spinner and the countryAdapter variable is ArrayAdapter<String>. Do you use a spinner by any chance? please let me know.
-
SudeepaNoble over 4 yearsNo, I did not use it anytime before. I just tried the code you sent me. Can you please tell me the entire code including activity.xml file. It will be very helpful for me.
-
Suri over 4 yearsThat's the only relevant code. I assume you are using a text view to do this, so I have changed it to text view instead of a spinner. If there is any mistake, tell me pls.
-
SudeepaNoble over 4 yearserror: cannot find symbol variable text_view. I am now getting this. I have imported android.widget.textview also. What should I do now.
-
Suri over 4 yearsYou must create the text view in an xml file by calling its id "text_view".
-
Suri over 4 yearsI have made the code clearer. Now you can have a look.
-
SudeepaNoble over 4 yearsYes. I've created Id as textview and it is working finally. But after opening the application, I'm not getting anything. Should I include any other buttons in text view?
-
Suri over 4 yearsNo need. When you open your app, there should be a pop-up window asking you for accessing your location, then you must click "allow" otherwise it will return "Unknown".
-
SudeepaNoble over 4 yearsThere's no pop up window coming for me. It is saying that application keeps stopping. Can you please help me in doing it.
-
Suri over 4 yearsYou missed the line "ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE}, 1);".
-
Arnold Brown over 4 yearsThis is also a working one. Just Copy/Paste is enough
-
SudeepaNoble over 4 yearsStill my application keeps stopping even after including the line.
-
Suri over 4 yearsWhat does the log say?
-
SudeepaNoble over 4 years2019-09-10 14:19:16.901 1498-1498/com.example.showlatlong E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) In terminal it is showing application has terminated. And in my android mobile, it is saying my application keeps stopping.
-
SudeepaNoble over 4 yearsCan you try the code for getting the address using reverse geocoding?? If you already have an idea, can you help me with that?
-
Suri over 4 yearsCan you show your logcat when you run your app pls.
-
SudeepaNoble over 4 yearsCan you please see it now.
-
CoolMind almost 4 years@JohnLord, if not use
Fused Location Profivider
and update Play Services seldom (or never), willLocationManager.getLastKnownLocation
work well? -
John Lord almost 4 yearsi would think so. All the google play wrapper does is add some events for you to use and auto-switches to the best current location. This could conceivably be wifi if you are in a city. Note that the underlying behavior depends on the OS version. Newer ones only trigger new points when you are moving or when they get around to giving you a point vs when you ask for it. It prevents bogging the system down.
-
Sambhav Khandelwal about 2 yearsplease also mention how to use it in a activity so that it helps everyone
-
gpuser about 2 yearsJust try to use..... LocationTracker.getInstance(this). connectToLocation();... from activity......you can also extend or add with your interface listener to update this from updateLattitudeLongitude method to update in ui/activity class.
-
Sambhav Khandelwal about 2 yearsCan you add it to your answer
-
gpuser about 2 years@SambhavKhandelwal please check the updated answer