Android Programming Tutorials

(Romina) #1
Sitting in the Background

To do that, first, implement a doSomeLongWork() method on LunchList as


follows:


private void doSomeLongWork(final int incr) {
SystemClock.sleep( 250 ); // should be something more useful!
}

Here, we sleep for 250 milliseconds, simulating doing some meaningful


work.


Then, create a private Runnable in LunchList that will fire off


doSomeLongWork() a number of times, as follows:


private Runnable longTask=new Runnable() {
public void run() {
for (int i= 0 ;i< 20 ;i++) {
doSomeLongWork( 500 );
}
}
};

Here, we just loop 20 times, so the overall background thread will run for 5


seconds.


Step #3: Fork the Thread from the Menu...........................................


Next, we need to arrange to do this (fake) long work at some point. The


easiest way to do that is add another menu choice. Update the


LunchList/res/menu/option.xml file to look like the following:


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/toast"
android:title="Raise Toast"
android:icon="@drawable/toast"
/>
<item android:id="@+id/run"
android:title="Run Long Task"
android:icon="@drawable/run"
/>
</menu>

71
Free download pdf