Android Lesson 5: android.os.Handler


We learn about android.os.Handler by creating some simple examples.

Example 1: Simple counter

Step 1: create new project
Step 2: with file contain_main.xml

add two TextView

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TUTORIALSPOTS.COM"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textColor="#ff0000"
        android:textSize="32dp"
        android:textIsSelectable="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="0"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

android os handler

Step 3: with file MainActivity.java

In class MainActivity:

package com.tutorialspots.handler;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public TextView tv;
    public int i = 0;
    public long step = 1000;//1000ms
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            tv.setText(String.valueOf(++i));
            handler.postDelayed(this, step);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        tv = (TextView) findViewById(R.id.textView);
        handler.postDelayed(runnable, step);
    }
...
}

Step 4: run, and we get the result:

android handler example

So, with Handler and Runnable, we can make a simple counter.

1 Comment

Leave a Reply