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

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);
}
};
}

Related

How to switch from Gps to network provider?

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()

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.

Unable to unregister from sensor events in Android

According to my understanding, unregisterListener() should do the trick and I should stop getting updates from the sensors. However, this is not working. I've tried moving on to the applications menu, as well as opening another application and turning the screen off. Nothing makes the updates from the sensors stop. My code is as follows: I am trying to unregister the listeners in the onPause() and unregisterSensors() function.
public class MainActivity extends Activity implements SensorEventListener,
LocationListener {
private Location location;
private int lat, lng;
private LocationManager locationManager;
private String provider;
private SensorManager senSensorManager;
private Sensor senAccelerometer;
private Sensor senGyroscope;
private Sensor senMagneticField;
private float last_x, last_y, last_z;
private float gy_x, gy_y, gy_z;
private float mag_x, mag_y, mag_z;
private Button button;
int toggle = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("MainActivity", "In the main activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
button = (Button) findViewById(R.id.btnButton1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
toggle++;
if ((senSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null
&& (location != null)) {
if (toggle % 2 == 0) {
button.setText("Stop");
registerSensors();
}
else {
unregisterSensors();
}
}
}
});
}
public void unregisterSensors() {
Log.i("MainActivity", senSensorManager.toString());
senSensorManager.unregisterListener(this);
locationManager.removeUpdates(this);
button.setText("Start");
Log.i("MainActivity", senSensorManager.toString());
}
public void registerSensors() {
senAccelerometer = senSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senGyroscope = senSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
senMagneticField = senSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
senSensorManager.registerListener(this, senAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senMagneticField,
SensorManager.SENSOR_DELAY_NORMAL);
/* DEBUG!! */onLocationChanged(location);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
last_x = sensorEvent.values[0];
last_y = sensorEvent.values[1];
last_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = (new Date()).toString() + " x:" + last_x
+ " y:" + last_y + " z:" + last_z;
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
if (mySensor.getType() == Sensor.TYPE_GYROSCOPE) {
gy_x = sensorEvent.values[0];
gy_y = sensorEvent.values[1];
gy_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = ("Gyroscope x:" + gy_x + " y:" + gy_y + " z:" + gy_z);
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
if (mySensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mag_x = sensorEvent.values[0];
mag_y = sensorEvent.values[1];
mag_z = sensorEvent.values[2];
context = getApplicationContext();
CharSequence text1 = ("Magnetic Field x:" + mag_x + " y:" + mag_y
+ " z:" + mag_z);
duration = Toast.LENGTH_SHORT;
toast = Toast.makeText(context, text1, duration);
toast.show();
}
}
protected void onPause() {
super.onPause();
senSensorManager.unregisterListener(this);
locationManager.removeUpdates(this);
}
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senGyroscope,
SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senMagneticField,
SensorManager.SENSOR_DELAY_NORMAL);
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude());
lng = (int) (location.getLongitude());
float speed = location.getSpeed();
Context context = getApplicationContext();
CharSequence text = (new Date()).toString() + " Lat:" + lat + " Long:"
+ lng + " Speed:" + speed;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It could be because the application is still running in the background, because it may not be dead yet.

GPS program works on JellyBean and KitKat but not Gingerbread

I am have written an app to find the GPS coordinates. The program works totally fine on Android 4.3 and 4.4.2 but for some reason its not working on 2.3.4 and 2.3.6. The GPS is not even turning on. Is there something additional that needs to be done to make it compatible with older APIs? I have included the following permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
This is the code :
package com.hari.gps;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
public static Context mContext;
public static Context getContext() {
return mContext;
}
public void setContext(Context mContext) {
MainActivity.mContext = mContext;
}
private LocationManager locationManager;
private String provider;
public static float lat, lng;
public static TextView t3, t4, t5, t6;
// SMSReceiver s;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.text1);
longitudeField = (TextView) findViewById(R.id.text2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
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.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
// s.onReceive(getApplicationContext(), getIntent());
//
// t3.setText(s.messageReceived);
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
public void msg(View view) {
EditText e1 = (EditText) findViewById(R.id.edit);
String phoneno = "8056371433";
String s = e1.getText().toString();
String message, m1, m2;
t3 = (TextView) findViewById(R.id.text3);
t4 = (TextView) findViewById(R.id.text4);
t5 = (TextView) findViewById(R.id.text5);
t6 = (TextView) findViewById(R.id.text6);
m1 = String.valueOf(lat);
m2 = String.valueOf(lng);
message = m1 + " " + m2;
if (e1.getText().length() == 0)
sendSMS(phoneno, message);
else
sendSMS(s, message);
}
private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(MainActivity.this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(
MainActivity.this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
boolean flag1 = true, flag2 = true;
lat = (float) (location.getLatitude());
lng = (float) (location.getLongitude());
if (lng < 0) {
lng = -lng;
flag1 = false;
}
if (lat < 0) {
lat = -lat;
flag2 = false;
}
if (flag2)
latituteField.setText("Latitude = " + lat + " N" + "\n");
else
latituteField.setText("Latitude = " + lat + " S" + "\n");
if (flag1)
longitudeField.setText("Longitude = " + lng + " E");
else
longitudeField.setText("Longitude = " + lng + " W");
// deg = Math.abs((int) lat);
// min = (int) ((lat - (float) deg) * 60.0);
// sec = (int) ((((lat - (float) deg) * 60) - min) * 60);
// if (flag2)
// latituteField.setText("Latitude = " +String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'N'+"\n");
// else
// latituteField.setText("Latitude = " +String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'S'+"\n");
// deg = Math.abs((int) lng);
// min = (int) ((lng - (float) deg) * 60.0);
// sec = (int) ((((lng - (float) deg) * 60) - min) * 60);
// if (flag1)
// longitudeField.setText("Longitude = " + String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'E');
// else
// longitudeField.setText("Longitude = " + String.valueOf(deg) + "° "
// + String.valueOf(min) + "\' " + String.valueOf(sec) + "\""
// + 'W');
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I had to add requestlocationupdates() to make it work Strange that I was getting GPS coordinates without using the said function on Jellybean and KitKat. So the modified code is :
Criteria criteria = new Criteria();
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
//start
public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener,com.google.android.gms.maps.GoogleMap.OnMapClickListener,OnMapLongClickListener,OnMarkerClickListener,GoogleMap.OnInfoWindowClickListener {
// Update interval in milliseconds for location services
private static final long UPDATE_INTERVAL = 5000;
// Fastest update interval in milliseconds for location services
private static final long FASTEST_INTERVAL = 1000;
// Google Play diagnostics constant
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Speed threshold for orienting map in direction of motion (m/s)
private static final double SPEED_THRESH = 1;
private static final String TAG = "Mapper";
private LocationClient locationClient;
private Location currentLocation;
private double currentLat;
private double currentLon;
private GoogleMap map;
private LatLng map_center;
private int zoomOffset = 5;
private float currentZoom;
private float bearing;
private float speed;
private float acc;
private Circle localCircle;
private double lon;
private double lat;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
// Define an object that holds accuracy and frequency parameters
LocationRequest locationRequest;
// Set up shared preferences to persist data. We will use it later
// to save the current zoom level if user leaves this activity, and
// restore it when she returns.
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get a handle to the Map Fragment
// map = ((MapFragment) getFragmentManager()
// .findFragmentById(R.id.mapme_map)).getMap();
map=((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.mapme_map)).getMap();
if(map != null){
// Set the initial zoom level of the map
currentZoom = map.getMaxZoomLevel()-zoomOffset;
// Add a click listener to the map
map.setOnMapClickListener(this);
// Add a long-press listener to the map
map.setOnMapLongClickListener(this);
// Add Marker click listener to the map
map.setOnMarkerClickListener(this);
// Add marker info window click listener
map.setOnInfoWindowClickListener(this);
} else {
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
/* Create new location client. The first 'this' in args is the present
* context; the next two 'this' args indicate that this class will handle
* callbacks associated with connection and connection errors, respectively
* (see the onConnected, onDisconnected, and onConnectionError callbacks below).
* You cannot use the location client until the onConnected callback
* fires, indicating a valid connection. At that point you can access location
* services such as present position and location updates.
*/
locationClient = new LocationClient(this, this, this);
// Create the LocationRequest object
locationRequest = LocationRequest.create();
// Set request for high accuracy
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set update interval
locationRequest.setInterval(UPDATE_INTERVAL);
// Set fastest update interval that we can accept
locationRequest.setFastestInterval(FASTEST_INTERVAL);
// Get a shared preferences
prefs = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
// Get a SharedPreferences editor
prefsEditor = prefs.edit();
// Keep screen on while this map location tracking activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
// Following two methods display and handle the top bar options menu for maps
// Save the current zoom level when going into the background
#Override
protected void onPause() {
// Store the current map zoom level
if(map != null){
currentZoom = map.getCameraPosition().zoom;
prefsEditor.putFloat("KEY_ZOOM",currentZoom);
prefsEditor.commit();
}
super.onPause();
Log.i(TAG,"onPause: Zoom="+currentZoom);
}
#Override
protected void onResume() {
super.onResume();
// Restore previous zoom level (default to max zoom level if
// no prefs stored)
if (prefs.contains("KEY_ZOOM") && map != null){
currentZoom = prefs.getFloat("KEY_ZOOM", map.getMaxZoomLevel());
}
Log.i(TAG,"onResume: Zoom="+currentZoom);
// Keep screen on while this map location tracking activity is running
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
/* The following two lifecycle methods conserve resources by ensuring that
* location services are connected when the map is visible and disconnected when
* it is not.
*/
// Called by system when Activity becomes visible, so connect location client.
#Override
protected void onStart() {
super.onStart();
locationClient.connect();
}
// Called by system when Activity is no longer visible, so disconnect location
// client, which invalidates it.
#Override
protected void onStop() {
// If the client is connected, remove location updates and disconnect
if (locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
}
locationClient.disconnect();
// Turn off the screen-always-on request
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onStop();
}
}

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!

Categories

Resources