Hi i am having a issue where the location icon wont dissaprear after calling location.removeUpdates. I have followed this solution.
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context context) {
this.mContext = context;
//getLocation();
}
/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* #return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* #return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
When i call the stopUsingGPS function it calls it but doesnt stop the location service, it still shows the icon in the action bar.
#Override
public void onPause() {
super.onPause();
GPSTracker gpsTracker = new GPSTracker(getActivity());
gpsTracker.stopUsingGPS();
}
Any suggestion would be gratefully appreciated. Thank you.
You can't really create a new instance of GPSTracker and call functions there. Because you've already started the Service. To achieve this, you should implement a ServiceConnection with a Binder.
In your Service add,
private final IBinder locationBinder = new LocationBinder();
#Override
public IBinder onBind(Intent intent) {
return locationBinder;
}
public class LocationBinder extends Binder {
public GPSTracker getService() {
Log.v("Test", "GPSTracker: getService() called");
return GPSTracker.this;
}
}
And in your activity,
private GPSTracker gpsTracker;
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder baBinder) {
gpsTracker = ((GPSTracker.LocationBinder) baBinder).getService();
}
public void onServiceDisconnected(ComponentName className) {
gpsTracker = null;
}
};
And the in your activity's onCreate(),
Intent locationIntent = new Intent(this, GPSTracker.class);
startService(locationIntent);
bindService(locationIntent, serviceConnection, Context.BIND_AUTO_CREATE);
And then onPause(),
#Override
public void onPause() {
super.onPause();
gpsTracker.stopUsingGPS();
}
And then onDestroy(),
#Override
public void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
Related
I want making an app, get latitude and longitude every 5 minute. I have class to get it. But i can't get the latitude and longitude using alarm manager from receiver class alarm manager .
i have some error
Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
this is my class receiver
public class AlarmReceiver extends BroadcastReceiver {
public static final String TYPE_REPEATING = "RepeatingAlarm";
private final int NOTIF_ID_REPEATING_SEND_DATA = 101;
public static final String EXTRA_TYPE = "type";
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
String type = intent.getStringExtra(EXTRA_TYPE);
String latitude = intent.getStringExtra("LATITUDE");
String longitude = intent.getStringExtra("LONGITUDE");
int notifId = 0;
if (type.equalsIgnoreCase(TYPE_REPEATING)) {
notifId = NOTIF_ID_REPEATING_SEND_DATA;
getLokasiTerkini(mContext);
//sendDataToServer(latitude,longitude);
}
}
private void getLokasiTerkini(Context context) {
GPSTracker gpsTracker = new GPSTracker(context);
gpsTracker.getLocation();
String latitude = String.valueOf(gpsTracker.getLatitude());
String longitude = String.valueOf(gpsTracker.getLongitude());
Log.d("GET_LAT_LONG", "getLokasiTerkini: " + latitude + " " + longitude);
}
private void sendDataToServer(final String latitude, final String longitude) {
String url = "http://192.168.57.121/GetLatLongAndroid/api/addLatLong.php";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("latitude", latitude);
requestParams.put("longitude", longitude);
client.post(url, requestParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
int value = response.getInt("value");
if (value == 1) {
String message = response.getString("message");
Log.d("PESAN", "onSuccess: " + message);
} else {
String message = response.getString("message");
Log.d("PESAN", "onSuccess: " + message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void setRepeatSendData(Context context, String type, String latitude, String longitude) {
mContext = context;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(EXTRA_TYPE, type);
intent.putExtra("LATITUDE", latitude);
intent.putExtra("LONGITUDE", longitude);
int requestCode = NOTIF_ID_REPEATING_SEND_DATA;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
1 * 60 * 1000,
pendingIntent);
Toast.makeText(context, "Send Repeat Data Activated", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
int requestcode = NOTIF_ID_REPEATING_SEND_DATA;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestcode, intent, 0);
alarmManager.cancel(pendingIntent);
Toast.makeText(context, "Repeating Alarm Dibatalkan", Toast.LENGTH_SHORT).show();
}
}
This is my GPSTracker class
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
public static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
if (!provider_info.isEmpty()) {
if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
locationManager.requestLocationUpdates(provider_info, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
} catch (Exception e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* #return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* #return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_refresh, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
public String getFeaturName(Context context){
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String featureName = address.getFeatureName();
return featureName;
}else {
return null;
}
}
public String getPremises(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String premises = address.getPremises();
return premises;
}else {
return null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
I want my class GPSTracker to access from receiver class.
Not possible to start LocationManager in BroadcastReceiver(You have used GPSTracker class here). So let use service on BroadcastReceiver and in that service you can use GPSTracker class.
write this in onReceive method
Intent serviceIntent = new Intent(context,YourService.class);
context.startService(serviceIntent); //start service for get location
my application is using GPS services now i in case the GPS is off the user have the option to navigate to the device settings and set the GPS on.
now i would like to handle the user selection,
in case the user turn on the GPS the app should run again the getLocation function other wise do nothing.
but i do not know how can i handle the result of the new activity because i run it from non activity class. the relevant method is LocationAlertDialog
this is my class code:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating,tryLocating = true;
private LocationManager locationManager;
private Location currentLoc=null;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
listener.getLocationInProccess();
try {
locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on Settings and make sure your GPS is enabled");
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) {
tryLocating =false;
listener.onLocationFound(currentLoc);
dialog.cancel();
}
});
alertDialog.show();
}
/**
* this function get Longitude and Latitude coordinates and send back the real street address.
* #param LATITUDE
* #param LONGITUDE
* #param ctx
* #return
*/
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
/**
* this function convert real address to geographical coordinates.
* #param strAddress -real address
* #return LatLng object which contain the coordinates
*/
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
Log.d("coordinates",p1.latitude+""+p1.longitude);
} catch (Exception ex) {
Log.d("Location Exception", "error converting address");
ex.printStackTrace();
}
return p1;
}
public boolean isTryLocating() {
return tryLocating;
}
}
So I found this code online to help with using GPS on android and right now I've got my app to find my current location if my GPS is on before running the application. But I was wondering how I would be able to find my location in the following situation:
1. Location is turned off.
2. Run the app.
3. Turn location on from the power toggles.
The code I'm using for GPS is:
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 ; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* #return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* #return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle("GPS Disabled");
//Setting Dialog Message
alertDialog.setMessage("To find the restaurants nearest to you, please turn on your GPS");
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Also in the OnCreate method, I've instantiated the class as follows:
gpsTracker = new GPSTracker(this){
#Override
public void onLocationChanged(Location location) {
//do stuff
}
Well I figured it out. For some reason, there was no network_provider and since gps_provider was off, it would get to the line
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
and would just pass over it and not run the requestLocationUpdates, hence not allowing the gpsTracker object to be notified whether anything was being updated or not. All I did was I made
String provider_info = LocationManager.GPS_LOCATION;
I have use this below code for find the current location but i got that some devices(samsung 7' and 10'inch and nexus 10'inch) exact current locations,but unfoirtunately i can't find the locations in samsung s3.
I don't have any idea ,what is issue.no find the locations.
here is my code:
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
}
else
{
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
When the location comes in check for accuracy. If its not accurate enough then don't process it.
#Override
public void onLocationChanged(Location location) {
if (!location.hasAccuracy()) {
return;
}
if (location.getAccuracy() > 5) {
return;
}
// do something with location accurate to 5 meters here.
}
Do this, Load the application in your device, move to open sky, run the application, wait for 2 minutes. Come back to office inside, and then execute above code
It worked for me.
Hope it helps you.
We worked in Samsung devices and had issues too. Just ensure the following:
GPS is on (Street Level should also be enabled)
Mobile Network is enabled (If required, also enable Use packet data option)
Download and install some 3rd party widgets in your phone and wait till the location coordinates appear/refresh in the widget. (This is because the widgets have timeout concept integrated in them and keep trying repeatedly to get coordinates)
Goto Google-maps from the device and check if your location is being identified. (Sometimes, we have observed that Google Maps would be able to identify coordinates where as we would not be able to!!)
Ensure that the GPS Satellite signal on the notification header bar is blinking.
If required, set a timer for refresh and add toast messages to display lat long once obtained.
For samsung device alone, for the first time, the GPS Coordinates do not get reflected immediately (It is null and can last upto half an hour :( How Annoying!! ). So, we used to wait outside the office for some time till the GPS coordinate is recieved.
I had the same problem. The point is: You need a time-gap between your "requestLocationUpdates" and "getLastKnownLocation"
Try to start requestLocationUpdates in the "onStart" or "onCreate" method.
protected void onStart() {
super.onStart();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
This activates your GPS. You have to wait some seconds until it found some locations.
So i put the "getlastKnownLocation" - method in an OnClickEvent. If no location is found it just displays a Toast.
public void onClick(View v) {
m_CurrentLocation = m_LocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (m_CurrentLocation != null)
// Your action with the last known location
else
Toast.makeText(YourActivity.this, "No GPS Location found", Toast.LENGTH_SHORT).show();
}
There are numerous bugs with LocationManager, why don't you try using fused location provider with LocationClient instead. The devs at Google have recommended this as well during the last Google I/O.
Unless the device runs on versions older than Froyo which do not have play services, there is no reason to use LocationManager.
I'm Developing an application to send User's current location on selected contact number when user long presses power key button while the device is actually locked as pattern/screen lock mode. so how can i enable GPS so that it gets auto enable and gets current longitude and latitude.
First, you need to take care of the key press, and there is some good information here.
Here is an example of getting longitude and latitude:
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
}
else
{
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}