I have the following class to get the user location.
public class GetUserLocation extends Activity {
Timer timer1;
LocationManager locationManager = null;
LocationResult locationResult;
boolean gpsEnabled = false;
boolean networkEnabled = false;
public static Location userLocation = null;
public String checkProviders(Context context) {
if (locationManager == null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
gpsEnabled = false;
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
networkEnabled = false;
}
if(!gpsEnabled && !networkEnabled)
return "No Location Service Found.\nPlease turn on your location service by\nenabling GPS or Data Service or WI-FI";
if(gpsEnabled && !networkEnabled)
return "No Internet Service Found.\nPlease turn on your inernet service by\nenabling Data Service or WI-FI";
return null;
}
public boolean getLocation(Context context, LocationResult result) {
locationResult = result;
if (locationManager == null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
// exceptions will be thrown if provider is not permitted.
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
// don't start listeners if no provider is enabled
if (!gpsEnabled && !networkEnabled)
return false;
if (gpsEnabled) {
locationManager.removeUpdates(locationListenerGps);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListenerGps);
}
if (networkEnabled) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListenerNetwork);
}
timer1 = new Timer();
//timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
// class GetLastLocation extends TimerTask {
// #Override
// public void run() {
//
// locationManager.removeUpdates(locationListenerGps);
// locationManager.removeUpdates(locationListenerNetwork);
//
// Location networkLocation = null, gpsLocation = null;
// if (gpsEnabled) {
// //t = Calendar.getInstance().getTimeInMillis();
// gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// }
//
// if (networkEnabled) {
// networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// }
//
// // if there are both values use the latest one
// if (gpsLocation != null && networkLocation != null) {
//
// if (gpsLocation.getTime() > networkLocation.getTime())
// locationResult.gotLocation(gpsLocation);
// else
// locationResult.gotLocation(networkLocation);
//
// return;
// }
//
// if (gpsLocation != null) {
// locationResult.gotLocation(gpsLocation);
// return;
// }
//
// if (networkLocation != null) {
// locationResult.gotLocation(networkLocation);
// return;
// }
//
// locationResult.gotLocation(null);
// }
// }
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
public void removeUpdates() {
if(timer1!=null) {
timer1.cancel();
}
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
userLocation = null;
locationResult.gotLocation(null);
}
public Timer getTimer() {
return this.timer1;
}
}
This code is working good for other devices, but not in galaxy s3. But in the test S3 device the google map is getting the user location fix.
Can anyone say why is this happening? Any Hints will be appreciated.
I solved a problem like this, installing the APP GPS Status, that reset the GPS.
Solution found at:
http://productforums.google.com/forum/#!topic/maps/q24Cq4sQAtc%5B1-25-false%5D
OR just, try clearing the App Data from "Maps".
You'll then need to re-grant access to location services when prompted.
Hugs
Related
I have implemented to get the user's current location when user clicked the agreement button. I have implemented the LocationListener in the activity and I have unregistered the listener at both onStop and onDestroyed. But according to LeakCanary, memory leak is still existing.
This is a brief of My code.
public class UserProfileEditActivity extends BaseActivity implements DatePickerDialog.OnDateSetListener, LocationListener, LocationResult {
LocationManager locationManager;
LocationHelper myLocation;
LocationResult locationResult;
public void getCurrentUserLocation() {
myLocation.getLocation(this);
}
#Override
protected void onStart() {
super.onStart();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
myLocation = new LocationHelper(locationManager, this);
}
#Override
protected void onPause() {
locationManager.removeUpdates(this);
super.onPause();
}
#Override
protected void onStop() {
reset();
super.onStop();
}
#Override
protected void onDestroy() {
reset();
super.onDestroy();
}
//implementation of LocationResult
#Override
public void gotLocation(Location location) {
//Got the location!
getCurrentUserHomeTown(location);
if (location != null)
showLog("Location lat :" + location.getLatitude() + " long :" + location.getLongitude());
}
private void reset() {
if (confirmationDialog != null)
confirmationDialog.dismiss();
if (myLocation != null) {
myLocation.stopLocationListeners();
locationManager.removeUpdates(this);
locationResult = null;
locationManager = null;
myLocation = null;
}
}
#Override
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
And this is how I trigger to gather location.
public void getCurrentUserLocation() {
myLocation.getLocation(this);
}
this is LocationHelper.class
public class LocationHelper {
private LocationResult locationResult;
private LocationManager locationManager;
private boolean gps_enabled = false;
private boolean network_enabled = false;
// private Timer timer;
private LocationListener locationListener;
public LocationHelper(LocationManager locationManager, LocationListener locationListener) {
this.locationManager = locationManager;
this.locationListener = locationListener;
}
#SuppressLint("MissingPermission")
public boolean getLocation(LocationResult result) {
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult = result;
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ignored) {
}
//don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, (float) 10.0, locationListener);
if (network_enabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0, locationListener);
getLastLocation();
// timer.schedule(new GetLastLocation(locationManager, locationListenerGps, locationListenerNetwork, gps_enabled, network_enabled, locationResult), 40000);
return true;
}
#SuppressLint("MissingPermission")
public void getLastLocation() {
locationManager.removeUpdates(locationListener);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
public void stopLocationListeners() {
locationManager.removeUpdates(locationListener);
// if (timer != null) {
// timer.cancel();
// timer = null;
// }
locationListener = null;
locationResult = null;
locationManager = null;
}
}
But the LeakCanary keep indicating there is memory leak with LocationManager and LocationListener. Please Help me find out this.
Hello I have a question for a class project app I am working on. I have a Notes app that pretty simply records text input from edit texts into a SQLite database and then retrieves each of them to a list fragment for the user to view. They can also click on each list item and that opens another fragment that displays the "details" of the entry, i.e. Subject, body content, time, and date entered. I want to make an addition that records user's current GPS/Network location for that particular entry (geotagging). I have a floating action button in the note details fragment that should link to a Map fragment with a marker on it corresponding to the location recorded when that entry was made. I'm fairly new to Android so still learning about all this. Just a bit hung up on this. Does anyone have a good explanation on how to save location into that same database (lat, long) when the entry is submitted, and then when the user clicks the FAB in details fragment, it displays a map with location marker for each respective entry? Please let me know if anyone can help, or if any of my database classes are needed?
Also want to add that I have indeed looked in quite a few places on Google, but I'm not quite sure if maybe I am using the wrong terminology or what, but results seems to be off for what I am looking for.
Here you have a class for getting the location:
public class MyLocation {
private static final int REQUEST_PERMISSIONS = 1;
private Timer timer1;
private LocationManager lm;
private LocationResult locationResult;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private String[] permissions = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
public boolean getLocation(final Context context, LocationResult result) {
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
try {
boolean allPermissionsGranted = true;
for(int i=0; i<permissions.length;i++) {
if(!Utils.PermissionGranted(permissions[i], context)) allPermissionsGranted = false;
}
if(!allPermissionsGranted) {
ActivityCompat.requestPermissions((Activity)context, permissions, REQUEST_PERMISSIONS);
return false;
}
if (gps_enabled) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
});
}
if (network_enabled) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
});
}
} catch (SecurityException e) {
Utils.Toast(context, e.getMessage());
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 5000);
return true;
}
private LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if(gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc != null && net_loc != null){
if(gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc != null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc != null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
When you are about to add a new note just do:
MyLocation.LocationResult locationResult = new MyLocation.LocationResult(){
#Override
public void gotLocation(Location location){
mCurrentLocation = location;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Any UI related code
}
});
}
};
Then for the map:
Go to https://developer.android.com/training/maps/index.html. You have to add a marker for every location in your database.
In my android app I'm retrieving user location for every 3 minutes and somehow I'm doing it in the following way.problems so far I have faced are
Whenever I'm getting location updates I'm getting multiple values at same time
Sometimes I'm getting both GPS and NETWORK provider values at a time.
I need only one value and also it should be either GPS or NETWORK Provider value,How to achieve this.
Here is my Service
public class MyService extends Service {
private static final String TAG = "TESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 180000;
private static final float LOCATION_DISTANCE = 0.0f;
double lati,longi;
String loc_name;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.i(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
Toast.makeText(getApplicationContext(), ""+location.getLatitude()+"==>"+location.getLongitude(), Toast.LENGTH_SHORT).show();
lati = location.getLatitude();
longi = location.getLongitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1);
if (addressList != null && addressList.size() > 0) {
{
loc_name = addressList.get(0).getAddressLine(1);
}
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeLocation());
Toast.makeText(getApplicationContext(), "" + params, Toast.LENGTH_LONG).show();
client.post("http://192.168.0.120/gpstracker/send_location.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Log.i("Status ==> ", "Sent to server");
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
mLastLocation.set(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(MyService.this, "Service Started", Toast.LENGTH_SHORT).show();
Log.i("Service Started", "Started");
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.i(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public String composeLocation()
{
ArrayList<HashMap<String, String>> locationList = new ArrayList();
HashMap<String, String> map = new HashMap();
String parsed_lati = String.valueOf(lati);
String parsed_longi = String.valueOf(longi);
map.put("e1", "123");
map.put("lati",parsed_lati);
map.put("longi",parsed_longi);
map.put("loc_name",loc_name);
locationList.add(map);
return new GsonBuilder().create().toJson(locationList);
}
}
You should first check before getting location from both. First check if location is available through gps and if not then use network to get location.
Here is a sample class which have methods for checking location.
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("Turn on your GPS to find nearby helpers");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should use Criteria to request location update instead of using Provider:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, listener, null);
That way you can use only one listener and the location value can be from either GPS or NETWORK provider.
I have an app that updating user location is the main feature of it.
So far I have a class that get users location through both GPS and NETWORK providers . It works just fine :
public class UserLocation {
private String TAG = "UserLocation";
Timer timer;
LocationManager locationManager;
OnLocationResultListener listener;
boolean gps_enabled = false;
boolean network_enabled = false;
public UserLocation setListener(OnLocationResultListener listener) {
this.listener = listener;
return this;
}
public boolean getLocation() {
if (locationManager == null) {
locationManager = (LocationManager) G.context.getSystemService(Context.LOCATION_SERVICE);
}
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Location GPS_PROVIDER is off");
ex.printStackTrace();
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Location NETWORK_PROVIDER is off");
ex.printStackTrace();
}
timer = new Timer();
timer.schedule(new GetLastLocation(), 0, GlobalConsts.LOCATION_RECHECK_TIME);
return true;
}
LocationListener gpslocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e(TAG, "Calling gpslocationListener==> onLocationChanged");
timer.cancel();
listener.onGotLocation(location);
locationManager.removeUpdates(gpslocationListener);
locationManager.removeUpdates(networklocationListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e(TAG, "Calling networklocationListener==> onLocationChanged");
timer.cancel();
listener.onGotLocation(location);
locationManager.removeUpdates(networklocationListener);
locationManager.removeUpdates(gpslocationListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
Log.e(TAG, "Getting last location in TimeTask ");
locationManager.removeUpdates(gpslocationListener);
locationManager.removeUpdates(networklocationListener);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
listener.onGotLocation(gps_loc);
else
listener.onGotLocation(net_loc);
return;
}
if (gps_loc != null) {
listener.onGotLocation(gps_loc);
return;
}
if (net_loc != null) {
listener.onGotLocation(net_loc);
return;
}
if (gps_loc == null && net_loc == null) {
Log.e(TAG, "tried to get location in Timetask but both location was null");
} else if (gps_loc == null) {
Log.e(TAG, "gps_loc is null in time task");
} else {
Log.e(TAG, "net_loc is null in time task");
}
listener.onGotLocation(null);
}
}
public interface OnLocationResultListener {
void onGotLocation(Location location);
void onNoLocationProvider();
}
}
The thing that I want is to get user location even if he is not using the app ( I mean getting his location when it changes , even if the app is not up and running)
What is the best approach to achieve this ?
Should I make a service and run this ?
How about using Google Play Location Api ? Does this help me ?
Thanks in advance.
Create this service which will always running in background even if your application is not running.
public class MyLocationService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public MyLocationService() {
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this)
.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("MyLocationService.onLocationChanged");
// do your work here with location
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mGoogleApiClient.disconnect();
super.onDestroy();
}
}
I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}