I have an AsyncTask class that needs to get user's location when this AsyncTask is called.
The idea is to check if location service is enabled or not, if not, the location service toggle will popup for user to turn it on, then it will go back to the task to continue getting the location and finish the job.
However, the code below show NullPointerException on the line lat = location.getLatitude(); near the end of onPreExecute(). They said because getLastKnownLocation gets nothing as it's just been turned on a moment ago, then how can I get the location right after the location service has been turned on?
LocationManager locationManager;
LocationListener locationListener;
double lat;
double longi;
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
location = new Location(LocationManager.NETWORK_PROVIDER);
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
//I copy the part below from the internet but seems like "onProviderDisabled" and "onLocationChanged" were never be called
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.v("GPS CHECKKKKKKK",location.getLatitude()+"_"+location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
};
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,0, locationListener);
lat = location.getLatitude();
longi= location.getLongitude();
Log.v("GPS Cord CHECK",lat+"_"+longi);
}
#Override
protected String doInBackground(final Checkout_Package... params) {
//Doing the job that needs lat and longi value!
}
Thank you for your time!
You cannot create and put a location listener in onPreExecute() because the onChanged handlers will only be invoked much later when onPostExecute or even your AsyncTask has finished.
What you should do instead is start an AsyncTask in that location changed handler.
So in onLocationChanged().
With greenapps's suggest I figured it out. I put the code into the button that call the AsyncTask
checkout_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocationManager locationManager;
LocationListener locationListener;
gotit = false; //Boolean to start the AsyncTask only once.
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.v("GPS CHECKKKKKKK",location.getLatitude()+"_"+location.getLongitude());
lat = location.getLatitude();
longi = location.getLongitude();
if (gotit == false) {
new Checkout_Async(Checkout.this, listener).execute(new Checkout_Package(user, product_all, getTotalCost(product_all), fee, getTotalCost(product_all) + fee, lat, longi));
gotit = true;
pd.dismiss();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
pd=ProgressDialog.show(Checkout.this,"",getResources().getString(R.string.please_wait),false);
locationManager.requestLocationUpdates("gps",50,0,locationListener);
}
});
Now it works. Thank you!
Related
There is any solution to check if user disable GPS in settings?
I open my app, open top toolbar of android system, disable GPS and close this toolbar. In this moment I want to app check if status of GPS was changed.
I use check if GPS is active in onResume(), but this solution works only when user enable GPS, when disable onResume() is not called.
Any ideas?
Edit:
This is may class:
public class PrivacyActivity extends BaseActivity implements GpsStatus.Listener, LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Toast.makeText(this, "ads", Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast.makeText(this, "ads1", Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
}
and when I disable gps I didn't see toast.
You can use the LocationListener class
// Acquire a reference to the system Location Manager
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.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Log.i("Example", "GPS is ON");
}
public void onProviderDisabled(String provider) {
Log.i("Example", "GPS is OFF");
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You can get more info in http://developer.android.com/guide/topics/location/strategies.html
Reference the locationListener first.
LocationListener locationListener;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng myPlace = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(myPlace).title("me"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPlace));
mMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
onProviderDisabled method will be fired if the user has disabled GPS from settings.
The intent inside the method will take the user to location settings directly.
Tested and works fine.
I've written my custom location manager to check for an update in the user's location every 30 seconds. The code is working fine i.e. I'm receiving updates in user's location. But the problem is that the GPS icon is always visible on the status bar on top. I'm guessing that it should be visible only once in 30 seconds. Is this normal or I'm doing something wrong?
public volatile Double mLatitude = 0.0;
public volatile Double mLongitude = 0.0;
int minTime = 30000;
float minDistance = 0;
MyLocationListener myLocListener = new MyLocationListener();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestSingleUpdate(criteria, myLocListener, null);
locationManager.requestLocationUpdates(bestProvider, minTime, minDistance, myLocListener);
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc)
{
if (loc != null) {
//Do something knowing the location changed by the distance you requested
mLatitude = loc.getLatitude();
mLongitude = loc.getLongitude();
Toast.makeText(mContext, "Location Changed! "+Double.toString(mLatitude)+" "+Double.toString(mLongitude), Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String arg0)
{
//Do something here if you would like to know when the provider is disabled by the user
Toast.makeText(mContext, "Provider Disabled! "+Double.toString(mLatitude)+" "+Double.toString(mLongitude), Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String arg0)
{
//Do something here if you would like to know when the provider is enabled by the user
Toast.makeText(mContext, "Provider Enabled! "+Double.toString(mLatitude)+" "+Double.toString(mLongitude), Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
//Do something here if you would like to know when the provider status changes
Toast.makeText(mContext, "Provider Status Changed! "+Double.toString(mLatitude)+" "+Double.toString(mLongitude), Toast.LENGTH_LONG).show();
}
}
As long as 1 or more apps have called requestLocationUpdates for the GPS provider, GPS will stay on. It doesn't turn off between requests. It can't- doing so would cause it to lose satellite lock, which would cause it to have to re-establish. That takes a lot more than 30 seconds sometimes. So GPS will stay on until you unregister for GPS events.
The question is old but still, it would be great to give a better answer.
You need to use a Handler which runs continuously on 5 minutes interval so, you get the location update only once and you release the GPS device, this way your app won't listen to the GPS updates but your handler know when it should be called again to listen the updates.
public static void getLocation(Context context) {
Handler locationHandler = new Handler();
locationHandler.post(new Runnable() {
#Override
public void run() {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Handle the location update
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}, null);
locationHandler.postDelayed(this, 1000 * 60 * 5);
}
});
}
On this code i want to get the gps location every 3 seconds. but when i run this program on my device it tells me that latitude and longitude are both 0 every time. how should i handle this problem?
and what is the looper task ?? it gives me error when i donot use it
public class LocationService extends Service {
final static String TAG = "MyService";
double latitude ;
double Longitude ;
LocationManager lm;
LocationListener ll;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread() {
public void run() {
Looper.prepare();
while(true){
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
ll = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, ll);
//when i log here , it gives me wronganswer
Log.d(TAG,Double.toString(latitude));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Log.d(TAG, "OnDestroy");
super.onDestroy();
}
class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
//when i log here , it gives me correct answer
double lat = location.getLatitude();
double lon = location.getLongitude();
latitude = lat;
Longitude = lon;
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
}
When you get location from GPS, it can take some time, because GPS module needs to find satellites. So you need to wait couple or few minutes while GPS module find satellites. If WI-FI location provider available you can get location more quick.
Additional info about location providers you can find here: http://developer.android.com/guide/topics/location/strategies.html
Since Android has
GPS_PROVIDER and NETWORK_PROVIDER
you can register to both and start fetch events from onLocationChanged(Location location) from two at the same time. So far so good. Now the question do we need two results or we should take the best. As I know GPS_PROVIDER results have better accuracy than NETWORK_PROVIDER.
for example you have location listener:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//here you get locations from both providers
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
YOu need to do something like that:
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListener);
but before registering you need to check is these providers available on this device, like that:
boolean network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
Hi I am New to android programming and currently developing an application that uses location manager to get user location and place a marker on a map. i am attempting to use AsyncTask to run the LocationListener and Constantly update the marker when the user location has changed.
this is the class i am working on...
public class IncidentActivity extends MapActivity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.incidentactivity);
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setTraffic(true);
mapController = mapView.getController();
String coordinates[] = {"-26.167004","27.965505"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
geoPoint = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
mapController.animateTo(geoPoint);
mapController.setZoom(16);
mapView.invalidate();
new MyLocationAsyncTask().execute();
}
private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener{
private double latLocation;
private Location l;
//location management variables to track and maintain user location
protected LocationManager locationManager;
protected LocationListener locationListener;
#Override
protected Void doInBackground(Void... arg0) {
Looper.prepare();
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);
this.publishProgress(l);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Location... values) {
super.onProgressUpdate(values);
}
//this method is never executed i dont know why...?
public void onLocationChanged(Location location) {
if (location != null){
latLocation = location.getLatitude();
Toast.makeText(getBaseContext(), " Your latLocation :" + latLocation, Toast.LENGTH_LONG).show();
//Log.d("Your Location", ""+latLocation);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
I've just implemented such AsyncTask:
class GetPositionTask extends AsyncTask<Void, Void, Location> implements LocationListener
{
final long TWO_MINUTES = 2*60*1000;
private Location location;
private LocationManager lm;
protected void onPreExecute()
{
// Configure location manager - I'm using just the network provider in this example
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
nearProgress.setVisibility(View.VISIBLE);
}
protected Location doInBackground(Void... params)
{
// Try to use the last known position
Location lastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If it's too old, get a new one by location manager
if (System.currentTimeMillis() - lastLocation.getTime() > TWO_MINUTES)
{
while (location == null)
try { Thread.sleep(100); } catch (Exception ex) {}
return location;
}
return lastLocation;
}
protected void onPostExecute(Location location)
{
nearProgress.setVisibility(View.GONE);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(this);
// HERE USE THE LOCATION
}
#Override
public void onLocationChanged(Location newLocation)
{
location = newLocation;
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
From what I have read and tried, you cannot use a looper (which is needed by the locationlistener), inside an ASyncTask. Click Here
Actually it mean the two threading models are not compatible, so you can't
use these together. Looper expects to to own the thread that you associate
it with, while AsyncTask owns the thread it creates for you to run in the
background. They thus conflict with each other, and can't be used together.
Dianne Hackborn suggested using a HandlerThread, but I succeeded in getting mine to work inside of an IntentService. I will admit that my code is still a bit of a hack.
i want to make application like this :
User clicks the button
The application show the user's coordinates (Latitude and Longitude)
i'm following the steps here
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
double glat = location.getLatitude();
double glong = location.getLongitude();
Toast.makeText(getApplicationContext(), "Your position\n"+glat+"\n"+glong, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
how to implement it to button click event?
if the user clicks the button, the toast appear showing the position :)
UPDATE
I implement it using startActivityForResult() but the result is empty or null
here's my code :
this is the code on the button that i want to click
btn_obj_useKor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), MyLocationListener.class);
startActivityForResult(intent, 0);
}
});
and this is my MyLocationListener class :
public class MyLocationListener extends Activity{
Intent intent;
String output = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double glat = location.getLatitude();
double glong = location.getLongitude();
output = glat+","+glong;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
intent.putExtra("returnedData", output);
setResult(RESULT_OK, intent);
finish();
}
}
When i click the button it showing WTF! that means the result is null or empty.
what's the problem and what should i do then?
It wont return a result immediately since it takes time for the GPS provider to start and find your location. This is why you listen for a callback event.
Currently your code is listening for the network location, which is not very accurate. Change the LocationManager to GPS_Provider (on your last line) to use GPS if it is enabled.
Responding to an onClick is a user event, the LocationListener onLocationChanged is also an event. If you trigger the user event before the LocationListener event, there will be no position available to display.
My suggestion is to call startActivityForResult on another activity in the button onClick handler, the 2nd activity has all the LocationManager & LocationListener code in it, in the onLocationChanged event handler you pass the position back to the 1st activity.