Wednesday, 30 January 2013

Fork the Thread from the Menu | Android Tutorial pdf

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>

This requires a graphic image in LunchList/res/drawable/run.png – find something that you can use that is around 32px high.
Since the menu item is in the menu XML, we do not need to do anything special to display the item – it will just be added to the menu automatically. We do, however, need to arrange to do something useful when the menu choice is chosen. So, update onOptionsItemSelected() in LunchList to look like the following:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.toast) {
String message="No restaurant selected";
if (current!=null) {
message=current.getNotes();
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return(true);
}
else if (item.getItemId()==R.id.run) {
new Thread(longTask).start();
}
return(super.onOptionsItemSelected(item));
}

You are welcome to recompile, reinstall, and run the application. However, since our background thread does not do anything visible at the moment, all you will see that is different is the new menu item:
                                                  The Run Long Task menu item

No comments: