Skip to main content

Get Current location using FusedLocationProviderClient in Android


Hello to coders,
Previously we have taught you how you get current location using GPS/Network Provider. Then android has revealed FusedLocationProviderClient under GoogleApi. FusedLocationProviderClient is for interacting with location using fused location provider.
(NOTE : For using this feature, GPS must be turned on your device. For manually ask user to turn on GPS, please check next article)
So let’s get started for the tutorial for getting current location.
First add dependency for location by play services:
implementation 'com.google.android.gms:play-services-location:15.0.1'
Then define FusedLocationProviderClient:
private FusedLocationProviderClient mFusedLocationClient;
private TextView txtLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.txtLocation = (TextView) findViewById(R.id.txtLocation);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    };
}
Add permission in manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Now ask for runtime permission for above android 6 OS devices
// check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // reuqest for permission

} else {
   // already permission granted
}
Now, request for permission if not granted and get result on onRequestPermissionsResult overridden method, check highlighted code below:
private int locationRequestCode = 1000;
private double wayLatitude = 0.0, wayLongitude = 0.0;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
        locationRequestCode);

} else {
   // already permission granted
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case 1000: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mFusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
                    if (location != null) {
                        wayLatitude = location.getLatitude();
                        wayLongitude = location.getLongitude();
                        txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude));
                    }
                });
            } else {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
}
Here, when you allow to use permission for an app, it will return to onRequestPermissionsResult method. And again get the last location and print location on textview.
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
                    if (location != null) {
                        wayLatitude = location.getLatitude();
                        wayLongitude = location.getLongitude();
                        txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude));
}
                });
Above code will work if app has already grant the location permission
// check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // reuqest for permission

} else {
    // already permission granted
    // get location here
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
                    if (location != null) {
                        wayLatitude = location.getLatitude();
                        wayLongitude = location.getLongitude();
                        txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude));
}
                });
}
Here you can notice, why we put a condition that if(location!=null) before getting latitude-longitude. The location object may be null in following situations:
  • Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
  • The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
  • Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself.
Now if in case we can’t getting location then we have option for request location updates. Location updates will give you continuous location at any specific time interval as per your request. Let’s move on location updates.
private FusedLocationProviderClient mFusedLocationClient;
private TextView txtLocation;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.txtLocation = (TextView) findViewById(R.id.txtLocation);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(20 * 1000);
locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult == null) {
            return;
        }
        for (Location location : locationResult.getLocations()) {
            if (location != null) {
                wayLatitude = location.getLatitude();
                wayLongitude = location.getLongitude();
                txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude));
            }
        }
    }
};
    };
}
Here we definitely get the current location using this location updates. And once we get the location, we can also remove location continuous updates else you will get multiple locations updates. This will help you when you want to move marker on map as current location changes.
if (mFusedLocationClient != null) {
    mFusedLocationClient.removeLocationUpdates(locationCallback);
}
Now you can find some methods of location request like setPriority(), setInterval() and setFastestInterval().
  • setPriority: The priority of the request is a strong hint to the LocationClient for which location sources to use. For example, PRIORITY_HIGH_ACCURACY is more likely to use GPS, and PRIORITY_BALANCED_POWER_ACCURACY is more likely to use WIFI & Cell tower positioning, but it also depends on many other factors (such as which sources are available) and is implementation dependent.
  • setInterval: Set the desired interval for active location updates, in milliseconds. The location client will actively try to obtain location updates for your application at this interval, so it has a direct influence on the amount of power used by your application. Choose your interval wisely.
  • setFastestInterval: Explicitly set the fastest interval for location updates, in milliseconds. This controls the fastest rate at which your application will receive location updates, which might be faster than setInterval(long) in some situations (for example, if other applications are triggering location updates). This allows your application to passively acquire locations at a rate faster than it actively acquires locations, saving power.
Find the code here.

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!