Get latitude and longitude periodically using alarm manager - android

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

Related

how to retrieve user selection from settings in the device

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;
}
}

Search for location after enabling it within the app

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;

GPS Icon wont dissapear when remove updates is called from onPause Android

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);
}

How to get the data from the BroadcastReceiver to another class BroadcastReceiver

I am using the BroadcastReceiver in my application ,here i am receiving the current location and place in this class.hence i am getting the current location,hence my question is how to send this location string from this class to another class .i have to load this string data in the listview in another class so how can do this please help thanks in advance. My code is
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
MyTrip trip_method;
double latitude, longitude;
Context context;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
protected LocationManager locationManager;
Location location;
#Override
public void onReceive(Context context, Intent intent) {
trip_method = new MyTrip();
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Find_location();
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
public void Find_location() {
// Location nwLocation;
try {
location = getLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("nwLocation-------" + location);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println("latitude-------" + latitude + "longitude-----" + longitude);
Toast.makeText(
context,
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
// To display the current address in the UI
(new GetAddressTask()).execute(location);
} else {
trip_method.showSettingsAlert("NETWORK");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
/* *//**//*
* Following is a subclass of AsyncTask which has been used to get
* address corresponding to the given latitude & longitude.
*//**//**/
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
/* public GetAddressTask(Context context) {
super();
mContext = context;
}*/
/* *//**//*
* When the task finishes, onPostExecute() displays the address.
*//**//**/
#Override
protected void onPostExecute(String address) {
// Display the current address in the UI
Toast.makeText(context.getApplicationContext(),
"address---" + address,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Location... params) {
String Address = null;
String Location = null;
Geocoder geocoder;
List<android.location.Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2);
Location = addresses.get(0).getAddressLine(2);
System.out.println("Location----" + Location);
//This "Location" value i have to send to another activity
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the text
return Address;
/* } else {
return "No address found";
}*/
}
}// AsyncTask class
}
Use this in your code as appropriate:
In your First class:
Intent intent = new Intent(this, another_activity.class);
intent.putExtra("Location", Location.toString);
startService(intent)
In your Second class:
String Location = getActivity().getIntent.getStringExtra("Location")
Now you have passed string from one class to another. Use the Location variable where you need it.

how to enable GPS on long key press of power button while screen is locked in Android?

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;
}
}

Categories

Resources