Get String from Location Android - android

I found a great function which gives me possibility to get Location quickly.
After that i want to display its (longitude and latitude) but it doest work still i get 0.0 / 0.0.
here's code
What should i do if i want display this latitude and longitude mostly I'm interested in function getLastKnownLocation because i want display this data without using GPS or Internet
public class MainActivity extends Activity implements OnClickListener
{
private static final long MIN_TIME_BW_UPDATES = 0;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
public EditText lokalizacja;
public Button pobierz;
private static Context context;
LocationManager locationManager;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude ; // latitude
double longitude; // longitude
public static Context getContext()
{
return context;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lokalizacja = (EditText) findViewById(R.id.editText1);
pobierz = (Button) findViewById(R.id.button1);
pobierz.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.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;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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, (LocationListener) this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
String napis = String.valueOf(latitude+ "\n" + longitude);
lokalizacja.setText(napis);
return location;
}
}

As flow never enter the else part due the following condition
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
You need to have condition something like this
if (!isGPSEnabled || !isNetworkEnabled) {
// no network provider is enabled
} else {
or first check for GPS and then after network

For the first time, for getting your current location, you want to enable gps or network in your device. After getting lat and lng create a preference and save these values to preference. So make some changes in your getLocation() method.
If gps and network are disable try to return the saved value from preference.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />

Related

Unable to get location from gps

I am trying to create an app which gets latitude and longitude from user's gps this is the class that I am using :-
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;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// 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;
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) {
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 TODO;
Toast.makeText(this,"It's very important that you agree to gps permission, kindly restart the app and accept",Toast.LENGTH_LONG).show();
}
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);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
when I call this function in MainActivity it never asks for any permissions and also doesn't show any errors this is the function that I am using :-
String getlocurl(){
GPSTracker gps;
gps = new GPSTracker(MainActivity.this);
double latitude = 0;
double longitude = 0;
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
String mapurl = "https://www.google.com/maps/preview/#"+lat+","+lng+","+"8z";
return mapurl;
}
else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
return "error";
}
}
This is the result that I get : "https://www.google.com/maps/preview/#0.0,0.0,8z"
it returns 0.0,0.0 as latitude and longitude, how do I fix this?
Put this on your Manifest file before the application tag:
<uses-permission android:name="android.permission.INTERNET" /> <!-- verify if connected to the internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- verify if connected to any network -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- verify location using GPS, give precise location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- verify location using WiFi and mobile, gives approximate location -->

Getting "satellites in view", and "satellites in use" counts in Android

