Running a service to get location details - android

In my app, i need to create an android service to periodically get mobile user's current location(latitude and longitude). The service should get user's location in every 5 minutes.. How can i do this in android service that would run in background. And is this the right approach?

You can write a private/internal class(within your service) that implements locationListener and in the onStart meethod of your service you can requestLocationUpdates which will be listened by your listener
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, listener);

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
}
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
Log.i("**************************************", "Location changed");
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +"Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}

You don't need a service to accomplish this. In order to get location every 5mins, in your app, on the activity you can implement the location listener. While setting up the location manager, you can specify the minTime = 5mins (300000 ms). The onlocationChanged method will be called every 5 mins or when the distance change > minDistance, which ever occurs first.
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
MyLocationListener listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, minDistance, listener);

Related

Listen for GPS Status change

I need to listen when the user turns GPS on or off, and act upon that.
I understand this was available using the GPSStatus class, however that was deprecated.
How do I do this now?
You can use LocationListener !!
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
//handlePostion(loc);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
And below how to use this listener
mLocationListener = new MyLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new MyLocationListener();
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, mLocationListener);
And in on providerDisabled callback you can know when the GPS is off

Why can't I get the location by the NETWORK_PROVIDER as follows?

It is very simple.
But I see nothing appears on the logcat.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_selection);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("MapSelectionActivity", longitude + " " + latitude);
} else {
Log.d("MapSelectionActivity", "location unavailable");
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
I am sure my phone is connected to a wifi access point, which enables the phone to access the internet.
First change the line below:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
To:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
Like it's said here:
public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
...
minTime minimum time interval between location updates, in milliseconds
...
EDIT
I found this tutorial here, which has a simpler usage:
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, this.locationListener);
private final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location locFromGps) {
// called when the listener is notified with a location update from the GPS
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
}

LocationManager generating errorin code

this is my code in android and is showing error. I dont know what is wrong but i am certaqin it has to do something with LocationManager because until that line it works fine.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Exception", "Something gone wrong !! ");
/*after this line it shows error */
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
All i want right now is to display value of longitude and latitude so that i can be sure code is good till here.
Declate this variable
Location loc;
Write this code in Oncreate() method
LocationManager mlocManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
Then Write
loc.getLatitude();
loc.getLongitude();
Now you can use the value of latitude and longitude... :-)
Use Below Code Snippet
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
Check Below Line in Manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Android :How can i check whether GPS is working in my android device or not?

i am working in android. i am designing an application which is based on GPS location of my device.
Whenever i press any event key in my application i need to check whether my device is getting GPS location all the time or not.
Please help me for this. you may provide weblink for this.
Thank you in advance.
You should use this type of code:-
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
myLongitude = location.getLongitude();
myLatitude= location.getLatitude();
}
else
{
myLongitude =0;
myLatitude= 0;
}
LocationListener mlocListener;
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
Log.v("Checkin_Inspect_activity","cordintes of this place = "+myLatitude+" "+myLongitude);
and design you class like this:-
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
myLatitude= loc.getLatitude();
myLongitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
// Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
// Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
you can use the LocationListener class which will give the location detail whenever the location was update
here is the simple snippet of LocationListener
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
Edited
you can check the provider for location for gps like this way
if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
// do something
}else{
// do another thing
}
check out this tutorial link
http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/

Unable to get latitude and longitude from android

getLastKnownLocation always return null value. I have enabled geo fix and gps on emulator. However, there is no gps signal on the notification bar when running this on emulator. May I know is there any mistake in my code? Thanks.
public void onCreate(Bundle savedInstanceState) {
LocationManager location = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.near_layout);
location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String bestProvider = location.getBestProvider(criteria, true);
LocationListener ll = new mylocationlistener();
Location loc = location.getLastKnownLocation(bestProvider);
if(loc != null)
{
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(nearPlace.this, " nice" + latitude, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(nearPlace.this, "Location not available. GPS is not enabled.", Toast.LENGTH_LONG).show();
}
location.requestLocationUpdates(bestProvider, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(nearPlace.this, " nice" + location.getLatitude(), Toast.LENGTH_LONG).show();
nearPlaceDownloaderTask getNearPlace = new nearPlaceDownloaderTask();
getNearPlace.execute(ANDROID_WEB_LINK + "gt.php?la=" + location.getLatitude() + "&lo=" + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The reason your code is not working, is because you have specified the following criteria:
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
Android will prefer to use network location over GPS, because you don't care about the accuracy. By specifying an accuracy of 20 meters or so, it will probably automatically invoke GPS.
To manually invoke GPS location updates, override bestProvider:
bestProvider = LocationManager.GPS_PROVIDER;
You can really simplify this into two lines of code:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval,
precision, listener);
Don't forget to unregister your listener:
locationManager.removeUpdates(listener);
You might also want to check this out geofix not working
Also make sure you have mock locations allowed set in the emulator. Take a look at Pauls answer as well, which is why I was asking in comments what provider was returned

Categories

Resources