Recipe Scheduling a Runnable Task from the Main Thread

This recipe implements a clock timer, which is often needed in applications. For example, it can be used in a game to keep track of how long a player takes to complete a level. This provides a simple way to handle user interaction while a background thread continues to run.

The timer is run in a background thread so it does not block the UI thread, but it needs to update the UI whenever the time changes.As shown in Listing 3.5, the TextView text starts with a welcome message and the button text with trigger ID starts with the value "Press Me."

Listing 3.5 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<TextView android:id="@+id/text"

android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

<Button android:id="@+id/trigger"

android:layout_width="100dip" android:layout_height="100dip" android:text="Press Me"

</LinearLayout>

These text resources in the layout XML file are associated with TextView variables in the BackgroundTimer Java activity using the following initializers:

mTimeLabel = (TextView) findViewById(R.id.text); mButtonLabel = (TextView) findViewById(R.id.trigger);

After identified in Java, the text can be modified during run-time.When the application starts, the mUpdateTimeTask starts a counting timer and overwrites the text mTimeLabel with the new time in minutes and seconds.When the button is pressed, its onClick() method overwrites the text mButtonLabel with the number of times the button was pressed.

The handler mHandler is created and used to queue the runnable object mUpdateTimeTask. It is first called in the onCreate() method and then the recursive call in the task itself continues to update the time every 200ms.This is more often than needed to ensure a smooth time change each second without excessive overhead in task calls.The complete activity is shown in Listing 3.6.

Listing 3.6 src/com/cookbook/background_timer/BackgroundTimer.java package com.cookbook.background_timer;

import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.view.View; import android.widget.Button; import android.widget.TextView;

public class BackgroundTimer extends Activity {

//keep track of button presses, a main thread task private int buttonPress=0; TextView mButtonLabel;

//counter of time since app started, a background task private long mStartTime = 0L; private TextView mTimeLabel;

//Handler to handle the message to the timer task private Handler mHandler = new Handler();

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

mStartTime = SystemClock.uptimeMillis(); mHandler.removeCallbacks(mUpdateTimeTask); mHandler.postDelayed(mUpdateTimeTask, 100);

mTimeLabel = (TextView) findViewById(R.id.text); mButtonLabel = (TextView) findViewById(R.id.trigger);

Button startButton = (Button) findViewById(R.id.trigger); startButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view){

mButtonLabel.setText("Pressed " + ++buttonPress

private Runnable mUpdateTimeTask = new Runnable() { public void run() {

final long start = mStartTime;

long millis = SystemClock.uptimeMillis() - start; int seconds = (int) (millis / 1000); int minutes = seconds / 60; seconds = seconds % 60;

mTimeLabel.setText("" + minutes + ":"

+ String.format("%02d",seconds)); mHandler.postDelayed(this, 200);

@Override protected void onPause() {

mHandler.removeCallbacks(mUpdateTimeTask);

super.onPause();

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

mHandler.postDelayed(mUpdateTimeTask, 100);

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment