I have an app that monitors the accelerometer and the GPS and out puts them to a file.
I have defaulted the GPS to 0,0. But it doesn't seem to change.
public String location = "0 , 0";
public void onLocationChanged(Location arg0) {
arg0.getLatitude();
arg0.getLongitude();
location = arg0.getLongitude() + "," + arg0.getLatitude();
locationText = TextView.class.cast(location);
}
The text view is there to show if it is acutaully changing, but that doesn't seem to update either.
The location text view is at the top of the screen.
Im not sure what else I can include to help you help me. But if there is anything let me know.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
This is the code of the accelerometer, which works, and the GPS which doesn't.
Thanking you and a happy new year.
CODE
public class AccelOrientExample extends Activity implements SensorEventListener, LocationListener {
// Accelerometer X, Y, and Z values
private TextView accelXValue;
private TextView accelYValue;
private TextView accelZValue;
// Orientation X, Y, and Z values
private TextView orientXValue;
private TextView orientYValue;
private TextView orientZValue;
private TextView locationText;
private TextView toWrite;
public Toast myToast;
public String accel;
public int counter = 0;
public String orientData;
private LocationManager lm;
private Toast loc;
public String location = "0 , 0";
private SensorManager sensorManager = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a reference to a SensorManager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
// Capture accelerometer related view elements
accelXValue = (TextView) findViewById(R.id.accel_x_value);
accelYValue = (TextView) findViewById(R.id.accel_y_value);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
// Capture orientation related view elements
orientXValue = (TextView) findViewById(R.id.orient_x_value);
orientYValue = (TextView) findViewById(R.id.orient_y_value);
orientZValue = (TextView) findViewById(R.id.orient_z_value);
// Initialize accelerometer related view elements
accelXValue.setText("0.00");
accelYValue.setText("0.00");
accelZValue.setText("0.00");
// Initialize orientation related view elements
orientXValue.setText("0.00");
orientYValue.setText("0.00");
orientZValue.setText("0.00");
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
/**/
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
while(counter < 15)
{
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION)
{
orientXValue.setText(Float.toString(sensorEvent.values[0]));
orientYValue.setText(Float.toString(sensorEvent.values[1]));
orientZValue.setText(Float.toString(sensorEvent.values[2]));
}
MyFile file = new MyFile();
file.createFile("OrientData.txt");
orientData = sensorEvent.values[0] + "," + sensorEvent.values[1] + "," + sensorEvent.values[2] + "\n";
file.write(orientData);
counter ++;
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
accelXValue.setText(Float.toString(sensorEvent.values[0]));
accelYValue.setText(Float.toString(sensorEvent.values[1]));
accelZValue.setText(Float.toString(sensorEvent.values[2]));
accel = sensorEvent.values[0] + "," + sensorEvent.values[1] + "," + sensorEvent.values[2] + ",";
}
}
}
public void onLocationChanged(Location arg0) {
synchronized (this) {
lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
arg0.getLatitude();
arg0.getLongitude();
location = arg0.getLongitude() + "," + arg0.getLatitude();
Toast.makeText(getApplicationContext(),"Test",Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable(){
public void run() {
locationText.setText(location);
}
});
}
}
public void FileLogger(String accel, String location)
{
MyFile file = new MyFile();
file.createFile("RoadData.txt");
String toWrite = accel + location + "\n";
file.write(toWrite);
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String arg0) {
Log.e("GPS", "provider disabled " + arg0);
}
public void onProviderEnabled(String arg0) {
Log.e("GPS", "provider enabled " + arg0);
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
}
#Override
protected void onResume() {
super.onResume();
// Register this class as a listener for the accelerometer sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
// ...and the orientation sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
}
Can you try below
locationText.setText(location);
instead of
locationText = TextView.class.cast(location);
i expect locationText to be a TextView and
you requested location updates correctly and
added permission in manifest correctly and
the location update code is not getting executed by non-ui thread.
You might have the location services off, check that the provider is first available with;
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
Like #Javantor said you need to make sure that the manifest includes;
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and you are updating on the UI Thread. Try putting this in the onLocationUpdated code;
runOnUiThread(new Runnable(){
#Override
public void run() {
locationText.setText(location);
}
});
While it shouldn't make a difference, requesting the LocationManager this way;
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
with the time set to 0 instead of 1000ms ensures you get the updates as fast as they can come in.
Can you add some logging to the onLocationChanged method? That will let you know if the GPS data is being received at all.
Try launching Google Maps first and let it pinpoint your current location. Sometimes Location returns null because recent location list has been cleared. Also try this method to iterate over the currently enabled providers, not just the best one. This gives you a slightly higher chance or getting some coordinates returned. Hope this helps man. Good luck
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Related
In the code shown below, I can get the count of visible satellites in Android 7.0 and higher API using GnssStatus.callback. But I can't get the related SNR for each detected satelitte because GnssStatus.callback as no supported function.
I checked this link and found that we should use GnssMeasurement callback and call (getsnrindb()) as here.
How I can use (GnssMeasurement callback) to get SNR values ?
my code:
tv1 = (TextView) findViewById(R.id.Gps_location);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mGnssStatusCallback = new GnssStatus.Callback() {
// TODO: add your code here!
#Override
public void onSatelliteStatusChanged(GnssStatus status) {
satelliteCount = status.getSatelliteCount();
sat_id = status.getSvid(1);
constellationType = status.getConstellationType(1);
v = " Scan: "+ (count)+ " ,Sat-count=" +(satelliteCount) +"id="+ sat_id +" type"+ constellationType + " ,Eacc= "+accuracy+ "\n\n";
v += tv1.getText();
tv1.setText(v);
count= count + 1;
}
};
#Override
protected void onStart() {
super.onStart();
mLocationManager.registerGnssStatusCallback(mGnssStatusCallback);
mLocationManager.registerGnssMeasurementsCallback(mGnssMeasurmentscallbak);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
}
#Override
protected void onStop() {
mLocationManager.removeUpdates(this);
mLocationManager.unregisterGnssStatusCallback(
mGnssStatusCallback
);
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
}
}
}
Calculates the GPS signal strength, using GnssStatus.Callback() through getSatelliteCount(), which gives us the number of satellites that are within our reach, and each of them has a signal-to-noise ratio (getCn0DbHz(i)).
// Android N (7.0) and above status and listeners
private GnssStatus.Callback mGnssStatusCallback ;
mGnssStatusCallback = new GnssStatus.Callback() {
#Override
public void onSatelliteStatusChanged(GnssStatus status) {
int satelliteCount = status.getSatelliteCount();
int usedSatellites = 0;
float totalSnr = 0;
for (int i = 0; i < satelliteCount; i++){
if (status.usedInFix(i)) {
usedSatellites++;
totalSnr += status.getCn0DbHz(i); //this method obtains the signal from each satellite
}
}
// we calculate the average of the power of the GPS signal
float avgSnr = (usedSatellites > 0) ? totalSnr / usedSatellites: 0.0f;
Log.d(TAG, "Number used satelites: " + usedSatellites + " SNR: " + totalSnr+"avg SNR: "+avgSnr);
}
};
try {
mLocationManager.registerGnssStatusCallback(mGnssStatusCallback);
} catch (SecurityException e) {
Log.e(TAG,"Error "+e);
}
hi there can anybody give me a sample code for get location for every five minutes please i have tried and i can get location once by cliking on button,
but i need it to be displayed once for five minutes.
thank you
this is my code :
public void checkLocation(View v) {
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS is disabled.", Toast.LENGTH_SHORT).show();
} else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 15000, 1, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
Here is the code for getting location and set the listener for gps to get current location on few minute and distance, also I have used runnable object to get the location on every few minutes.
Location gpslocation = null;
private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
private static final int GPS_DISTANCE= 1000; // set the distance value in meter
/*
for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
*/
private void obtainLocation(){
if(locMan==null)
locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(isLocationListener){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
}
}
}
}
Now use this method to get the current location and the listener was called on location change with every 1 min and 1000 meter of distance.
For getting every 5 min you can use this handler and runnable to get this location on well set period time:
private static final int HANDLER_DELAY = 1000*60*5;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
myLocation = obtainLocation();
handler.postDelayed(this, HANDLER_DELAY);
}
}, START_HANDLER_DELAY);
Here is GPS listener for location change event:
private LocationListener GPSListener = new LocationListener(){
public void onLocationChanged(Location location) {
// update location
locMan.removeUpdates(GPSListener); // remove this listener
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
You can set interval time for listener and handler same for getting GPS location.
Hi Use the below timer code.
You can use the below options
option 1
this will get the locations if mobile moved 100meters.
captureFrequencey=3*60*1000;
LocationMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, captureFrequencey, 100, this);
have a look at this link http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29
Option 2
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
Timer will call the handler for your time duration (change 1000 into your required time ).
Hope this will help you.
I used runnable for doing this,
final Runnable r = new Runnable() {
public void run() {
//Here add your code location listener call
handler.postDelayed(this, 300000 );
}
};
handler.postDelayed(r, 300000 );
try like this:
private Handler handler = new Handler();
handler.postDelayed(runnable, 300000);
private Runnable runnable = new Runnable() {
public void run() {
if (location != null) {
onLocationChanged(location);
} else {
System.out.println("Location not avilable");
}
handler.postDelayed(this, 300000);
}
};
Hey While I am running the application it gives a error java.lang.IllegalArgumentException: listener==null , that tells that listener is null.
My sample code is here:
public class HelloAndroidGpsActivity extends Activity {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}
/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("mobile location manager is ="+locManager);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
locListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
System.out.println("mobile location is in listener1");
}
#Override
public void onProviderEnabled(String provider) {
System.out.println("mobile location is in listener2");
}
#Override
public void onProviderDisabled(String provider) {
System.out.println("mobile location is in listener3");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
System.out.println("after setting listener");
}
private void buttonGetLocationClick() {
getCurrentLocation();
System.out.println("mobile location is ="+mobileLocation);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n"
+ altitiude + "\n" + accuracy + "\n" + time);
} else {
editTextShowLocation.setText("Sorry, location is not determined");
}
}
}
Output in textbox is "Sorry, location is not determined""
If any one can tell me what is the problem then please help me.
Thank you
Initialize the listener before you use it.
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
At this point of time, locListener is null, and you are initializing it after this line of code. This may be the reason.
So rearrange the lines of your code like this;
locListener = new LocationListener() {...};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Hope this may help to solve your issue...
hi i am doing a application based on gps,i use gps as service for my project ,when gps is turn on it show the location correctly and application runs fine ,but after that i exit from my app completely and when the gps turned off the it shows crash message.which mean even if l leave or exit my app the service class is still running ,and also app get crash if i turn off gps when app is running ,but if i did not turn of gps it work fine.Now how can i solve this problem. i will show my service class used for gps
public class Gps_Service extends Service {
TextView txtv;
List<Address> myList;
String addressStr;
LocationManager lm;
LocationListener ll;
SQLiteDatabase DiaryDB = null;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("########### serviceOnCreate");
// Toast.makeText(this, "GPS Service started(Diary)", Toast.LENGTH_LONG).show();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
#Override
public void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "GPS Service Destroyed(Diary)", Toast.LENGTH_LONG).show();
lm.removeUpdates(ll);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
// Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private class mylocationlistener implements LocationListener
{
public void onLocationChanged(Location location)
{
if (location != null) {
Geocoder myLocation = new Geocoder(Gps_Service.this, Locale.getDefault());
// Toast.makeText(MyService.this,location.getLatitude() + " " + location.getLongitude() +"\n",Toast.LENGTH_LONG).show();
// DiaryDB = MyService.this.openOrCreateDatabase("DIARY_DATABASE", MODE_PRIVATE, null);
// DiaryDB.execSQL("INSERT INTO Locations(LATITUDE, LONGITUDE) VALUES('" +location.getLatitude()+"','"+location.getLongitude()+"')");
// DiaryDB.close();
// ParseTweetsActivity.latitude = ""+location.getLatitude();
//ParseTweetsActivity.longitude = ""+location.getLongitude();
AndroidGoogleMapsActivity.lats = Double.parseDouble(""+location.getLatitude());
AndroidGoogleMapsActivity.longt = Double.parseDouble(""+location.getLongitude());
Advertiser_get_direction.latitudefrom = Double.parseDouble(""+location.getLongitude());
Advertiser_get_direction.longtitudefrom = Double.parseDouble(""+location.getLongitude());
AndroidGoogleMapsActivity.longt = Double.parseDouble(""+location.getLongitude());
System.out.println("saaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+AndroidGoogleMapsActivity.lats);
// ParseTweetsActivity.load();
try
{
myList = myLocation.getFromLocation(location.getLatitude(),location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if(myList!=null)
{
Address address = (Address) myList.get(0);
addressStr = "";
addressStr += address.getAddressLine(0) + "\n";
addressStr += address.getAddressLine(1) + "\n";
addressStr += "Country name "+address.getCountryName() + "\n";
addressStr += "Locality "+address.getLocality() + "\n";
addressStr += "Country code "+address.getCountryCode() + "\n";
addressStr += "Admin Area "+address.getAdminArea() + "\n";
addressStr += "SubAdmin Area "+address.getSubAdminArea() + "\n";
addressStr += "PostalCode "+address.getPostalCode() + "\n";
// txtv.append(location.getLatitude() + " " + location.getLongitude() +"\n");
// txtv.append(addressStr+"\n");
System.out.println(location.getLatitude() + " " + location.getLongitude() +"\n");
lm.removeUpdates(ll);
}
}
}
public void onProviderDisabled(String provider)
{
// Toast.makeText(MyService.this,"Provider Disabled",Toast.LENGTH_LONG).show();
txtv.setText("");
}
public void onProviderEnabled(String provider)
{
// Toast.makeText(MyService.this,"Provider Enabled.....",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
You have declared a TextView within your Service. That's not good. TextView is a UI component and doesn't belong on the service.
In your onProviderDisabled() method, you call txtv.setText(""); which will probably crash because txtv is null. This is probably why your app is crashing when you disable GPS.
Change your code from
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
to following
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new mylocationlistener();
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0,ll);
}
I had a problem like this when i didn`t release listener in the onDestroy().
Try to add the following code:
lm.unregisterListener(ll);
I am trying to get my current position of my phone via GPS in my program.
The Problem is, that either the coordinates are to inaccurate (only degrees) or no location is given. I programmed my third program now and each of them with a different tutorial, but it did not work as it should work there.
uses-permission are set, so that is not the answer ;)
So here is my code:
public class GpsActivity extends Activity{
private TextView latituteField;
private TextView longitudeField;
private TextView dateField;
private TextView timeField;
private LocationManager locationManager;
private String provider;
private LocationListener listener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
dateField = (TextView) findViewById(R.id.tvdate);
timeField = (TextView) findViewById(R.id.tvtime);
GregorianCalendar g = new GregorianCalendar();
g.setTimeInMillis(System.currentTimeMillis());
DateFormat df = DateFormat.getInstance();
Date d = df.getCalendar().getTime();
dateField.setText(""+d.getDate()+"."+(d.getMonth()+1)+"."+(1980+d.getYear()));
timeField.setText(""+g.getTime().getHours()+"h "+g.getTime().getMinutes()+"m "+g.getTime().getSeconds()+"s");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(""+lat+"//"+location.getAccuracy());
longitudeField.setText(""+lng+"//"+location.getProvider());
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
listener = new MyLocationListener();
locationManager.requestLocationUpdates("gps" ,10000L, 10.0f, listener);
}
class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
latituteField.setText(("Lat: " + location.getLatitude()));
longitudeField.setText("LLong: " + location.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Thanks for answering!
Rene
You are probably getting just a weak signal. You may use the android location API to get an approximate location.
Make sure that you stand outside and have a free view to the sky for getting a "good" signal. Don't stand next to buildings, etc. However even if you do that you won't get an accurate signal. Phone GPSs' are optimized for energy saving and not for accuracy. They won't put a too expensive chip on your phone as well...