Sunday, October 25, 2015

android - How to do a task after a delay

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text color will be red after 5 seconds."
        android:textSize="25dp"
        android:padding="15dp"
        android:fontFamily="sans-serif-condensed"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Do a Task After A delay"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidsnippets;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.os.Handler;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private TextView mTv;

    private Handler mHandler;
    private Runnable mRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        Button btn = (Button) findViewById(R.id.btn);
        mTv = (TextView) findViewById(R.id.tv);

        /*
            Handler
                A Handler allows you to send and process Message and Runnable objects associated
                with a thread's MessageQueue. Each Handler instance is associated with a single
                thread and that thread's message queue. When you create a new Handler, it is bound
                to the thread / message queue of the thread that is creating it -- from that point
                on, it will deliver messages and runnables to that message queue and execute them
                as they come out of the message queue.

            public Handler ()
                Default constructor associates this handler with the Looper for the current thread.
                If this thread does not have a looper, this handler won't be able to receive
                messages so an exception is thrown.


        */
        // Initialize a new instance of Handler
        mHandler = new Handler();

        // Set a click listener for button
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    Runnable
                        Represents a command that can be executed. Often used to run code in a
                        different Thread.

                    Thread
                        A Thread is a concurrent unit of execution. It has its own call stack for
                        methods being invoked, their arguments and local variables. Each application
                        has at least one thread running when it is started, the main thread, in the
                        main ThreadGroup. The runtime keeps its own threads in the system thread group.

                        There are two ways to execute code in a new thread. You can either subclass
                        Thread and overriding its run() method, or construct a new Thread and pass a
                        Runnable to the constructor. In either case, the start() method must be
                        called to actually execute the new Thread.

                */
                mRunnable = new Runnable() {
                    /*
                        public abstract void run ()
                            Starts executing the active part of the class' code. This method is
                            called when a thread is started that has been created with a class which
                            implements Runnable.
                    */
                    @Override
                    public void run() {
                        // Do some task on delay
                        // Set the TextView text color to red
                        mTv.setTextColor(Color.RED);
                    }
                };

                /*
                    public final boolean postDelayed (Runnable r, long delayMillis)
                        Causes the Runnable r to be added to the message queue, to be run after the
                        specified amount of time elapses. The runnable will be run on the thread to
                        which this handler is attached. The time-base is uptimeMillis(). Time spent
                        in deep sleep will add an additional delay to execution.

                        Parameters
                            r : The Runnable that will be executed.
                            delayMillis : The delay (in milliseconds) until the Runnable will be executed.
                        Returns
                            Returns true if the Runnable was successfully placed in to the message
                            queue. Returns false on failure, usually because the looper processing
                            the message queue is exiting. Note that a result of true does not mean
                            the Runnable will be processed -- if the looper is quit before the
                            delivery time of the message occurs then the message will be dropped.
                */
                mHandler.postDelayed(mRunnable, 5000);
            }
        });
    }
}
More android examples