How to switch from Gps to network provider? - android

Need some help. I am making an app where i get location updates from either gps or network provider. If gps is not enabled then i gave the button to enable the gps. Now what i need to do is to take updates from gps, if the gps can't get a signal then i switch over to network provider and take location updates and as soon as gps is available the switch to gps again and calculate the distance the user has travelled. I got multiple questions.
What does the getProvider and getBestProvider methods do? I think it provides the best provider that is available to the phone (correct me if i am wrong) and how can i use it to get location updates.
I need to know what providers are enabled when the user launches the app. How can i do that? I used isProviderEnabled but got confused when enabling or disabling the wifi it gives me nothing.
I tried some conditions if gps not enabled then switch to network provider but this doesn't do anything. I read many posts regarding this but couldn't figure out how to use it in my code. Any help would be greatly appreciated. Thanks. Here is my code.
public class MainActivity extends Activity {
public boolean getLocation() {
try {
isGps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
isNetwork_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!isGps_enabled && !isNetwork_enabled)
return false;
if (isGps_enabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
if (isNetwork_enabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accu = (TextView) findViewById(R.id.accu);
speed1 = (TextView)findViewById(R.id.speed);
t = (TextView)findViewById(R.id.t);
prevLatLon = (TextView) findViewById(R.id.prevLatLon);
distance = (TextView)findViewById(R.id.distance);
listView = (ListView)findViewById(R.id.listView);
listText = (TextView)findViewById(R.id.listText);
settings = (Button)findViewById(R.id.settings_button);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
List<String> providers = locationManager.getProviders(criteria, true);
for (String provider: providers){
distance.setText("Providers: " + provider);
}
provider = locationManager.getBestProvider(criteria, false);
/*isGps_enabled = locationManager.isProviderEnabled(provider);
Toast.makeText(this, isGps_enabled + "", Toast.LENGTH_SHORT).show();
isNetwork_enabled = locationManager.isProviderEnabled(provider);
Toast.makeText(this, isNetwork_enabled + "", Toast.LENGTH_SHORT).show();*/
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location loc) {
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
getLocation();
int accuracy = (int) loc.getAccuracy();
speed = (int) loc.getSpeed();
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + loc.getTime());
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(loc.getTime());
String formatted = format.format(date);
if (flag == 0) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
distanceInMeters = 0;
distanceTo = 0;
distanceBetween = 0;
timestamp = loc.getTime();
timestampmsec = 0;
hours = 0;
minutes = 0;
seconds = 0;
startTime = loc.getTime();
flag = 1;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time + "\nDistance: " + distanceInMeters + " meters"
+ "\ntimestamp: " + timestamp);
}
else {
prevLatitude = latitude;
prevLongitude = longitude;
prevSpeed = speed;
prevTime = time;
prevDistanceInMeters = distanceInMeters;
prevDistanceTo = distanceTo;
prevDistanceBetween = distanceBetween;
//prevTimestamp = timestamp;
prevTimestampmsec = timestampmsec;
prevHours = hours;
prevMinutes = minutes;
prevSeconds = seconds;
prevLatLon.setText("Previous Latitude: " + prevLatitude + "\nPrevious Longitude: " + prevLongitude +
" \nPrevious speed: " + prevSpeed + " \nTime: " + prevTime + "\nPrevious Timestamp: " + prevTimestamp);
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
timestamp = loc.getTime();
if (loc.hasSpeed()) {
Toast.makeText(MainActivity.this, "true", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "false", Toast.LENGTH_SHORT).show();
}
getDistance();
distanceTo = androidDistanceTo(prevLatitude, prevLongitude, latitude, longitude);
Location.distanceBetween(prevLatitude, prevLongitude, latitude, longitude, results);
distanceBetween = results[0];
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time + "\nDistance: " + distanceInMeters + " meters"
+ "\nTimestamp: " + timestamp);
speed = prevSpeed + speed;
distanceInMeters = prevDistanceInMeters + distanceInMeters;
distanceTo = prevDistanceTo + distanceTo;
distanceBetween = prevDistanceBetween + distanceBetween;
timestampmsec = (long) (timestamp - startTime);
seconds = TimeUnit.MILLISECONDS.toSeconds(timestampmsec);
if(seconds >= 60) {
minutes = (int) seconds / 60;
seconds = seconds % 60;
}
if(minutes >= 60){
hours = (int) minutes / 60;
minutes = minutes % 60;
}
}
distance.setText("Distance: " + distanceInMeters + " meters" + "\nDistanceTo: " + distanceTo + " meters" +
"\nDistanceBetween: " + distanceBetween + " meters" + "\nTime: " + hours + " hours " +
minutes + " minutes " + seconds + " seconds");
Toast.makeText(MainActivity.this, "Location Changed", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String arg0) {
//TODO auto generated method stub
Toast.makeText(MainActivity.this, provider + " disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
//TODO auto generated method stub
Toast.makeText(MainActivity.this, provider + " enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
//TODO auto generated method stub
}
};
}
public void getDistance(){
double dLat = Math.toRadians(latitude - prevLatitude);
double dLon = Math.toRadians(longitude - prevLongitude);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(prevLatitude))
* Math.cos(Math.toRadians(latitude)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
distanceInMeters = (6372800 * c);
}
public static double androidDistanceTo(double lat_a, double lng_a, double lat_b, double lng_b) {
Location locationA = new Location("Point A");
locationA.setLatitude(lat_a);
locationA.setLongitude(lng_a);
Location locationB = new Location("Point B");
locationB.setLatitude(lat_b);
locationB.setLongitude(lng_b);
return (locationA.distanceTo(locationB));
}
public void resetButton(View view) {
list.clear();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 30000, 0, locationListener);
}
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(locationListener);
}

