Getting "satellites in view", and "satellites in use" counts in Android - 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;
}

Related

How can I get current location lattitude and longitude in marshmallow and later versions?

First I want to check Internet connection is connected or not .if not connected then show dilog box for start Internet connection.
Then I want to check GPS is on or not if on then get latitude and longitude location and show the latitude and longitude in text or in Toast.
In My Code I have Used GPS Tracker to get location.
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) {
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;
}
/**
* 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
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS Setting");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
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() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#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 arg0) {
return null;
}
}
Main Activity onCreate I have used below code to get location in latitude and longitude
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
CurrentLattitude = gpsTracker.getLatitude();
CurrentLongitude = gpsTracker.getLongitude();
Log.e(TAG, String.valueOf(CurrentLattitude));
Log.e(TAG, String.valueOf(CurrentLongitude));
} else {
gpsTracker.showSettingsAlert();
}
I am getting location in and able to see in Logcat when runs on kitkat but when same code I am using in marshmallow it will gives below:
E/latlang: 0.0
E/latlang: 0.0
How can I get the latitude and the longitude in marshmallow?
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Checking internet connection:
private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}

Android GPS App - How do I alter it to continuously update the gps coordinates?

currently my android app is working to get gps coordinates and print them to my screen. The issues is that they seem to sometimes be up to 300m inaccurate. I don't understand how to alter it so that it will actually get a gps fix and continuously update my longitude and latitude with accurate coordinates.
The following code is my GPS handler.
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
else {
gps.showSettingsAlert();
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
locationManager.getBestProvider(criteria, true);
Hope this wil helps you.
It looks like you use both Network Provider and GPS Provider for getting the location updates. Because Network Provider is relying on cell tower and Wi-Fi signals, it will be less accurate than GPS Provider.
To solve this problem, you can filter the location received by LocationManager by this method
private static final int TWO_MINUTES = 1000 * 60 * 2;
/** Determines whether one Location reading is better than the current Location fix
* #param location The new Location that you want to evaluate
* #param currentBestLocation The current Location fix, to which you want to compare the new one
*/
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
Taken from : http://developer.android.com/guide/topics/location/strategies.html
or
Just disable updates from Network Provider by removing these lines from your code
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

Storing latitude and longitude in CSV file every 15 minutes

I want to access users location i.e latitude and longitude in every 15 minutes and store them in a CSV file. How can I do this?
I have a GPSTracker class:
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 * 15; // 15 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;
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS() {
if (locationManager != null) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
and in MainActivity:
File root = Environment.getExternalStorageDirectory();
File gpxfile = new File(root, "mydata.csv");
try {
writer = new FileWriter(gpxfile);
writeCsvHeader("DateTime", "Latitude", "Longitude");
writeCsvData(""+strDate,latitude,longitude);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
private void writeCsvHeader(String h1, String h2, String h3) throws IOException {
String line = String.format("%s,%s,%s\n", h1,h2,h3);
writer.write(line);
}
private void writeCsvData(String date, double lat, double lon) throws IOException {
String line = String.format("%s,%f,%f\n", date, lat, lon);
writer.write(line);
}
for CSV I have referenced
http://antipastohw.pbworks.com/w/page/41913616/Write%20CSV%20files%20onto%20SD%20Card%20Storage
For doing an repetitive task you can use Handler like,
handler.postDelayed(new Runnable(){
#Override
public void run() {
// get Location or do whatever you want
}
}, (15 * 60 * 1000));
In this case getLocation() will call after every 15 min.
May this way possible
Timer timer = new Timer();
timerTask = new TimerTask() {
Handler mnhandler = new Handler();
#Override
public void run() {
mnhandler.post(new Runnable() {
#Override
public void run() {
//Use ur method which store CSV file
}
});
}
};
timer.schedule(timerTask, start, duration);

Get String from Location 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" />

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