Recipe Creating a Runnable Activity

This recipe is an activity that evaluates a computationally intensive function, such as edge detection in an image. Here, a dummy function called detectEdges() is run to emulate the actual image-processing algorithm.

If detectEdges() is called in onCreate() by itself, it hangs the main thread and does not display the UI layout until computation is done. Therefore, a separate thread needs to be created and started for the time-consuming function. Because the main purpose of the activity is this time-consuming operation, it is natural to have the activity itself implement Runnable.As shown in Listing 3.4, the background thread is declared in the onCreate()

method.When the background thread is started, it calls the activity's run() method, which is overridden with the intended functionality.

The button is implemented exactly as in the previous "Launching a Secondary Thread" recipe. Pressing the button shows the UI is still responsive when the background task detectEdges() runs.

Listing 3.4 src/com/cookbook/runnable_activity/ package com.cookbook.runnable_activity;

import; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;

public class EdgeDetection extends Activity implements Runnable { int numberOfTimesPressed=0;

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

final TextView tv = (TextView) findViewById(; //in-place function call causes main thread to hang: /* detectEdges(); */

//instead, create background thread for time-consuming task Thread thread = new Thread(EdgeDetection.this); thread.start();

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

tv.setText("Pressed button " + ++numberOfTimesPressed + " times\nAnd computation loop at " + "(" + xi + ", " + yi + ") pixels");

@Override public void run() {


//Edge Detection int xi, yi;

private double detectEdges() { int x_pixels = 4000; int y_pixels = 3000; double image_transform=0;

//double loop over pixels for image processing //meaningless hyperbolic cosine emulates time-consuming task for(xi=0; xi<x_pixels; xi++) {

image_transform = Math.cosh(xi*yi/x_pixels/y_pixels);

return image_transform;

Learn Photoshop Now

Learn Photoshop Now

This first volume will guide you through the basics of Photoshop. Well start at the beginning and slowly be working our way through to the more advanced stuff but dont worry its all aimed at the total newbie.

Get My Free Ebook

Post a comment