saving the state of activity when the layout changes - android

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.

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

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

connection to aspx page from android?

I have developed an application get location but i need to save it to server using aspx webpage.
I have created tables on the webpage and i need to save these lat,long to the webpagepage using the unique id as imei?
I have created a table with imei, latlong, datetime
aspx name /http://Log.aspx/
can anybody help me please I have searched many but I couldn't understand.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
// initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// check if GPS is enabled
// else switch on gps
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
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);
}
}
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");
Intent intent = new Intent(
"android.location.GPS_ENABLED_CHANGE");
intent.putExtra("disabled", false);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
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);
}
}
else {
// get cell id
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);
// to write it to file
appendData("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 15, 0,
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");
// to write the file..
appendData(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}
I wrote a WS few months back like this:
<%# WebService Language="VBScript" Class="DataIns" %>
Imports System
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Globalization
<WebService(Namespace:="http://www.mysite.org/webservices/")> Public Class DataIns :Inherits WebService
<WebMethod()> Public Function devIns (ByVal dm As String) As String
Dim strArr() As String
Dim rtnVal As String
strArr = dm.split("^")
Dim connection As SqlConnection
Dim connection1 As SqlConnection
Dim connection2 As SqlConnection
Dim cmd As SqlCommand
Dim connectionString As String
connectionString = ConfigurationManager.ConnectionStrings("sqlsds").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmdtrans As SqlCommand
Dim cmdCheck As SqlCommand
Dim result as String
Dim sqltrans as String
Dim notes as String
Dim notes1 As String
sqltrans= "select dbo.fnCheckBlackList(#p_imei)"
cmdtrans=new sqlcommand(sqltrans,connection)
cmdtrans.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection.Open()
notes=cmdtrans.ExecuteScalar()
Catch ex As Exception
notes = ex.Message
Finally
connection.Close()
End Try
notes = If(IsDBNull(notes),"","")
if notes.Trim().Equals("TIMEUP") then
Context.Response.Output.Write("Save Completed Wipeout")
Context.Response.End()
return string.Empty
else
connection1 = New SqlConnection(connectionString)
result = "select dbo.fnCheckImeiDateWise(#p_imei)"
cmdCheck=new sqlcommand(result,connection1)
cmdCheck.Parameters.AddWithValue("#p_imei",strArr(0))
Try
connection1.Open()
notes1=cmdCheck.ExecuteScalar()
Catch ex As Exception
notes1 = ex.Message
Finally
connection1.close()
End Try
if notes1.Trim().Equals("FINE") then
connection2 = New SqlConnection(connectionString)
cmd = New SqlCommand("dbo.spInsertDeviceData", connection2)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#p_imei", strArr(0))
cmd.Parameters.AddWithValue("#p_location", strArr(1))
cmd.Parameters.AddWithValue("#p_aic", Integer.Parse(strArr(2)))
cmd.Parameters.AddWithValue("#p_adc", Integer.Parse(strArr(3)))
cmd.Parameters.AddWithValue("#p_ail", strArr(4))
cmd.Parameters.AddWithValue("#p_adl", strArr(5))
cmd.Parameters.AddWithValue("#p_tsss", Double.Parse(strArr(6)))
cmd.Parameters.AddWithValue("#p_ts", Double.Parse(strArr(7)))
cmd.Parameters.AddWithValue("#p_tsgp", Double.Parse(strArr(8)))
cmd.Parameters.AddWithValue("#p_tvpc", Double.Parse(strArr(9)))
Try
connection2.Open()
rtnVal = cmd.ExecuteNonQuery()
Catch ex As Exception
rtnVal = ex.Message
Finally
connection2.Close()
End Try
'Context.Response.Output.Write(rtnVal)
Dim parameterString As String
Dim dow2 As String
parameterString = ConfigurationManager.AppSettings("FREQUENCY")
parameterString = parameterString + "|"
parameterString = parameterString + getNewTime(ConfigurationManager.AppSettings("UPDATEAT1"))
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFWEEK1")
dow2 = ConfigurationManager.AppSettings("DAYOFWEEK2")
if String.IsNullOrEmpty(dow2) then
else
parameterString = parameterString +"*"
parameterString = parameterString + dow2
end if
parameterString = parameterString + "|"
parameterString = parameterString + ConfigurationManager.AppSettings("DAYOFMONTH")
Context.Response.Output.Write("Save Completed" + "|"+ parameterString)
Context.Response.End()
return string.Empty
else
Context.Response.Output.Write("ERROR")
Context.Response.End()
return string.Empty
End If
End If
end function
end class
and this was called like
http://www.mysite.org/DataIns.asmx/dIns?dm=<data-separated=by-^>

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