Wednesday, 21 January 2026

Change Background With A Touch



 This tutorial is the simplest example of changing the background color with a touch.

First start with the xml file i.e activity_main.xml

In actual you don't really have to do anything in the xml file but just for understanding, just type this line in the base / Constraint Layout

android:background="@color/white"

So that the complete xml script becomes:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

It already has the id defined so no worries.

Now let's move on to the Java code i.e MainActivity.java file:

Here create an object of Constraint Layout

ConstraintLayout cl;

and initialize it in the onCreate method

cl = findViewById(R.id.main);

finally in the onUserInteraction method, just set the color you want

cl.setBackgroundColor(Color.WHITE);

If you want random colors on every interaction, just create an array of colors in this way with a random object:

int[] color = {Color.BLUE, Color.CYAN, Color.MAGENTA,
Color.BLACK, Color.GRAY, Color.GREEN, Color.RED};
Random random = new Random();

In onUserInteraction use the random object to set a random color:

cl.setBackgroundColor(color[random.nextInt(color.length-1)]);

So now the complete Java code becomes:

package com.example.backgroundcolorchanger;

import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

ConstraintLayout cl;
int[] color = {Color.BLUE, Color.CYAN, Color.MAGENTA,
Color.BLACK, Color.GRAY, Color.GREEN, Color.RED};
Random random = new Random();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cl = findViewById(R.id.main);
}

@Override
public void onUserInteraction() {
super.onUserInteraction();
cl.setBackgroundColor(color[random.nextInt(color.length-1)]);
}
}



Friday, 14 November 2025

How to Vibrate your phone in Android Studio

 

The shortest code to make your phone vibrate is here.

First of all write the vibrate permission in the AndroidManifest.xml file

<uses-permission android:name="android.permission.VIBRATE"/>

Then create a button in activity_main.xml

<Button
android:id="@+id/pattern_vibration_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trigger Pattern Vibration"/>

Now in the Java file:

Create an object of Vibrator and get the system's vibrator service

Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

Check if the device supports vibrator

if (vibrator == null || !vibrator.hasVibrator()) {
Toast.makeText(this, "Vibrator not supported on this device", Toast.LENGTH_SHORT).show();
return;
}

Create a method to perform the vibration

private void triggerPatternVibration() {
long[] pattern = {0, 200, 100, 300};

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
VibrationEffect effect = VibrationEffect.createWaveform(pattern, -1);
vibrator.vibrate(effect);
} else {
// For devices with SDK < 26
vibrator.vibrate(pattern, -1); // -1 means no repeat
}
Toast.makeText(this, "Pattern Vibration Triggered", Toast.LENGTH_SHORT).show();
}

The patterns are in milli seconds and goes in this way: wait, vibrate, pause, vibrate.

Check the Build version.

Perform the vibration only once hence use -1.

Finally let the vibration be controlled through the button we created:

Button patternVibrationButton = findViewById(R.id.pattern_vibration_button);
patternVibrationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
triggerPatternVibration();
}
});

So here we are done with our code.

------------------------------------------------------------------------------------------

The complete code:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.VIBRATE"/>

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.PhoneVibrate">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">

<Button
android:id="@+id/pattern_vibration_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trigger Pattern Vibration"/>

</LinearLayout>

MainActivity.java

package com.prashantsj.apps.phonevibrate;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private Vibrator vibrator;

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

vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

if (vibrator == null || !vibrator.hasVibrator()) {
Toast.makeText(this, "Vibrator not supported on this device", Toast.LENGTH_SHORT).show();
return;
}

Button patternVibrationButton = findViewById(R.id.pattern_vibration_button);
patternVibrationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
triggerPatternVibration();
}
});
}

private void triggerPatternVibration() {
long[] pattern = {0, 200, 100, 300};

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
VibrationEffect effect = VibrationEffect.createWaveform(pattern, -1); // -1 means no repeat
vibrator.vibrate(effect);
} else {
// For devices with SDK < 26
vibrator.vibrate(pattern, -1); // -1 means no repeat
}
Toast.makeText(this, "Pattern Vibration Triggered", Toast.LENGTH_SHORT).show();
}

}

Thursday, 16 October 2025

How to turn ON the Torch!

 Do you wonder how can we lit the light of our Android Phone's Torch?

Here we have a very small code to do that!


We only need just one permission in our AndroidManifest.xml to turn ON the light:

<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />

So after adding this, the AndroidManifest.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Torch">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


Then in the activity_main.xml, create a button for user interaction:

<Button
android:id="@+id/torchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle Flashlight" />

Here is the full content of the activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/torchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle Flashlight" />
</LinearLayout>


Finally in the MainActivity.java we have to do multiple thing:

1. Create object of CameraManager which is used to interact with the camera hardware, in this case, to control the flashlight.

2. Create a String object cameraId which holds the ID of the camera (typically used to refer to the back camera here).

3. Create a boolean isTorchOn to track whether the torch is currently on or off.

private CameraManager cameraManager;
private String cameraId;
private boolean isTorchOn = false;

4. The getSystemService(CAMERA_SERVICE) call retrieves a system-level service to access the camera hardware.

cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);

5. Add a try catch block:

  • This block attempts to get a list of camera IDs using cameraManager.getCameraIdList(). The first item in the list ([0]) corresponds to the back camera.

  • If there’s an error in accessing the camera, it catches the CameraAccessException and prints the stack trace.

try {
cameraId = cameraManager.getCameraIdList()[0]; // Use the back camera
} catch (CameraAccessException e) {
e.printStackTrace();
}

6. Set up the Button for Toggling Torch:

A Button named torchButton is found using findViewById(R.id.torchButton), which references the button element defined in the XML layout file.

The setOnClickListener method attaches a click listener to the button, so when it’s clicked, the toggleTorch() method will be called.

Button torchButton = findViewById(R.id.torchButton);
torchButton.setOnClickListener(view -> toggleTorch());


7. toggleTorch() Method: This method toggles the flashlight (torch) on and off.

It checks the isTorchOn flag:

If the torch is on (isTorchOn is true), it calls cameraManager.setTorchMode(cameraId, false) to turn the flashlight off.

If the torch is off (isTorchOn is false), it calls cameraManager.setTorchMode(cameraId, true) to turn it on.

After toggling the torch, it updates the isTorchOn flag accordingly.

private void toggleTorch() {
try {
if (isTorchOn) {
// Turn off the torch
cameraManager.setTorchMode(cameraId, false);
isTorchOn = false;
} else {
// Turn on the torch
cameraManager.setTorchMode(cameraId, true);
isTorchOn = true;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}


So the complete code of MainActivity.java will be:

package com.prashantsj.apps.torch;

import android.app.Activity;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends Activity {

private CameraManager cameraManager;
private String cameraId;
private boolean isTorchOn = false;

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

// Initialize the CameraManager
cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);

// Get the camera ID (for the back camera)
try {
cameraId = cameraManager.getCameraIdList()[0]; // Use the back camera
} catch (CameraAccessException e) {
e.printStackTrace();
}

// Button to toggle torch
Button torchButton = findViewById(R.id.torchButton);
torchButton.setOnClickListener(view -> toggleTorch());
}

private void toggleTorch() {
try {
if (isTorchOn) {
// Turn off the torch
cameraManager.setTorchMode(cameraId, false);
isTorchOn = false;
} else {
// Turn on the torch
cameraManager.setTorchMode(cameraId, true);
isTorchOn = true;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}



ElevenLabs For Audio Models