Tips, Tutorials, Resources for Web Design and Online Marketing

Main Menu

  • Mobile App Development
    • App Tutorials
    • App Reviews
  • Website Guides
  • Small Businesses & Startups
  • News
  • Guest Posts
  • About
    • Mobile App Development Company Delhi, India
    • Mobile App Development Company Gurgaon
    • Mobile App Development Company Dallas, Florida
    • Website Design Company Delhi
    • WordPress Website Development Company

Tips, Tutorials, Resources for Web Design and Online Marketing

Header Banner

Tips, Tutorials, Resources for Web Design and Online Marketing

  • Mobile App Development
    • App Tutorials
    • App Reviews
  • Website Guides
  • Small Businesses & Startups
  • News
  • Guest Posts
  • About
    • Mobile App Development Company Delhi, India
    • Mobile App Development Company Gurgaon
    • Mobile App Development Company Dallas, Florida
    • Website Design Company Delhi
    • WordPress Website Development Company
  • 10 Tips To Grow Your Online Business

  • How to Choose the best custom software development companies in India ?

  • 7 Tasks to Complete before Starting Your Website Development Project

  • Online Marketing Tips and Productivity Tools for Small Businesses during Coronavirus

  • Tutorial 2: Which type of website does your business need ?

Android Tutorials & Tips
Home›Android Tutorials & Tips›How to Handle Location when Developing an Android App [Fused Location, Nougat]

How to Handle Location when Developing an Android App [Fused Location, Nougat]

By Abhay Anand
October 9, 2017
11261
2

Hi Mobile App Developers, Lets take a quick Look at :

Handling Permissions and Location Updated in Android Apps using Fused Location
Scope: Handling of Permission and getting updates. We’ll talk about this strictly in the context of FUSED location API

Background: We found that Location handling was really one of the areas in android app development where there was some persistent confusion. Trainee staff in our own team had to be explained how to map user requirements to a workable location strategy.

Excluded: Actual code for implementing the fused location which we will look into in a subsequent article.

LEVEL: BEGINNER TO INTERMEDIATE

Background: We found that Location handling was really one of the areas in android app development where there was some persistent confusion. Trainee staff in our own team had to be explained how to map user requirements to a workable location strategy.

COVERAGE: Code snippets provided without full working code.

LEVEL: BEGINNER TO INTERMEDIATE

Lets Assume the following use cases for the application of this article:
The client requires that your mobile app show the nearest service provider to him – it could be
a) A Cab Hailing App
b) A Trucking / Commercial Vehicle app
c) A Delivery and Logistic app
d) A Service provider such as a Carpenter / Electrician, Beauty Salon

Handling Location Permissions in Android

Tackling Location Permissions in Android

If you see carefully, case a), b) , c) are somewhat similar in the sense that a periodic tracking is required whereas case d) is mainly that of retail shops /offices at a single point where periodic tracking of the service provider is not required to know of his location. Just a user initiated update is enough.

How to provide periodic Tracking from the Mobile Phone itself?
So, in the above scenarios a), b), c) a periodic updating of the location – latitude and longitude is required by the app. We’ve generally seen this done by an API which saves the provider’s location periodically into the database and the android activity can retrieve the lat, long of the chosen provider in the activity’s view from the database. The trick is to do this with proper permissions (chosen either on opening app or install etc.) , and with only the required battery consumption.

And this brings us to an important Question, which is:

What is the best way to provide location permissions when developing your Android App?

First up, location was earlier requested through android.location API but since 2014, Fused Location through Google Play Services has been available to get location updates. This is compatible Android 2.3 onwards, so pretty much covers all devices.

Fused location has many advantages and is a recommended way of getting location details according to Google. We assume here that you would know it’s background but if you don’t check out the details here.

So coming back, lets look at how location permission is saved in a typical android phone (Nougat, Marshmallow included).

Situations your Android app must tackle when seeking location updates

A) Either the location is completely off.
OR
B)if the Location setting is on – then
1) Whether GPS option is on (High Accuracy)
2) Whether Networking or Wifi (Low Battery setting) use is On

Fused location provider API (now FusedLocationProviderClient) actually takes care of all these situations and removes the guesswork by automatically changing the appropriate system settings based on desired accuracy and available options /permissions.

Typical runtime Location Permission Popup in Android

Typical run-time Location Permission Popup in Android

Power consumption for Location Service

Power Consumption options when choosing Location in Android app

Settings and Permissions Strategy

Keep in mind that many a times networking or low power or what is denoted by COARSE_LOCATION Permission will SUFFICE for your needs. According to Google the accuracy is 50-100 metres for COARSE_LOCATION. If you are in suburb or city in India, i think we can take a worse case scenario of 75-100 metres accuracy.

I would say that this is sufficient for most logistics and delivery app situations such as b) and c) and definitely acceptable for case d). Another aspect that we found was that in many cases, developers had made GPS usage mandatory even when unnecessary.

