Changes the Background Color Randomly Every 10 Seconds in Java Code

In this tutorial, you'll learn how to implement a feature in a Java application where the background color changes randomly every 10 seconds. This involves setting up a timer or a background thread to periodically update the color of a view, such as a LinearLayout or ConstraintLayout, by generating random color values and applying them programmatically using Java code. This tutorial will cover concepts such as handling timers, generating random colors, and updating UI elements dynamically.
Submitted on July 07, 2024

A simple Android Java code snippet for changing the background color of MainActivity randomly every 10 seconds.

MainActivity.java

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.RelativeLayout;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private RelativeLayout mainLayout;
    private Handler handler = new Handler();
    private Random random = new Random();
    private Runnable colorChangeRunnable = new Runnable() {
        @Override
        public void run() {
            changeBackgroundColor();
            handler.postDelayed(this, 10000); // 10 seconds delay
        }
    };

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

        mainLayout = findViewById(R.id.main_layout);

        // Start changing background color immediately
        handler.post(colorChangeRunnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Stop the handler when the activity is destroyed
        handler.removeCallbacks(colorChangeRunnable);
    }

    private void changeBackgroundColor() {
        // Generate random RGB values
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);

        // Create a new color with random RGB values
        int randomColor = Color.rgb(red, green, blue);

        // Set the background color of the main layout
        mainLayout.setBackgroundColor(randomColor);
    }
}

      

Explanation:

  1. Imports: Import necessary Android classes and packages.
  2. Class Declaration: MainActivity extends AppCompatActivity.
  3. Variables:
    • mainLayout: RelativeLayout where we change the background color.
    • handler: Used to schedule color changes every 10 seconds.
    • random: Used to generate random RGB values.
    • colorChangeRunnable: Runnable task that changes the background color and reschedules itself every 10 seconds.
  4. onCreate():
    • Initializes the main layout (mainLayout).
    • Starts the color change process by posting colorChangeRunnable to handler.
  5. onDestroy():
    • Stops the handler from continuing to post colorChangeRunnable when the activity is destroyed to prevent memory leaks.
  6. changeBackgroundColor():
    • Generates random values for red, green, and blue components of the color.
    • Creates a new color using Color.rgb() with the random values.
    • Sets the background color of mainLayout to the generated random color.

Additional Notes:

  • Make sure your activity_main.xml file contains a RelativeLayout with the id main_layout or adjust the code accordingly if you use a different layout.
  • This example uses Handler and Runnable for simplicity. In a production app, you might consider other approaches, such as Timer or JobScheduler, depending on your requirements and Android version compatibility.