in my application i have a button that start counting the time how long the user has been in the same location. and i want the app stop the timer counting if the user goes out from the area he started so i made a class that give me the current location (LAT,LONG,PLACE NAME) and i don't know how to use the "onLocationChanged" and Should I use it? or something else for what i need?
public class MapCurrentPlace extends Service implements LocationListener {
private final Context mContext;
public static final String MY_TEMP = "sharedFile";
SharedPreferences setting;
SharedPreferences.Editor editor;
// 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
String placeName = "";
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 500; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public MapCurrentPlace(Context context) {
this.mContext = context;
getLocation();
}
public String getPlaceName(){
Geocoder gc = new Geocoder(mContext);
try {
List<Address> list = gc.getFromLocation(latitude, longitude, 1);
if(list.size()>0){
String city = list.get(0).getLocality();
String street = list.get(0).getAddressLine(0);
placeName = city+", "+street+"";
}
} catch (IOException e) {
placeName = "";
e.printStackTrace();
}
return placeName;
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// no network provider is enabled
this.canGetLocation = false;
return null;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,0, this);
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,0, 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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(MapCurrentPlace.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;
}
public boolean getIsNetworkEnabled() {
return this.isNetworkEnabled;
}
/**
* 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 OFF");
// Setting Dialog Message
alertDialog.setMessage("Allow GPS");
// On pressing Settings button
alertDialog.setPositiveButton("SETTING", 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 intent) {
// TODO Auto-generated method stub
return null;
}
}
locationManager.getLastKnownLocation
this one returns last know location fix. This might be kind of old if no apps requested location for a while.
Location updates will be fired each time device location was changed.
So it's up to you what to use. If you want to get up-to date location, use location updates. But bear in mind that location updated drain battery.
Also you might want to look into Geofences: http://developer.android.com/training/location/geofencing.html
The onLocationChanged method will be called when the current location is changed. This is a default method called because you have implemented the LocationListener.
I do not know how you are implementing the timer (perhaps an AsyncTask so your app can do other stuff as well - http://developer.android.com/reference/android/os/AsyncTask.html), but then in the OnLocationChanged method add some call to your timer variable to stop.
OnLocationChanged will trigger whenever the device travels the minDistance parameter of requestLocationUpdates, from the last relevant location of your device (i.e. since the event last triggered).
Of course, the trigger rate also takes into account the minTime parameter, which should be used to prevent saturation of the calls, and thus saving battery/data usage (e.g. car travelling too fast for your minDistance).
As you have it now (you supplied an inline 0 to the call), you need to manually check if the most recent OnLocationChanged data is a relevant change to your scenario.
It's much more transparent to just use that parameter as the system tries to make it hardware-independent and battery-efficient. You already have a MIN_DISTANCE_CHANGE_FOR_UPDATES in your boilerplate code, just add it as a parameter instead of '0' as you have, and set it to the number of meters you need:
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 30; //30 meters
//...
//at some point while your service/activity is running
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,
this);
//...
#Override
public void onLocationChanged(Location currentLocation) {
//triggered when System asserts a 30 meter variation from last relevant location
doMyStuff();
}
Side note: remember most GPS hardware has issues with very fine locations, especially at sub-10m.
You can also keep the value at 0, receive updates at the granularity the hardware updates itself, and do the checks manually - just use the Location parameter supplied with the event and do your own checks to decide, which is pretty much a geo-fencing check:
Location lastRelevantLocation;
#Override
public void onLocationChanged(Location currentLocation) {
// called when the listener is notified with a location update from the GPS
// hardware update rate might call this more than your CPU should handle
if(checkOutsidePerimeter(location)){
lastRelevantLocation = currentLocation;
doMyStuff();
}
}
Remember minTime if you want to keep tabs on granularity.
Related
My scenario is to get lat and long of the mobile device for every 20sec and put the lat,long values in database using asmx web service.I have written a service which implements location listener and able to get the lat long values from the service
The implementation of the service is as below.My GpsTracker Service.
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 *20* 1; //5 seconds
// 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);
}
}
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
}
#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;
}
}
And in my activity I have two buttons upon click of the button this service should be started.But now I am having the following problems
1)If the phone goes to sleep mode the lat,long values are not fetched by the service.
2)How to return the lat,long values to the activity so that I can call a web service which puts the lat,long values in database(a different app picks these values from here)
3)The LocationManager.requestlocationupdates function gives lat long values in irregular intervals than what is specified in the arguments
I have seen people using AlarmManager,but i don't get the proper usage as LocationManager.requestlocationupdates provides the same functionality.Connecting to asmx part is pretty clear and I am using ksoap jar file for that.Is there any other which is better than that.
I have also tried using CWAC LocationPoller which is an awesome thing,but as Commonware suggested in previous posts that LocationPoller is designed for much longer polling periods: an hour, not 10 seconds.I have dropped on proceeding that idea.
This is my first Service that I have seen and I am complete newbie to android world who has delved into it 3 days ago.Please Help!!.Expecting your valuable suggestions
Thanks in Advance..
I am doing application, we are in inside the room or not. I have to stored 4 corner values means doing polygon. But i cant get exactly value in the same position, it gets different values in the same position. How it get solution this problem??
Code:
MainActivity.java
public class MainActivity extends Activity {
Button btnShowLocation;
TextView tvLat;
TextView tvLang;
TextView tvInsideRoom;
dbHandler myDbHelper;
// GPSTracker class
GPSTracker gps;
Handler mHandler1;
tvInsideRoom = (TextView)findViewById(R.id.insideRoom);
btnShow = (Button) findViewById(R.id.btnShow);
// show location button click event
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mHandler1 = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(100);
mHandler1.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// creating GPS Class object
GPSTracker gps = new GPSTracker (MainActivity.this);
// check if GPS location have some values
if (gps.canGetLocation()) {
double currentlat = gps.getLatitude();
double currentlong = gps.getLongitude();
tvLat = (TextView)findViewById(R.id.lat);
tvLang = (TextView)findViewById(R.id.lang);
tvLat.setText(""+currentlat);
tvLang.setText(""+currentlong);
boolean boolFlag = myDbHelper.isInsideRoom(currentlat,currentlong);
tvInsideRoom.setText("");
if(boolFlag)
tvInsideRoom.setText("You are in inside Room");
else
tvInsideRoom.setText(""+boolFlag);
} else {
// no current location
gps.showSettingsAlert();
}
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
}); }
GPSTracker.java
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 = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 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) {
Log.d("Accuracy1 := ", ""+location.getAccuracy());
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) {
Log.d("Accuracy2 := ", ""+location.getAccuracy());
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 is settings");
// 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) {
this.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;
}}
The accuracy of location tracking can vary vastly. What you are trying to achieve will never work because of an insufficient accuracy. Especially inside a room, but even with GPS.
Depending on where you are, network cell-towers, wifi or GPS will be used to determine the current location, and all with a different accuracy. Even outside, it usually takes a few seconds until you get a GPS fix.
Use getAccuracy() to check if your location is somewhat useful with the current fix.
I make a tutorial of GPS that you can get the location pressing a button, but now I want to make this process automatically, I try calling it on the onCreate method but only works once.... any Idea how? this is what i try:
GPS CLASS
public class GPS implements LocationListener{
private final Context mContext;
//flag for GPS status
boolean isGPSEnable = false;
// Flag for network status
boolean isNetworkEnable = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; //location
double latitude; //latitude
double longitude; //longitude
// the minimum distances to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // Minimun distance 10 meters
// The minimum time between updates in millisenconds
private static final long MIN_TIME_BTW_UPDATES = 1000 * 60 * 1; // 1 MINUTE
// Declaring a Location Manager
protected LocationManager locationManager;
public GPS(Context context){
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
//getting GPS status
isGPSEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnable = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnable && !isNetworkEnable){
// no network provider is enable
}
else {
this.canGetLocation = true;
if(isNetworkEnable){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BTW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) 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 Enable get lat/long using GPS Services
if(isGPSEnable){
if(location == null){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BTW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS ENABLE", "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((LocationListener) GPS.this);
}
}
/**
* function to get latitude
*/
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
//return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
//return longitude
return longitude;
}
/**
* Function to check GPS/wifi enable
* #return boolean
*/
public boolean canGetLocation(){
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
*/
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(mContext.getString(R.string.AlertDialog_Tittle));
// Setting Dialog Message
alertDialog.setMessage(mContext.getString(R.string.dialog_message));
// On pressing Setting button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
}
});
// On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
#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;
}
}
and the main-activity class:
public class MainActivity extends ActionBarActivity {
private EditText edTLatitud;
private EditText edTLongitud;
private EditText edTCompass;
private EditText edTDirecc;
private SensorManager sensorManager;
private Sensor compassSensor;
// GPS class
GPS gps;
// Compass class
Compass compass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpsactivity);
edTCompass = (EditText)this.findViewById(R.id.edTxtBrujula);
edTDirecc = (EditText)this.findViewById(R.id.edTxtBrujdireccion);
edTLatitud = (EditText)this.findViewById(R.id.edTxtLatitud);
edTLongitud = (EditText)this.findViewById(R.id.edTxtLongitud);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
gps = new GPS(MainActivity.this);
// Check if GPS is enable
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Print on the screen the coordinates
UpdateGPSonScreen(latitude, longitude);
}
else {
// can't get location
// GPS or network is not enable
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
// Show the Latitude and longitude of the GPS on the application
public void UpdateGPSonScreen(double latitude, double longitude)
{
try{
edTLatitud.setText(String.valueOf(latitude));
edTLongitud.setText(String.valueOf(longitude));
}
catch (Exception e)
{
e.printStackTrace();
}
}
thanks in advance...
Do you want the EditText to be updated with the user location information intermittently? If so, you could create a thread that on intervals calls a function that retrieves the location data.
If the GPS class is not used anywhere else except in MainActivity make it as inner class of your Activity or Implement LocationListener in your Activity class itself to update your TextViews inside onLocationChanged method.
Put locationManger null check before you use it anywhere, there is no sense an to check for null after using it multiple times.
Your Class structure should be like
public class MainActivity extends ActionBarActivity{
// Define your text views to use them globally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpsactivity);
//find all your views
}
class GPS implements LocationListener{
//copy all your code here with required correction
#Override
public void onLocationChanged(Location location){
//get your latitude and longitude from location Object
// call same method to update your view
}
}
}
I have written whole code in stackoverflow editor only so make correction if any syntax error is found.
i need to get myLocation using GPS, how to get it? I try next code, but it works not ever. When i restart my phone and run application it does not works.
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTraker 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 = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 3000; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTraker(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) {
locationManager.removeUpdates(GPSTraker.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 is settings");
// 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;
}
}
and using it:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_near_new, null);
elvMain = (ExpandableListView) v.findViewById(R.id.elvMain);
GPSTraker gps = new GPSTraker(getActivity());
if (gps.canGetLocation()) {
myLat = gps.getLatitude();
myLong = gps.getLongitude();
Log.d("myDebug", "new get Location +" + myLat);
// \n is for new line
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.d("myDebug", "Can not get location");
gps.showSettingsAlert();
}
return v;
}
What it is wrong? Maybe someone have some ideas how to solve this? After i reboot my phone this program
can not get my location too.
Do you want continuous location updates or just a single location?
By "GPS, without network" I assume that you want to get a location even when the network is not available, not that the network location should never be used.
Some basics on LocationManager:
On startup, you need to request an instance of LocationManager and then call RequestLocationUpdates(), passing as an argument the class that will receive location updates. When a new location is available, LocationManager will call onLocationChanged(), passing the current location as an argument.
Looking at your code, you have it all there, but in the wrong places:
Most of the code in your getLocation() method should go into onCreate().
The call to requestLocationUpdates() should go in your service's onStartCommand() method. You should unregister by calling removeUpdates() in your stopSelf() method so that the GPS will be released when your service is stopped. (For an Activity, do this in onResume() and onPause(), respectively. Otherwise it will keep the GPS awake and drain the battery even after the service stops/user navigates away from the activity, until the system kills the app.)
The code for handling a location update, which you have placed in onCreateView(), should go into onLocationChanged().
I see you are also calling LocationManager.getLastKnownLocation(). This will get the last location that LocationManager has previously obtained, but it will not start the GPS. If no other app has requested a location update before (using requestLocationUpdates()), it has no location to report, and if the device moved since the last position was obtained, you will get an out-of-date position.
If you need a single location update in a reliable fashion and with up-to-date information, follow the instructions above and place the call to removeUpdates() in your onLocationChanged() method. That will release the GPS after the first location update. Note that you may have to wait some time for the location update, as the GPS may take some time to start up.
every time I run my application on my Galaxy Note 10.1, I got different locations for my current location, although I've not moved a step!!
below is the GPS Class, and we use an object of it in different classes
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 = null; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
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;
/*if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, 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, this);
Log.d("GPS", "GPS is 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 settings");
// 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;
} }
And here is the Manifest
uses-permission android:name="com.fltirha.faltirha.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I need to get an accurate data and these are all the result locations I got for my current location:
21.536638661233727 , 39.23742879844281
21.536857937756533 , 39.237249447421995
21.536522367052235 , 39.237391639089886
GPS isn't 100% accurate. The distance between the first and second reading is only 30 metres, and you could easily have an error of that magnitude, especially if you're indoors.
Along with the lattitude and longitude, the GPS location provider also gives you an accuracy measure in metres. The accuracy represents 1 standard deviation of error, which means that about 2/3 of the time your true location is not more than the given number of metres away from the given location. But it also means that about 1/3 of the time your true location is further away. I think your next step should be to see whether the GPS accuracy readings are correct or not.
One approach which helps is to use a Kalman Filter on the readings from all providers. The advantage of this is that it incorporates the accuracy readings into its guess of your location, so low accuracy readings get ignored and high accuracy readings get much more weight. If you want to use a Kalman filter, I suggest starting with the code that I posted on "Smooth GPS data" last month.
It's ok, calculate distance between your points in meters and you'll see that the difference between them is less than about 50 meters. It's normal for GPS to have such accuracy, you never get exact same position even if you don't move at all.
If you want more accuracy in your results, I would suggest:
Takee your measurements outside in clear view of the sky.
Don't just take the first fix reported. In my experience, the "first fix is the worst fix" as far as accuracy goes. I would wait until receiving four or five position reports before deciding to use one.
If you need several positions, don't stop the GPS receiver! Most GPS receivers will lose data if you stop them. Things like frequency offsets, precise time, etc. All these have to be determined again. If you need a fix in 2 seconds, just keep the receiver running.
Still, you will not get the same answer every time. That's the nature of GPS. It is about accuracy, not perfection. The best you can get in open sky from most commercial handsets is about 3 to 5 meters, most of the time.