I am having an unusually difficult time getting correct "satellites in use" and "satellites in view" integers from my GPS implementation. I have reviewed numerous relevant Stackoverflow threads with no immediate enlightenment. Below is what I have so far that "should" work, however it does not. I've rebuilt this several times from different perspectives without getting either the number of satellites in use or satellites in view. Thanks in advance...
public class GpsData extends Service implements LocationListener {
private GpsStatus mGpsStatus;
private final Context mContext;
boolean isGPSEnabled = false; // flag for GPS status
boolean isNetworkEnabled = false; // flag for network status
boolean canGetLocation = false; // flag for GPS status
Location location; // location
double dLatitude, dAltitude, dLongitude, dAccuracy, dSpeed, dSats;
float fAccuracy, fSpeed;
long lSatTime; // satellite time
String szSignalSource, szAltitude, szAccuracy, szSpeed;
public String szSatellitesInView;
public String szSatellitesInUse;
public static String szSatTime;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters
private static final long MIN_TIME_BW_UPDATES = 1000; //1 sec
protected LocationManager locationManager;
protected GpsListener gpsListener = new GpsListener();
public GpsData(Context context) {
this.mContext = context;
getLocation();
locationManager.addGpsStatusListener(gpsListener);
}
class GpsListener implements GpsStatus.Listener{
#Override
public void onGpsStatusChanged(int event) {
int iCountInView = 0;
int iCountInUse = 0;
mGpsStatus = locationManager.getGpsStatus(mGpsStatus);
Iterable<GpsSatellite> satellites = mGpsStatus.getSatellites();
if (satellites != null) {
for (GpsSatellite gpsSatellite : satellites) {
iCountInView++;
if (gpsSatellite.usedInFix()) {
iCountInUse++;
}
}
}
{
{
szSatellitesInView = String.valueOf(iCountInView);
szSatellitesInUse = String.valueOf(iCountInUse);
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS satellite status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting cellular 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.addGpsStatusListener(gpsListener);//needed?
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Cell tower", "Cell tower");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
dLatitude = location.getLatitude();
dLongitude = location.getLongitude();
lSatTime = location.getTime();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.addGpsStatusListener(gpsListener);
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);
if (location != null) {
dLatitude = location.getLatitude();
dLongitude = location.getLongitude();
lSatTime = location.getTime();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
Got it.
public class GpsData extends Service implements LocationListener {
boolean isGPSEnabled = false; // flag for GPS satellite status
boolean isNetworkEnabled = false; // flag for cellular network status
boolean canGetLocation = false; // flag for either cellular or satellite status
private GpsStatus mGpsStatus;
private final Context mContext;
protected LocationManager locationManager;
protected GpsListener gpsListener = new GpsListener();
Location location; // location
double dLatitude, dAltitude, dLongitude, dAccuracy, dSpeed, dSats;
float fAccuracy, fSpeed;
long lSatTime; // satellite time
String szSignalSource, szAltitude, szAccuracy, szSpeed;
public String szSatellitesInUse, szSatellitesInView;
public static String szSatTime;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters
private static final long MIN_TIME_BW_UPDATES = 1000; //1 second
public GpsData(Context context) {
this.mContext = context;
getLocation();
}
class GpsListener implements GpsStatus.Listener{
#Override
public void onGpsStatusChanged(int event) {
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);// getting GPS satellite status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);// getting cellular network status
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {//GPS is enabled, getting lat/long via cellular towers
locationManager.addGpsStatusListener(gpsListener);//inserted new
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Cell tower", "Cell tower");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
szAltitude = " NA (using cell towers)";
szSatellitesInView = " NA (using cell towers)";
szSatellitesInUse = " NA (using cell towers)";
}
}
}
if (isGPSEnabled) {//GPS is enabled, gettoing lat/long via satellite
if (location == null) {
locationManager.addGpsStatusListener(gpsListener);//inserted new
locationManager.getGpsStatus(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);
if (location != null) {
dAltitude = location.getAltitude();
szAltitude = String.valueOf(dAltitude);
/**************************************************************
* Provides a count of satellites in view, and satellites in use
**************************************************************/
mGpsStatus = locationManager.getGpsStatus(mGpsStatus);
Iterable<GpsSatellite> satellites = mGpsStatus.getSatellites();
int iTempCountInView = 0;
int iTempCountInUse = 0;
if (satellites != null) {
for (GpsSatellite gpsSatellite : satellites) {
iTempCountInView++;
if (gpsSatellite.usedInFix()) {
iTempCountInUse++;
}
}
}
szSatellitesInView = String.valueOf(iTempCountInView);
szSatellitesInUse = String.valueOf(iTempCountInUse);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}

Android GPS using old locations

Im trying to learn more about location services in android and am attempting to build an app which can locate an Android device and send it's latitude and longitude to a server. I've had everything working as expected for a while, but am still being bothered by a small bug. When I send the command from the server to locate the device the first time, the device returns a recent, but old, location such as a road I drove on the same day.
On the second time the device receives a command from the server to locate the device, the device returns an accurate location.
Here is the relevant code:
LocationTracker.java
public class LocationTracker extends Service implements LocationListener {
//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*1000; //10,000 meters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10000; // 10,000 minutes
//Declaring a Location Manager
protected LocationManager locationManager;
public void fetchLocation(Context context) {
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
new MyAsyncTask().execute(stringLatitude, stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.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;
//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();
}
}
}
//If no GPS, get location from Network Provider
if (isNetworkEnabled && !isGPSEnabled)
{
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();
}
}
}
}
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(LocationTracker.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;
}
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
Log.i("New Location: ", stringNewLatitude + " " + stringNewLongitude);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public IBinder onBind(Intent intent)
{
return null;
}
Why is my location updating as an old location the first time it tries, and a correct location on the second time?
Also note that I would also like to remove requestLocationUpdates seen here:
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
because it causes a handler on dead thread warning, but when I removed it my device stopped acquiring my location. This may be part of the problem.
I would greatly appreciate any help!
It's because you're using getLastKnownLocation().
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation(String Provider) :
Returns a Location indicating the data from the last known location fix obtained from the given provider.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

Location only refreshes when I turn GPS off

So I have a problem when trying to resolve my location. When given the command to find my location, it instead gives me the last location of where I turned my GPS off. Being able to find my coarse location using WiFi also seems to not be working.
Here is my current class
public class LocationTracker extends Service implements LocationListener {
//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 void fetchLocation(Context context) {
contextnormal = context;
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.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(LocationTracker.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;
}
#Override
public void onLocationChanged(Location location)
{
//Want to Execute Asynctask method to HTTP post the lat and long. Is there a way `to pass in a context to do this?`
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
if (contextnormal != null) {
fetchLocation(contextnormal);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
I would guess the problem lies in these lines
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();
}
}
And for some reason it is giving the last known location as the last time the GPS was turned on. Any ideas as to why it is doing that instead of giving the last known location as the present location if the GPS is on?
EDIT:
Implementing the following method and testing:
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
You can't just query the location manager for its last known location repeatedly, that will only get you the last known location. It sounds like what you are trying to do is get location updates as you move around.
In this case, you will need to register for location updates, as you tried with your line:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
You are on the right track here, but what is this (the last argument on the function call [yes I know it is a reference to the current class...])? The last argument is supposed to be an intent or a callback where the updates will be broadcast to. It doesn't appear that you have implemented that from the code you provided.
Change your this argument to a class which implements LocationListener. The location updates will come to the onLocationChanged method where you can then process them as you see fit. A simple way to do this is to add a nested inner class which implements the listener, then you can just create an instance of that class and pass it to the location manager, in place of your current this argument.
EDIT
OK, so you are implementing the thing correctly, but blisfully ignoring the location updates, don't do that. The service you have is a Context -- so you can pass that around as you see fit, although it may be better to use:
this.getApplicationContext();
If you are passing it to some long running thing. What I would recommend is to queue your location updates when the arrive in onLocationChanged(). After queuing the location, signal a background worker thread (or AsyncTask) to actually post the location to your web service.
Also, don't override onBind and return null. Just don't override it.

Send GPS data while App is running background in Android

I developed app that getting GPS data and send to Server. So i want to get GPS data while my app is running background in Android device. I have search in many websites, but i could not answer.
I use 2 class. One of them is Main class and another is GPSTracker class. Now i give some part code of 2 class.
Main Class
public class Request extends Activity {
public static Float longitude;
public static Float latitude;
public static int ID;
public static String URL="http://xxx.xxx";
GPSTracker gps;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
final Button button_send_info = (Button)findViewById(R.id.button_send_info);
final TextView show_infos = (TextView) findViewById (R.id.textView1);
gps = new GPSTracker(Request.this);
if(gps.canGetLocation()){
latitude = (float) gps.getLatitude();
longitude = (float) gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
if( Build.VERSION.SDK_INT >= 8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button_send_info.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("latitude", latitude.toString()));
postParameters.add(new BasicNameValuePair("longitude", longitude.toString()));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost(URL, postParameters);
String res=response.toString();
show_infos.setText(res);
}
catch (Exception e)
{
//hata alanı
}
}
});
GPSTracker Class;
public class GPSTracker extends Service implements LocationListener {
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;
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);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
How can i do it?
There is a component called Service in android. It provides background activity. You can perform background process in it. Service has no GUI. You can write a GPS fetching code there.
Have a look at simple tutorial of Service components from Vogella.

Categories

Resources