Android Programming Tutorials

(Romina) #1
Life and Times

Note how we chain to the superclass in onPause() – if we fail to do this, we


will get a runtime error.


With this implementation, our background thread will run to completion


or until isActive is false, whichever comes first.


Step #3: Resume in onResume().........................................................


Now, we need to restart our thread if it is needed. It will be needed if the


progress is greater than 0 , indicating we were in the middle of our


background work when our activity was so rudely interrupted.


So, add the following implementation of onResume():


@Override
public void onResume() {
super.onResume();

isActive.set(true);

if (progress> 0 ) {
startWork();
}
}

This assumes we have pulled out our thread-starting logic into a


startWork() method, which you should implement as follows:


private void startWork() {
setProgressBarVisibility(true);
new Thread(longTask).start();
}

And you can change our menu handler to also use startWork():


@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.toast) {
String message="No restaurant selected";

if (current!=null) {
message=current.getNotes();
}

79
Free download pdf