For a long time I was combing the Internet in search of a simple solution, how can I add only 1 class to the project and no longer worry about geolocation problems.
The criteria were:
1) solve everything in 1 class, as little as possible using external code.
2) the user should always have at hand 1 static variable in which his location is indicated and he should not know about anything else.
Most of the posts did not answer the question: of course, you first need to contact the service, then you need to install a listner, then you can look at a three-page short example how to do it.
In the end, I wrote my class, with which I want to introduce you: it is easy to use and anyone can handle it: just add it to the project and you will be happy.
import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; class MyLocationListener implements LocationListener { static Location imHere;
So what is there?
')
The class is divided into 3 parts:
1)
imHere is a
location type variable in which the latest information about the user's location will always be available.
2) the
SetUpLocationListener function — in any case, we will need an initial installation in order for the system to start updating the
imHere variable without our participation.
3) all other mandatory parts
LocationListener , which can be altered at will.
So how does it work?
1) create the class
MyLocationListener2) copy the code written above into it
3) in the main function (for example,
MainActivity ) closer to the beginning we run:
MyLocationListener.SetUpLocationListener(this);
or for stream lovers
final Context mainContext = this; new Thread(new Runnable() { @Override public void run() { MyLocationListener.SetUpLocationListener(mainContext); } }).start();
4) now we always have and in any part of our project there is a variable of the
Location type
MyLocationListener.imHere , which stores the latest user location and a lot of additional information, such as speed or positioning accuracy.
And in conclusion: this is a fundamental code and there is something to improve. For example, you need to take into account that at first the location may not be determined and imHere will be null, but this is not all soon: now we have a class that allows us to add geolocation to our project with a minimum of knowledge.
(!) Do not forget: depending on the selected provider, you need to add an appropriate permission to the manifest. For example, the GPS_PROVIDER used above requires adding the following line to the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />