Recipe Handling a Time Consuming Initialization

This recipe addresses a common case of needing to run a time-consuming initialization when an application starts. Initially, the layout is set to show a specific "Loading..." splash screen specified in the loading.xml file. In this example, it is a simple text message as shown in Listing 3.8, but it could be a company logo or introductory animation.

Listing 3.8 res/layout/loading.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/loading" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Loading..." />

</LinearLayout>

While this layout is being displayed, the function initializeArrays(), which takes time to complete, is launched in a background thread to avoid hanging the UI.The initialization uses static variables to ensure a screen change or another instance of the activity does not require a recalculation of the data.

When the initialization is done, a message is sent to the handler mHandler. Since the act of sending a message is all the information needed, just an empty message is sent as mHandler.sendEmptyMessage(0).

Upon receiving the message, the UI thread runs the handleMessage() method. It is overridden to continue on with the activity after the starting initialization, here setting up the main screen specified in the main.xml layout file. The full activity is shown in Listing 3.9.

Listing 3.9 src/com/cookbook/handle_message/HandleMessage.java package com.cookbook.handle_message;

import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message;

public class HandleMessage extends Activity implements Runnable { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loading);

Thread thread = new Thread(this); thread.start();

private Handler mHandler = new Handler() { public void handleMessage(Message msg) { setContentView(R.layout.main);

public void run(){

initializeArrays(); mHandler.sendEmptyMessage(O);

final static int NUM_SAMPS = 1000; static double[][] correlation; void initializeArrays() {

if(correlation!=null) return;

correlation = new double[NUM_SAMPS][NUM_SAMPS]; //calculation for(int k=0; k<NUM_SAMPS; k++) {

correlation[k][m] = Math.cos(2*Math.PI*(k+m)/1000);

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