getBestProvider does the following:
Returns the name of the provider that best meets the given criteria.
Only providers that are permitted to be accessed by the calling
activity will be returned. If several providers meet the criteria, the
one with the best accuracy is returned. If no provider meets the
criteria, the criteria are loosened in the following sequence: power requirement, accuracy, bearing, speed, altitude
getProvider does the following:
Returns the information associated with the location provider of the
given name, or null if no provider exists by that name.
In layman's terms you choose the provider with getProvider and the system chooses the provider with getBestProvider
You can find out what providers are enabled by looking at isProviderEnabled
Your code for starting the listeners looks fine. But you don't actually call getLocation() anywhere other than onResume() and onLocationChanged() You need to move that call out of onLocationChanged() and put it towards the end of onCreate()

Related

How to get GPS Distance travelled in Android with this code?

I am totally new to Android and I am stuck with a problem.
Basically what I want is when I move, my app get GPS info and display on my phone including the distance that I travelled in meter. But I don't know how to do that in Android.
This is my code.
public class MainActivity extends AppCompatActivity {
TextView tv;
TextView tv2;
ToggleButton tb;
Button currentGPS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Location location11 = null;
double Longitude1 = 0;//location11.getLongitude();
double Latitude1 = 0;//location11.getLatitude();
tv = (TextView) findViewById(R.id.textView2);
tv.setText("Ready");
tb = (ToggleButton)findViewById(R.id.toggle1);
final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
tb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(tb.isChecked()){
tv.setText("connecting..");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
100,
1,
mLocationListener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
100,
1,
mLocationListener);
}else{
tv.setText("Information not connecting");
lm.removeUpdates(mLocationListener);
}
}catch(SecurityException ex){
}
}
});
}
private final LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location1) {
Log.d("test", "onLocationChanged, location:" + location1);
double longitude = location1.getLongitude();
double latitude = location1.getLatitude();
double altitude = location1.getAltitude();
float accuracy = location1.getAccuracy();
String provider = location1.getProvider();
final double latitudeA = location1.getLatitude();
final double longitudeA = location1.getLongitude();
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latitudeA);
locationA.setLongitude(longitudeA);
Location locationB = new Location("point B");
locationB.setLatitude(latitude);
locationB.setLongitude(longitude);
distance = locationA.distanceTo(locationB);
float currentSpeed = (location1.getSpeed()*3600/1000);
String convertedSpeed = String.format("%.2f",currentSpeed);
tv.setText("Provider : " + provider + "\n\nlatitude : " + longitude + "\n\nlangitude : " + latitude
+ "\n\naltitude : " + altitude + "\n\naccuracy : " + accuracy +"/\n\nMoving distance : " + distance + "/m"
+ "\n\nCurrent speed : " + convertedSpeed + "Km/h");
}
public void onProviderDisabled(String provider) {
Log.d("test", "onProviderDisabled, provider:" + provider);
}
public void onProviderEnabled(String provider) {
Log.d("test", "onProviderEnabled, provider:" + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("test", "onStatusChanged, provider:" + provider + ", status:" + status + " ,Bundle:" + extras);
}
};
}

