Android Programming Tutorials

(Romina) #1
Life and Times

for (int i=progress;
i< 10000 ;
i+= 200 ) {
doSomeLongWork( 200 );
}

Step #2: Pause in onPause()................................................................


Now, we need to arrange to have our thread stop running when the activity


is paused (e.g., some other activity has taken over the screen). Since threads


are relatively cheap to create and destroy, we can simply have our current


running thread stop and start a fresh one, if needed, in onResume().


While there are some deprecated methods on Thread to try to forcibly


terminate them, it is generally better to let the Thread stop itself by falling


out of whatever processing loop it is in. So, what we want to do is let the


background thread know the activity is not active.


To do this, first import java.util.concurrent.atomic.AtomicBoolean in


LunchList and add an AtomicBoolean data member named isActive, initially


set to true (new AtomicBoolean(true);).


Then, in the longTask Runnable, change the loop to also watch for the state


of isActive, falling out of the loop if the activity is no longer active:


for (int i=progress;
i< 10000 && isActive.get();
i+= 200 ) {
doSomeLongWork( 200 );
}

Finally, implement onPause() to update the state of isActive:


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

isActive.set(false);
}

78
Free download pdf