GPS is mainly necessary for Taxi or Cab hailing apps: where a more frequent update of location as well as direction and speed calculations are required. Practically, one should set Limits of accuracy and / or update as per the business requirements. More frequent or more accurate location settings will lead to greater battery drain.

The App may also provide the user, options to change his / her location settings if he or she wants to – taking full benefit of the location feature. Ideally, it should work with the low power setting also, except where GPS is compulsorily required – such as a cab hailing App.
Therefore, do not restrict the user to use GPS only; unless it’s a business requirement.

As a far as permissions are concerned if location is required regularly, it would be better to take permission on install but switch location services off whenever not needed. If it is infrequent or based on a specific activity or event then you can give permissions at Runtime. In order to use the location services provided by Google Play Services Fused Location Provider, connect your app using the Settings Client, check the current location settings and prompt the user to enable the required settings if needed.

Steps in getting Location Updates in Fused Location (Location services Android Tutorial)

1. Setting the Permission

Import Google Play services from Android SDK (../sdk/extras/google/google_play_service/libproject/google-play-services_lib) as a library in your application


{
manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gms.location.sample.locationupdates"

/manifest
}

2. Create a Location Services Client


private FusedLocationProviderClient mFusedLocationClient;
// ..
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

3. Getting the Last known Location


mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});

Note that null handling has to be done as in some scenario location may not be returned. Also, the above step is not really necessary if we’re requiring periodic location updates.
To get periodic location updates, and in our own control we need to set up a Location request client and get location requests from it at pre-configured periodic intervals.
And to do this you have to define all these configuration settings. Which brings us to Step 4.

4. Set Update interval, Fastest update interval and Priority Configuration for Location Updates.

In this case lets assume we have a case where infrequent location updates are fine – say every 10 minutes is more than enough. Also lets assume a very high accuracy is not required and we can do with 100 metre error. Typical settings in such as scenario would probably be like this:

protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(900000);
mLocationRequest.setFastestInterval(600000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}

So as you can see – we’re defining these settings in the LocationRequest object just created. We have the setFastestInterval as upper limit for any location update (which other apps may also be getting ) to be used by you. So for us since 10 mins is the minimum and we can do with 15 minutes as well – we’ve kept the values accordingly (measured in milliseconds).

After creating the locationRequest – get the current location to begin with:

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);

Apart from this, you can also get the Current Location Settings, prompt user to change settings if required (an optional step in most cases) as explained here. NOW you are ready to get the regular Location updates which is required for Tracking.

5. Getting Regular Location updates from Fused Location.

The API updates your app periodically with the best available location, based on the currently-available location providers such as WiFi and GPS (Global Positioning System). The accuracy of the location is determined by the providers, the location permissions you’ve requested, and the options you set in the location request.


@Override
protected void onResume() {
super.onResume();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}

private void startLocationUpdates() {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback,
null /* Looper */);
}

So startLocationUpdates is the main method which is passing the LocationRequest object and Callback.
mRequestingLocationUpdates is a boolean flag which is used to indicate if location requests are ON or OFF by the user of the App.
Now the LocationCallback interface also needs to be implemented which actually gets the Latitude and Longtitude.


private LocationCallback mLocationCallback;
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...

mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
}
};
};
}

Stopping or Pausing a Location Request
This is an important option which can help reduce power consumption to stop getting location updates when not needed. For example, if it’s a regular saving of location in database but when your vehicle is stopping or in rest – on click of your Rest / Shift Completed button, the location updates could stop as there is no need to track you. This could even be time based.

@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}

private void stopLocationUpdates() {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}

Note: The important thing to be kept in mind is that the above examples show location requests based on a specific activity but if your requirement is such that tracking continues even if application is in background then you need to use a background service and get the current location. In that scenario , you do NOT need to request Location updates as the background service itself can be run periodically and just get the current location. Further , here the settings need not be configured to Reflect the Fastest interval and just the Accuracy to BALANCED POWER would be enough.

Another option could be to use PendingIntent as explained here to get location in background cases.

If you’re looking to build a Location, GPS tracking, Logistics or Cab hailing app , maybe our mobile app development company based out of Delhi, can help you. Just reach out to us and we’ll be happy to provide a free consultation.

Tagsandroid locationandroid tutorialFusedLocationGPS tracking
Previous Article

Comparing the Rs. 1500 Reliance JioPhone to ...

Next Article

