Git Product home page Git Product logo

balwindersingh1989 / androidbestlocationtracker Goto Github PK

View Code? Open in Web Editor NEW
37.0 3.0 11.0 225 KB

Android Library to get best available location . Getting location in background or foreground is just a 5 lines of code away :)

Kotlin 97.94% Java 2.06%
android android-library permissions location android-app android-development android-sdk android-location-navigator android-location androidlocation

androidbestlocationtracker's Introduction

androidBestLocationTracker

Get best available locaiton from android locaiton providers

use latest version 2.0.10

Whats comming next ?

To make location data as stream and not callback. Will be incorporating flow{} to this lib.

Live Location Sharing

========================

Android Best Location Tracker is an Android library that helps you get user best location with a object named BaseLocationStrategy that would give a accurate location using accuracy alogirthm.

Installation

Add this to your build.gradle file

repositories {
    maven {
        url "https://jitpack.io"
    }
}

dependencies {
         implementation 'com.github.balwinderSingh1989:androidBestLocationTracker:2.0.6'
}

Don't forget to add the following permissions to your AndroidManifest.xml

<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" />
add below if you need locaton in background for android Q and above. Check out this blog
https://www.ackee.agency/blog/how-to-fetch-location-in-background-on-android
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

Use

To create a tracker you just need to add the below code in your Android Activity/Service

// You can pass an ui Context but it is not mandatory getApplicationContext() would also works
// Be aware if you target android 23, you'll need to handle the runtime-permissions !
// see http://developer.android.com/reference/android/support/v4/content/ContextCompat.html
if (    ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
    || ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // You need to ask the user to enable the permissions
} else {
    setupLocation();
}


  private void setupLocation()
    {
         baseLocationStrategy = getLocationStatergy(this, this)

         baseLocationStrategy?.apply {
                  setDisplacement(5)
                  setPeriodicalUpdateTime(1000)
                  setPeriodicalUpdateEnabled(true)

                  shouldFetchWhenInBackground(fetchAggresively = true, lifecycle)

                  /**
                  NOTE :SET  fetchAggresively true if you need location in background faster than android default (which is few times in a hour).
                  when this is TRUE : for android API  < 31, location will be fetched by foreground service and for above lib will use workmanger


                  REMEMBER : You would need permission <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> to fecth location in
                  background for Adnroid 10 and above



                  lifecycle  = set this to activity as lib would use this lifecycle to bind the foreground service and would start the service once the activity is not visible
                  (i.e activity is in background)

                  **/

                  startListeningForLocationChanges(object : LocationChangesListener {
                      override fun onBetterLocationAvailable(location: Location?) {
                          Log.d(TAG, "onBetterLocationAvailable  ${location.toString()}")
                      }

                      override fun onConnected() {
                          Log.d(TAG, "onConnected")
                      }

                      override fun onConnectionStatusChanged() {}
                      override fun onFailure(s: Error) {
                         //check error codes here

                      }
                  })
                  baseLocationStrategy?.startLocationUpdates()
  }



//also from android 10 and above , one cannot ask foreground and background location at the same time. Hence for background location one should have a proper use case
//and UI option to trigger background location. Once you have decided the use case, you can call below fun to let lib known that ACCESS_BACKGROUND_LOCATION is granted, so that
//lib can start providing you location when your app is in background.

     btnStartBackgroundFetch.setOnClickListener {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_BACKGROUND_LOCATION
                ) == PackageManager.PERMISSION_GRANTED

            ) {
                baseLocationStrategy?.backgroundLocationPermissionGranted()
            } else {
                this.requestPermissions(
                    arrayOf(
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                    ), REQUEST_CODE
                )
            }
        }


And it's done, as soon as a location gets available, it will call the onLocationChanged() with latest and best available locaition. Also, to get lastKnown location any time (this should only we called if )

baseLocationStrategy.getLastLocation();

Manage the tracker

By default, after a baseLocationStrategy is created, it automatically starts listening to updates... and never stops. LocationTracker has two methods to start and stop listening for updates.

If you want to stop listening for updates, just call the baseLocationStrategy.stopListeningForLocationChanges() method. For example, if you need a one shot position, you can do that:

 baseLocationStrategy.startListeningForLocationChanges(new LocationChangesListener() {
            @Override
            public void onLocationChanged(Location location) {
                //get best accurate location here and here you can stop
                baseLocationStrategy.stopListeningForLocationChanges()
            }
            @Override
            public void onConnected() {
                //best location provider has been connected and you will surely get location changes now
            }
            @Override
            public void onConnectionStatusChanged() {
            }
            @Override
            public void onFailure(String s) {
            }
        });
        baseLocationStrategy.startLocationUpdates();

You can also do it in the onPause() Activity method if you want.

@Override
protected void onPause() {
	if(baseLocationStrategy != null) {
		baseLocationStrategy.stopListeningForLocationChanges();
	}
	super.onPause();
}

REMEMBER! A LocationTracker never stops untill you tell it to do so.

You may want to start listening for updates after all. To do that, LocationTracker has a public method named startLocationUpdates(), call it when you want.

For example, in the onResume() Activity method:

@Override
protected void onResume() {
	if(baseLocationStrategy != null) {
		baseLocationStrategy.startLocationUpdates();
	}
	super.onResume();
}

Contact & Questions

If you have any questions, fell free to send me an email at [email protected] You can also fork this project, or open an issue :)

androidbestlocationtracker's People

Contributors

balwindersingh1989 avatar sal0max avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

androidbestlocationtracker's Issues

Make Google Play services error dialog optional

Thanks for this great library. It is the only one I could find which provides a convenient way to access Android GPS data without the need of Google Play services (FusedLocationProvider).

I tested your library with great success on an emulator without Google Play services. It works great! However, there's still this message dialog popping up, like in this screenshot:
Screenshot_1656887882

I guess this is because of this code:

if (googleApiAvailability.isUserResolvableError(status)) {
   googleApiAvailability.getErrorDialog(context as Activity?, status, 2404).show()
}

Is there a chance you could make this error dialog optional?

It could confuse users and realistically, they can't change anything on the situation or even chose actively not to use Google services. And as mentioned: Despite the error message, location fetching is working perfectly fine without Google services.

androidBestLocationTracker - will it do this?

Hi balwinderSingh1989, found androidBestLocationTracker via StackOverflow, it looks exactly like a simple app I need - downside, I do not know mobile development at all. You say if a question ask / email - sorry cannot find your mail. So the question 'is' - is androidBestLocationTracker basically an app ready to go? if not what do I need to do? and/or can you help :) My need is very simple a tracking app (permissions granted) that fires a request to a Firebase database on location change. Would be great/preferable if this could be done 'in the background' without the app actually being open. Hopefully you still 'monitor' this git and I look forward to any reply - cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.