Android - activity lifecycle

Soldato
Joined
18 Aug 2011
Posts
2,853
Location
Norfolk
I have a class that is to be a 1/4 mile timer.

The code is below:
public class QuarterMile extends Activity
{
TextView display;
TextView display2;

double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distanceMeters = 0;

//the timer view
private TextView textTimer;
//the start finish buttons
private Button startButton, resetButton;
//the start time
private long startTime = 0L;
//create a handler
private Handler myHandler = new Handler();
//timing variables
long timeInMillies = 0L, timeSwap = 0L, finalTime = 0L;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.quarter_mile);

display = (TextView) findViewById(R.id.textView1);
display2 = (TextView) findViewById(R.id.textView2);

LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, Loclist);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if(loc == null)
{
display.setText("No GPS location found");
Intent i = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(i, 0);
Toast.makeText(getApplicationContext(),
"Please set Mode to 'High accuracy' to enable GPS tracking " +
"and then go back to the 1/4-mile timer. Thank you.",
Toast.LENGTH_LONG).show();
}
else
{
//Set the last latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
lastLat = currentLat;
lastLon = currentLon;
String message = "Current Location \nLongitude: " + currentLon +
"\nLatitude: "+ currentLat +
"\nCurrent Location \nLongitude: " + lastLon +
"\nLatitude: "+ lastLat;
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}

textTimer = (TextView) findViewById(R.id.textTimer);
startButton = (Button) findViewById(R.id.startButton);
resetButton = (Button) findViewById(R.id.resetButton);

startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);
}
});

resetButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
//reset the thread/runnable
myHandler.removeCallbacks(updateTimerMethod);

//reset the timer to 00:00:00
int seconds = (int) (0);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (0);
textTimer.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliseconds));
}
});
}

//start a thread to count the timer
private Runnable updateTimerMethod = new Runnable()
{
public void run()
{
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;

int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
textTimer.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliseconds));
myHandler.postDelayed(this, 0);
//if the distance travelled is 400 or more stop the timer
if(distanceMeters >= 10)
{
timeSwap += timeInMillies;
myHandler.removeCallbacks(updateTimerMethod);

startTime = 0L;
timeInMillies = 0L;
timeSwap = 0L;
finalTime = 0L;
}
}
};

LocationListener Loclist = new LocationListener()
{
@override
public void onLocationChanged(Location location)
{
//start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
//get last location
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//request new location
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, Loclist);

//get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();

Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);

Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);

distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;

display.setText(String.format("%.2f Km", distanceKm));
display2.setText("Distance is: " + distanceMeters);
}

My question is:

After the user has enabled GPS (if it's disabled) and goes back to the application the distance is 5800+km instead of being 0.00 like it is when it is opened up when GPS is already enabled.

Is there a way of reloading the onCreate() when the user presses back?
Or is there a way of updating the variables?
 
Soldato
Joined
16 Jun 2013
Posts
5,375
Why not create a private class for the main activity then call it oncreate() and onresume()? So it runs anew each time going through the entire process.

(Makes sense to my sleep deprived brain)
 
Soldato
OP
Joined
18 Aug 2011
Posts
2,853
Location
Norfolk
I tried creating an onResume() method but even just using:

@override
public void onResume()
{

}

Creates a "has stopped" working message when trying to load that particular class/service.

The package I'm using has 8 classes.

When the application is loaded it opens a class called A...a button pressed opens class B... then in class B there are 4 buttons to choose from to load classes C, D, E and F - from B I'm loading class F.


At the moment the code I have if the GPS is enabled before class F is loaded the app works fine and the current and last location are the same and gives a distance travelled of 0.00 (well almost).
If GPS is not enabled an Intent is used to take the user to turn on GPS. However once the user has done this and presses back the distance is 5812km or 5812000m. I want this to be 0.00 as it is when GPS is enabled before the app is fired.

:confused::confused::confused:

If it isnt 0.00 (or close to it) then it wont work because when the distance gets to >= 0 it stops the timer, but obviously with a distance of 5812000m the timer stops at 00:00:01.
 
Last edited:
Soldato
OP
Joined
18 Aug 2011
Posts
2,853
Location
Norfolk
Ok, had a look at the activity lifecycle and as it calls onPause() when a new activity is launched so I think I need to use onRestart() which it accepts, but I'm stuck on what code I should put in there to get it to work.

I tried:

@override
public void onRestart()
{
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, Loclist);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

//Set the last latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
lastLat = currentLat;
lastLon = currentLon;
String message = "Current Location \nLongitude: " + currentLon +
"\nLatitude: "+ currentLat +
"\nLast Location \nLongitude: " + lastLon +
"\nLatitude: "+ lastLat;
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}

So that when it restarts it recreates the location manager/listener and updates the current and last long/lat, but when I try pressing back to go back to the service it "has stopped".

Will I need to create a separate method where a new location manager/location listener can be created from both onCreate() and on Restart()?
 
Associate
Joined
29 Apr 2004
Posts
696
are you calling super.onResume() in your overridden onResume() method? I think it does some extra processing that is necessary.

P.S. it's worth pasting your code into a site like http://pastebin.com/ so that the code is formatted correctly and easier for sharing.
 
Soldato
OP
Joined
18 Aug 2011
Posts
2,853
Location
Norfolk
Taken the complete lazy way out and just created a button to re-check the current location when pressed.

Therefore when the "back" key is pressed after enabling GPS it doesn't matter that the long/lat is 0 as the user can press the button now to update their location.

Will see if that website works :)

Here is the code:
http://pastebin.com/Ku4zczui#

Basically just created the Location Manager and Location outside of the onCreate() and then make use of them within the onCreate() and the resetLocationButton().

If anyone has ideas how to make it any better I'd welcome criticism.

Here is the XML too - my design skills are lacking (just have grey buttons and text) so any ideas to make it look nice are welcomed too:
http://pastebin.com/c5sQktYi
 
Last edited:
Back
Top Bottom