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-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permissionandroid: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.ConstraintLayoutxmlns: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"><TextViewandroid: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;
publicclassMainActivityextendsAppCompatActivity {
Location gps_loc;
Location network_loc;
Location final_loc;
double longitude;
double latitude;
String userCountry, userAddress;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextViewtv= findViewById(R.id.text_view);
LocationManagerlocationManager= (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();
}
elseif (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, newString[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE}, 1);
try {
Geocodergeocoder=newGeocoder(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-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION" />
For a more detailed tutorial you can refer at this Medium GPS Tutorial
Cheers
Solution 3:
Using the Geocoder class in the Android framework location APIs, you can convert an address to the corresponding geographic coordinates. This process is called geocoding. Alternatively, you can convert a geographic location to an address. The address lookup feature is also known as reverse geocoding.
Use getFromLocation() method to convert a geographic location to an address. The method returns an estimated street address corresponding to a given latitude and longitude.
public List<Address> getFromLocation(double latitude, doubleint maxResults)
This Returns an array of Addresses that are known to describe the area immediately surrounding the given latitude and longitude. The returned addresses will be localized for the locale provided to this class's constructor.
Take a look here as well: https://developer.android.com/training/location/display-address
Solution 4:
Try This! (Did it one year back)- Will update your location on all your move at certain interval.
Add dependencies in grade
implementation 'com.google.android.gms:play-services-location:16.0.0'
Add permissions in Manifest
<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /><uses-permissionandroid:name="android.permission.INTERNET" />
In Your Activity
publicclassMainActivityextendsAppCompatActivityimplementsGoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
double longitude;
double latitude;
TextView tv;
Context context;
Location mLastLocation;
privateGoogleApiClient mGoogleApiClient;
privateLocationRequest mLocationRequest;
publicstatic final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
publicstatic final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
tv = findViewById(R.id. text_view);
mGoogleApiClient = newGoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
initLocation();
}
@OverridepublicvoidonConnected(@Nullable Bundle bundle) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100000); // Update location every secondif (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
setValue();
}
}
privatevoidsetValue() {
String strAddress = getAddressFromLocation(this, latitude, longitude);
tv.setText(strAddress);
}
@OverridepublicvoidonConnectionSuspended(int i) {
}
@OverridepublicvoidonConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@OverridepublicvoidonLocationChanged(Location location) {
if(location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
publicbooleancheckLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// Asking user if explanation is neededif (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
// Show an explanation to the user *asynchronously* -- don't block// this thread waiting for the user's response! After the user// sees the explanation, try again to request the permission.//Prompt the user once explanation has been shownActivityCompat.requestPermissions(this, newString[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
else
{
// No explanation needed, we can request the permission.ActivityCompat.requestPermissions(this, newString[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
returnfalse;
}
else
{
returntrue;
}
}
@OverrideprotectedvoidonStart() {
super.onStart();
mGoogleApiClient.connect();
}
@OverrideprotectedvoidonResume() {
super.onResume();
mGoogleApiClient.connect();
initLocation();
}
@OverrideprotectedvoidonPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
@OverrideprotectedvoidonDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
privatevoidinitLocation() {
if(checkAndRequestPermissions(context)) {
Toast.makeText(context,"Permission Granded",Toast.LENGTH_SHORT).show();
}
}
publicstaticbooleancheckAndRequestPermissions(Context context) {
int locationPermission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = newArrayList<>();
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions((Activity) context, listPermissionsNeeded.toArray(newString[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
returnfalse;
}
returntrue;
}
publicstaticStringgetAddressFromLocation(Context context, final double latitude, final double longitude) {
String straddress = "";
Geocoder geocoder = newGeocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = newStringBuilder();
if(address.getAddressLine(0) !=null && address.getAddressLine(0).length()>0 && !address.getAddressLine(0).contentEquals("null"))
{
sb.append(address.getAddressLine(0)).append("\n");
}else {
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
straddress = sb.toString();
//Log.e("leaddress","@"+straddress);
}
} catch (IOException e) {
//Log.e(TAG, "Unable connect to Geocoder", e);
}
return straddress;
}
}
Solution 5:
Please try the below way here you can get location using the gps and network both
publicclassLocationTracker {
publicstaticStringTAG= LocationTracker.class.getName();
booleanisGPSEnabled=false;
booleanisNetworkEnabled=false;
booleancanGetLocation=false;
Locationlocation=null;
privatestaticfinallongMIN_DISTANCE_CHANGE_FOR_UPDATES=0;
privatestaticfinallongMIN_TIME_BW_UPDATES=1000;
protected LocationManager locationManager;
static Context mcontext;
privatestatic LocationTracker instance;
publicstaticsynchronized LocationTracker getInstance(Context ctx) {
mcontext = ctx;
if (instance == null) {
instance = newLocationTracker();
}
return instance;
}
publicvoidconnectToLocation() {
stopLocationUpdates();
displayLocation();
}
privatevoiddisplayLocation() {
try {
Logger.i(TAG,"displayLocation");
Locationlocation= 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;
}
} elseif (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;
}
publicvoidupdateLattitudeLongitude(double latitude, double longitude) {
Logger.i(TAG, "updated Lat == " + latitude + " updated long == " + longitude);
SharedPreferenceManagersharedPreferenceManager= SharedPreferenceManager.getInstance();
sharedPreferenceManager.updateUserDeviceLatLong(latitude, longitude);
}
publicvoidstopLocationUpdates(){
try {
if (locationManager != null) {
Logger.i(TAG,"stopLocationUpdates");
locationManager.removeUpdates(locationProviderListener);
locationManager = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
publicLocationListenerlocationProviderListener=newLocationListener() {
@OverridepublicvoidonLocationChanged(Location location) {
try {
doublelatitude= location.getLatitude();
doublelongitude= location.getLongitude();
updateLattitudeLongitude(latitude, longitude);
} catch (Exception e) {
ExceptionHandler.printStackTrace(e);
}
}
@OverridepublicvoidonStatusChanged(String s, int i, Bundle bundle) {
}
@OverridepublicvoidonProviderEnabled(String s) {
}
@OverridepublicvoidonProviderDisabled(String s) {
}
};
}
Post a Comment for "How Can I Get My Current Location In Android Using Gps?"