What should a Requirements Document (or a ...

Abhay Anand

Hi Folks, this is Abhay here. I am into Digital Marketing and SEO and a huge fan of the startup eco-system here in India. Looking to interact with like minded folks and learn more about mobile app and digital trends and happenings.

Related articles More from author

  • Top Android Libraries for 2018
    Android Tutorials & TipsMobile App DevelopmentMobile App Tools

    Top 10 Android Development Libraries | Best Android Libraries for Developers

    January 10, 2018
    By Abhay Anand
  • Android Tutorials & TipsMobile App Development

    10 Best Practices for Mobile App Development in 2018 (updated for 2019)

    April 18, 2018
    By Umesh Sethi
  • Optimising your Play Store Listing, ASO
    Android Tutorials & TipsMobile App DevelopmentMobile App ToolsSmall Businesses & Startups

    How to Optimise your App on Google Play Store, ASO for Play Store Listing ?

    October 30, 2017
    By Saurabh Kumar

Recommended Articles

  • Web

    10 Reasons to use Woocommerce for your E-commerce Development

  • Web

    Websites for Business Owners – Tutorial 1 – Market Research for your website

  • Optimising your Play Store Listing, ASO
    Android Tutorials & TipsMobile App DevelopmentMobile App ToolsSmall Businesses & Startups

    How to Optimise your App on Google Play Store, ASO for Play Store Listing ?

  • featured image web design checklist
    Small Businesses & StartupsWeb

    7 Tasks to Complete before Starting Your Website Development Project

Web Design & App Tutorials

  • November 7, 2020

    10 Tips To Grow Your Online Business

  • October 3, 2020

    10 Reasons to use Woocommerce for your E-commerce Development

  • September 4, 2020

    21 steps to Create a successful e-commerce store ! (Ultimate Guide)

  • August 28, 2020

    How to Choose the best custom software development companies in India ?

  • July 31, 2020

    7 Best Lead Generation Plugins for WordPress in 2020 & beyond

  • July 24, 2020

    7 Tasks to Complete before Starting Your Website Development Project

  • June 24, 2020

    5 practical tips to make your Ecommerce Store a Success

  • May 11, 2020

    Tutorial 4: How to choose the best theme for your business website ?

  • April 17, 2020

    Online Marketing Tips and Productivity Tools for Small Businesses during Coronavirus

  • March 31, 2020

    Tutorial 3 – How to Create a Project Plan / To Do List for your Website Design Project

  • March 11, 2020

    Tutorial 2: Which type of website does your business need ?

  • February 26, 2020

    Websites for Business Owners – Tutorial 1 – Market Research for your website

Check our Earlier Posts

  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • September 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • April 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • Recent

  • Popular

  • Comments

  • online marketing dashboard opened

    10 Tips To Grow Your Online Business

    By Editorial Staff
    November 7, 2020
  • 10 Reasons to use Woocommerce for your E-commerce Development

    By Saurabh Kumar
    October 3, 2020
  • 21 steps to creating your ecommerce store

    21 steps to Create a successful e-commerce store ! (Ultimate Guide)

    By Umesh Sethi
    September 4, 2020
  • how to find the best custom software development company in India

    How to Choose the best custom software development companies in India ?

    By Abhay Anand
    August 28, 2020
  • Lead Generation Plugins for WP websites

    7 Best Lead Generation Plugins for WordPress in 2020 & beyond

    By Umesh Sethi
    July 31, 2020
  • Top 10 Bitcoin Apps for 2018

    The Best Bitcoin mobile apps to watch out for in 2018

    By Saurabh Kumar
    December 23, 2017
  • iPhone 8 specifications, iPhone 8 Actual features

    Does the iPhone 10 or iPhone X meet users expectations? Features, Specifications, Details

    By Saurabh Kumar
    September 12, 2017
  • Google Tez App launch in India

    Google Tez App launched – Tez App Review and How to use it.

    By Umesh Sethi
    September 18, 2017
  • mobile app development, mobiile app programming, Java vs. Kotlin

    Kotlin vs. Java for Android App Development – And the winner is….

    By Umesh Sethi
    September 9, 2017
  • Creating a Requirements Document for Mobile App Development

    What should a Requirements Document (or a RFP) for your Mobile App Contain ?

    By Umesh Sethi
    October 17, 2017
  • Shailesh Manjrekar
    on
    September 12, 2020

    21 steps to Create a successful e-commerce store ! (Ultimate Guide)

    Thank you so much, ...
  • Maulik Shah
    on
    September 12, 2020

    How to Choose the best custom software development companies in India ?

    Such an informative post.Thanks ...
  • mayank
    on
    September 4, 2020

    How to Choose the best custom software development companies in India ?

    It's very wonderful information ...
  • Upendra
    on
    August 6, 2020

    7 Tasks to Complete before Starting Your Website Development Project

    Thanks for this blog ...
  • Bharat
    on
    July 7, 2020

    5 practical tips to make your Ecommerce Store a Success

    A very nice content ...

Our Terms of Use | Partners

Visit blogadda.com to discover Indian blogs
Featured on Blog Directory
Creative Spark Solutions is a web & app development company based in Delhi, India. With this blog we continue to connect with developers, clients and anyone interested in mobile & tech news, happenings & articles.
2017, Creative Spark Solutions helping clients in Web, Mobile & Software