saving the state of activity when the layout changes

i need to save my all variables and text views to display all values when i change my layout to landscape. can anybody help me out? i tried to save somethings in the onsavedInstanceState method but it won't save anything. here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accu = (TextView) findViewById(R.id.accu);
speed1 = (TextView)findViewById(R.id.speed);
t = (TextView)findViewById(R.id.t);
prevLatLon = (TextView) findViewById(R.id.prevLatLon);
listView = (ListView)findViewById(R.id.listView);
listText = (TextView)findViewById(R.id.listText);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
accuracy = (int) loc.getAccuracy();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + time);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(loc.getTime());
String formatted = format.format(date);
if(flag == 0){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
flag = 1;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " +time);
}
else {
prevLatitude = latitude;
prevLongitude = longitude;
prevSpeed = speed;
prevTime = time;
prevLatLon.setText("Previous Latitude: " + latitude + "\nPrevious Longitude: " + longitude +
" \nPrevious speed: " + speed + " \nTime: " + time);
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time);
speed = prevSpeed + speed;
}
/*currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
currentLat = currentLocation.getLatitude();
currentLon = currentLocation.getLongitude();*/
//list.add("speed: " + speed + " accuracy: " + accuracy);
Toast.makeText(MainActivity.this, "Location Changed", Toast.LENGTH_SHORT).show();
}
i tried this
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + time);
prevLatLon.setText("Previous Latitude: " + latitude + "\nPrevious Longitude: " + longitude +
" \nPrevious speed: " + speed + " \nTime: " + time);
savedInstanceState.putDouble("latitude", latitude);
savedInstanceState.putDouble("longitude", longitude);
savedInstanceState.putDouble("prevLatitude", prevLatitude);
savedInstanceState.putDouble("prevLongitude", prevLongitude);
savedInstanceState.putDouble("speed", speed);
savedInstanceState.putDouble("accuracy", accuracy);
// etc.
}
When you save something using the onSaveInstanceState you are supposed to retrieve them later on either on the onRestoreInstanceState or using the onCreate(Bundle).
On the onCreate of your activity do this code:
onCreate(Bundle bundle)
{
/* ... */
if (bundle == null)
{
//Initialize data
data = 0;
} else
{
//Load data from the bundle (the same way you saved them)
data = bundle.getInt("MY_DATA", 0); //0 is default value
}
}
Alternatively you can use the onRestoreInstanceState(Bundle) method which guarantees that bundle will always be non-null. I'm not sure which of the two is better for which case, but both work.

How to get location update for every half an hour android?

hi i have developed an android application for getting location and sending it to server it is working good but location update is not working it is currently running once i have to get location and send to server once in half an hour, and this process should run only for 9 hrs to 17 hrs how can i do it pls help me..!
my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
TextView tv1 = (TextView) findViewById(R.id.locationResults);
if (loc != null) {
tv1.setText("Cell ID: " + loc.getCid() + " , "
+ "Lac: " + loc.getLac() + "mcc : " + mcc
+ "mnc : " + mnc);
}
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
}
else {
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");
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
String imei = telephonyManager.getDeviceId();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
String cdt = sdf.format(new Date());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String lat = Double.toString(latitude);
String lon = Double.toString(longitude);
String locations = Double.toString(latitude) + ","
+ Double.toString(longitude);
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
else {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
// TextView tv1 = (TextView)
// findViewById(R.id.locationResults);
if (loc != null) {
tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 10, 1,
this);
}
}
}
// 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;
}
#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 gps NETWORK ID : ");
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
You can use requestLocationUpdates of LocationManager Class
requestLocationUpdates (long minTime, float minDistance, Criteria
criteria, PendingIntent intent)
So, the first param you can specify as 30 mins according to your requirement.
To keep track of hours elapsed, you can have something like :
var1 = System.CurrentTimeMillis(); //Get time when service started
In onLocationChanged()
var2 = System.CurrentTimeMillis();
Now calculate var2-var1 to get elapsed time. if >17 hrs, removeUpdates from locationManager
I have a similar project going on, I am using a Service for this, fired by an AlarmManager.
Check here for more info.
The approach provided by Schaemelhout and the approach taken by library referred to in the comments is the only workable solution I have found.
Using an AlarmManager to wake your service guarantees the service is periodically invoked/restarted. This serves to counteract any power saving actions that the OS/phone might hit your service with in the mean time.
Registering a location listener from your alarm BroadcastReceiver wakes up the GPS (the GPS would not normally be running if the phone is asleep). In your alarm BroadcastReceiver you will need to take and hold a WakeLock and stay awake until results are passed back to the listener.
The down side to this approach is that it takes a while for a location to be available and the accuracy may be bad. Your service might have to wait a while until acceptable accuracy is achieved (the Location accuracy value can be wrong, so it might be be best to wait for a few samples). The whole approach will need to be tuned to your required update frequency and accuracy requirements. If you need very frequent and accurate updates I suspect holding a wake-lock and keeping the GPS alive might be the only way to go.
I also tried using the lm.requestLocationUpdates() using a PendingIntent. This did faithfully wake up my service and pass it an Intent, but if the GPS was sleeping prior to the wake up the Intent lacked a location.

