Page 1 of 1

Setting up a timed method to run in the background

#1 lexxe  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 44
  • Joined: 05-December 10

Posted 26 April 2011 - 11:47 AM

Recently I started with Android development and one of the things I wanted was to have an image that rotates automatically on a timer. I had researched this extensively and had my issues finding a clear answer on it. Across multiple tutorials I found my answer, and refined it to a nice bit of code that does everything I needed it to, and can be used for a variety of tasks.

What you need to know before starting this tutorial:
General understanding of Android XML

Setup:
First things you're going to want to do is a couple imports. We will be using TextView widget and a handler, so we need to import both of those:
import android.os.Handler;
import android.widget.TextView;


Part I: "Is your runnable running?" "Yes?" "You had better go catch it! Hahahaha. Ha."

When we decide to implement this, we need to know what we're going to do. For the sake of keeping things simple, you we're going to just make a TextView count. For this purpose, we will need to set up a text view. I'm going to assume you have a project open, so I'll just jump right into the code you're going to need implement.

Lets set up our text view:
<TextView   
    android:id="@+id/changingText"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="we haven't changed it yet!"
    />


Dang, thats a sweet TextView, you might say. Wrong!

Uh, anyways. You have your TextView set up next we have to set up a runnable to handle our actual action of changing the TextView.

Here is our basic le yawn runnabe:
private Runnable TextViewChanger = new Runnable(){
    	public void run() {
    	}
    };


So what are we actually going to accomplish by running this here runnable? You can put anything in there you want to run, but we're going to count. Lets count to 5. Since this is a TextView we're changing, lets just make a string array. I like to put these variables above the onCreate method, so lets put our string array up there. While we're at it, we need to add a counting variable to it so we can keep track of where we're at in the count. We're going to use an integer to do this. Also, we need to assign a name to our text view. Lets call it textCount, after its Great Aunt textCount. Attach our TextView to textCount so we can use it later and have our app know what we're talking about.

String message[] = {"We just counted to 1", "We just counted to 2", "We just counted to 3", 
        "We just counted to 4", "We just counted to 5"};
	int counter = 0;
	TextView textCount;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textCount = (TextView)findViewById(R.id.changingText);
    }


Ok, lets pop back down to our fancy little runnable to add our code to it.

We're going to use a simple increment to keep track of our number and display the correct string, and an if statement to make sure it doesn't go out of our array. Lets set that up now.

With our full method:
private Runnable TextViewChanger = new Runnable(){
    	public void run() {
			textCount.setText(message[counter]);
			counter++;
			if (counter > 4){
				counter = 0;
			}
    	}
    };


There, now your runnable does something! On to part 2!

Part 2: Handler! Handle something!

If you're still with me, we need to name our handler we will be using and create a method to execute our runnable via the handler. A handler in this situation basically controls our runnable so we can run it at certain time. So up where we named our string array, our integer, and whatnot, we need to name our handler.

String message[] = {"We just counted to 1", "We just counted to 2", "We just counted to 3", 
        "We just counted to 4", "We just counted to 5"};
	int counter = 0;
	TextView textCount;
	private Handler counterHandler = new Handler();



Next we need to somehow make that counter be able to be called multiple times without us invoking it. Thats where the onCreate come in. We're going to make a method that handles the time delay of our runnable.

Here is how I set up the method:
    private void LetsCount(){
    	counterHandler.postDelayed(TextViewChanger, 1000);
    }


What we just set up is a method we can call that invokes the handler that runs the runnable. Say the last part of 5 times fast. Or make an app that will display it for you 5 times fast. Either way. What we're passing the postDelayed() is what runnable we want to run, in this case its our only runnable, and how long after this line of code we want the runnable to be run in milliseconds. Remember that 1000 milliseconds is 1 second. We're going to count every second.

We are almost done by this point. We have the runnable, we have the handler method set up, all we need now is to call the method, and keep calling it so we can repeat this every seconds. You will need to call the method from both the onCreate and from within the runnable.

And this code to the end of each the onCreate and the runnable:
LetsCount();


Thats it! Your runnable should work just fine now. Here is what your code should look like:
package org.spencercole.textchanger;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class TextChanger extends Activity {
	String message[] = {"We just counted to 1", "We just counted to 2", "We just counted to 3", 
	        "We just counted to 4", "We just counted to 5"};
		int counter = 0;
		TextView textCount;
		private Handler counterHandler = new Handler();

	    /** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        textCount = (TextView)findViewById(R.id.changingText);
	        LetsCount();
	    }
	private void LetsCount(){
		counterHandler.postDelayed(TextViewChanger, 1000);
	}
	private Runnable TextViewChanger = new Runnable(){
	    	public void run() {
				textCount.setText(message[counter]);
				counter++;
				if (counter > 4){
					counter = 0;
				}
	                        LetsCount();
	    	}
	    };



}


Good luck! You can do anything with this that you like. I've used it to rotate banners by calling the resource id from an integer array. You can expand on that by adding an on click listener to rotate with the image to call specific articles for a blog viewer app, or something else. Experiment and enjoy!

Is This A Good Question/Topic? 1
  • +

Replies To: Setting up a timed method to run in the background

#2 laserbeak43  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 129
  • Joined: 07-November 09

Posted 05 May 2011 - 06:52 PM

nice, I'll try it as soon as i'm able
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1