Tuesday, March 29, 2016

android - Handler and Runnable Thread example

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:padding="16dp"
    tools:context=".MainActivity"
    android:background="#c7d1d6"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click The Buttons"
        android:padding="25sp"
        android:textSize="25sp"
        android:layout_margin="15dp"
        android:fontFamily="sans-serif-condensed"
        android:background="#fff"
        />
    <Button
        android:id="@+id/btn_runnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Runnable Thread"
        android:layout_below="@+id/tv"
        />
    <Button
        android:id="@+id/btn_repeated"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Repeated Task"
        android:layout_toRightOf="@id/btn_runnable"
        android:layout_toEndOf="@id/btn_runnable"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Repeated Task"
        android:layout_toRightOf="@id/btn_repeated"
        android:layout_toEndOf="@id/btn_repeated"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

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

import java.util.Random;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private Button mButtonStartRunnable;
    private Button mButtonStartRepeatedTask;
    private Button mButtonStopRepeatedTask;
    private TextView mTextView;

    private Handler mHandler;
    private Runnable mRunnable;

    private Random mRandom = new Random();


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

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

        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButtonStartRunnable = (Button) findViewById(R.id.btn_runnable);
        mButtonStartRepeatedTask = (Button) findViewById(R.id.btn_repeated);
        mButtonStopRepeatedTask = (Button) findViewById(R.id.btn_stop);
        mTextView = (TextView) findViewById(R.id.tv);

        // Initialize a new Handler
        mHandler = new Handler();

        // Set a click listener for start runnable button
        mButtonStartRunnable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Set the TextView background color to white
                mTextView.setBackgroundColor(Color.WHITE);

                // Set the TextView text
                mTextView.setText("A Runnable Task");

                // Initialize a new Runnable
                mRunnable = new Runnable() {
                    @Override
                    public void run() {
                        // set the TextView text color with a random color
                        mTextView.setTextColor(getRandomHSVColor());
                    }
                };

                // Execute the task after specified time
                mHandler.postDelayed(mRunnable,1000);
            }
        });

        // Set a click listener for the start repeated task button
        mButtonStartRepeatedTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Set the text color to white
                mTextView.setTextColor(Color.WHITE);

                // Set the TextView text
                mTextView.setText("Repeated Task running...");

                // Initialize a new Runnable
                mRunnable = new Runnable() {
                    @Override
                    public void run() {
                        // Set a random background color for TextView
                        mTextView.setBackgroundColor(getRandomHSVColor());

                        // Repeat the task after a specified time delay
                        mHandler.postDelayed(this, 1000);
                    }
                };

                // Execute the task after specified time
                mHandler.postDelayed(mRunnable,1000);
            }
        });

        // Set a click listener for the stop repeated task button
        mButtonStopRepeatedTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Set the TextView text
                mTextView.setText("Repeated Task stop...");

                // Stop the repeated task
                mHandler.removeCallbacks(mRunnable);
            }
        });
    }

    // Custom method to generate random HSV color
    public int getRandomHSVColor(){
        // Generate a random hue value between 0 to 360
        int hue = mRandom.nextInt(361);
        // We make the color depth full
        float saturation = 1.0f;
        // We make a full bright color
        float value = 1.0f;
        // We avoid color transparency
        int alpha = 255;
        // Finally, generate the color
        int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
        // Return the color
        return color;
    }
}