android gps lagging

i got this gps reciever method, which store's some data into a database.
// GPS
private void addGPSListener() {
globalconstant.db.setVersion(1);
globalconstant.db.setLocale(Locale.getDefault());
globalconstant.db.setLockingEnabled(true);
final String gps =
"CREATE TABLE IF NOT EXISTS GPS_Values ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Accuracy INTEGER,Speed INTEGER,City TEXT,timestamp TIMESTAMP);";
globalconstant.db.execSQL(gps);
float f = Float.valueOf(globalconstant.gps_update_value.trim())
.floatValue();
Log.d("FESTIVALE :: ", "Frissítési idő: "
+ f);
float update = f;
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocListener = new MyLocationListener();
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 0,
globalconstant.mlocListener);
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
float szel = (float) loc.getLatitude();
float hossz = (float) loc.getLongitude();
int horiAcc = (int) (loc.getAccuracy());
// int speed=(int) ((loc.getSpeed()*3600)/1000); //sebesség km/h-ban
int speed = 0;
if (loc.hasSpeed()) {
speed = (int) ((loc.getSpeed() * 3600) / 1000); // sebesség
// km/h-ban
} else {
speed = 0;
}
String test = String.format("%.08f", szel);
String test2 = String.format("%.08f", hossz);
Geocoder geocoder = new Geocoder(main.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(szel, hossz,
1);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues gps_values = new ContentValues();
gps_values.put("Latitude", test);
gps_values.put("Longitude", test2);
gps_values.put("Accuracy", horiAcc);
gps_values.put("Speed", speed);
gps_values.put("City", city);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
gps_values.put("timestamp", dateFormat.format(date));
try {
globalconstant.db.beginTransaction();
globalconstant.db.insert("GPS_Values", null, gps_values);
globalconstant.db.setTransactionSuccessful();
} finally {
globalconstant.db.endTransaction();
}
Log.d("FESTIVALE :: ", "Hely " + test + ", " + test2 + " , "
+ horiAcc + " , " + speed + " , " + city + "," + dateFormat.format(date));
// String Text = "My current location is: " + "Latitude = "
// + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();
// Toast.makeText(getApplicationContext(), "Hely" +test + "\n" +
// test2 + "\n" + horiAcc + "\n" +speed + "\n" +city,
// Toast.LENGTH_SHORT)
// .show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// show gps otions
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.cancel();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(main.this);
builder.setMessage("A GPS nincs aktiválva!\nAktiválja most?")
.setPositiveButton("Aktivál", dialogClickListener)
.setNegativeButton("Nem", dialogClickListener).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}// gps vége
the avarege update time is 1 sec. But my phone get's lagging (galaxy s2)i can see it because there's a chronometer.
Does anyone have any idea about why?
i think i got the solution:
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 0,
globalconstant.mlocListener);
after the 'update' it stands a '0'. and heres what i found:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
that means the min Distance was '0' so this is why it was so 'laggy'.
But thank you for anyone!
GPS is VERY processor intensive. It does not surprise me that your phone slows. This is not unusual.
In fact, if you leave the GPS on long enough your phone will get hot and the battery will drain very rapidly!

Android gps starts when gps fixed

i have this gps method:
if (globalconstant.gps) {
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocManager
.addGpsStatusListener(main.this);
Log.w("TravellerLog :: ", "22");
addGPSListener();
ProgressDialog MyDialog = ProgressDialog.show(
main.this, "Info",
" GPS kapcsolódásra vár... ", true);}
...
/* GPS kapcsolódás figyelő */
public void onGpsStatusChanged(int event) {
// Log.w("TravellerLog :: ", "l1");
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
show_sens = show_sens + "- GPS\n";
sensors.setText(show_sens);
Toast.makeText(getApplicationContext(), "GPS kapcsolódva!",
Toast.LENGTH_SHORT).show();
// Co-ordinates
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
meres = false;
start_button.setText("START");
break;
case GpsStatus.GPS_EVENT_STARTED:
break;
case GpsStatus.GPS_EVENT_STOPPED:
break;
}
}
the addGPSListener()
// GPS
private void addGPSListener() {
globalconstant.db.setVersion(1);
globalconstant.db.setLocale(Locale.getDefault());
globalconstant.db.setLockingEnabled(true);
final String gps =
"CREATE TABLE IF NOT EXISTS GPS_Values ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 8), Longitude float(10, 8),Accuracy INTEGER,Speed INTEGER,City TEXT,timestamp TIMESTAMP);";
globalconstant.db.execSQL(gps);
Log.d("FESTIVALE :: ", "Frissítési idő: "
+ globalconstant.gps_update_value);
float f = Float.valueOf(globalconstant.gps_update_value.trim())
.floatValue();
float update = f * 1000;
globalconstant.mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
globalconstant.mlocListener = new MyLocationListener();
globalconstant.mlocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, (long) update, 5f,
globalconstant.mlocListener);
// if(Global.getInstance().currentGPSLocation != null){
//
// }
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
float szel = (float) loc.getLatitude();
float hossz = (float) loc.getLongitude();
int horiAcc = (int) (loc.getAccuracy());
// int speed=(int) ((loc.getSpeed()*3600)/1000); //sebesség km/h-ban
int speed = 0;
if (loc.hasSpeed()) {
speed = (int) ((loc.getSpeed() * 3600) / 1000); // sebesség
// km/h-ban
} else {
speed = 0;
}
String test = String.format("%.08f", szel);
String test2 = String.format("%.08f", hossz);
Geocoder geocoder = new Geocoder(main.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(szel, hossz,
1);
city = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
ContentValues gps_values = new ContentValues();
gps_values.put("Latitude", test);
gps_values.put("Longitude", test2);
gps_values.put("Accuracy", horiAcc);
gps_values.put("Speed", speed);
gps_values.put("City", city);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
gps_values.put("timestamp", dateFormat.format(date));
try {
globalconstant.db.beginTransaction();
globalconstant.db.insert("GPS_Values", null, gps_values);
globalconstant.db.setTransactionSuccessful();
} finally {
globalconstant.db.endTransaction();
}
Log.d("FESTIVALE :: ",
"Hely " + test + ", " + test2 + " , " + horiAcc + " , "
+ speed + " , " + city + ","
+ dateFormat.format(date));
// String Text = "My current location is: " + "Latitude = "
// + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();
// Toast.makeText(getApplicationContext(), "Hely" +test + "\n" +
// test2 + "\n" + horiAcc + "\n" +speed + "\n" +city,
// Toast.LENGTH_SHORT)
// .show();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
//
}
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status alters */
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v(tag, "Status Changed: Out of Service");
Toast.makeText(main.this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v(tag, "Status Changed: Temporarily Unavailable");
Toast.makeText(main.this,
"Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v(tag, "Status Changed: Available");
Toast.makeText(main.this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
}// gps vége
so the question is how can i manage that the gps listener (store in the database the coordinnates...) olny starts when the gps fixed?
thanks for your answers!
You have coded properly, only you need to check certain condition, if the condition gets fulfill then just add lat-lon details to sql, do as follows,
case GpsStatus.GPS_EVENT_FIRST_FIX:
{
...
...
...
new DBThread().start();
}
break;
private class DBThread extends Thread
{
public void run()
{
// Fetch Lat-lon details here and store in sqlite
...
// Remove gps code to save in battery from drain soon
}
}

Categories

Resources