How to detect Ambient Light (Bright/Dark or Day/Night) and set the layout background accordingly in your Android App?

This video shows simple steps to create an Android App in which you detect or check the ambient light using the in-built LIGHT sensors of the phone.

This sensor returns the value of the ambient light in lux (illuminance) SI units.

To demonstrate the Application, it uses a customizable threshold value (using EditText). If the ambient light is below the threshold value then the App will detect it as a dark environment and change the background color of the App’s layout to grey. However, if the ambient light is higher than the threshold value then the App will show it as a bright ambience and change the App’s layout background color to white.

For testing in the normal room light condition, threshold values between 50 to 100 has been used in the demonstration. The demonstration on a real phone is shown towards the end of this video.

From code perspective, it simply uses a LIGHT sensor and enables respective sensor’s event change listener to implement the logic.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com

Complete source code:

package com.programmerworld.ambientlightapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private TextView textViewOutput;
private EditText editTextThreshold;
private ConstraintLayout constraintLayoutMain;

private float floatThreshold = 1;

private SensorManager sensorManager;
private Sensor sensorLight;

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

textViewOutput = findViewById(R.id.textView);
editTextThreshold = findViewById(R.id.editTextThreshold);
constraintLayoutMain = findViewById(R.id.myLayout);

sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

SensorEventListener sensorEventListenerLight = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float floatSensorValue = event.values[0]; // lux

if (floatSensorValue < floatThreshold){
textViewOutput.setText("It is Dark");
constraintLayoutMain.setBackgroundColor(Color.parseColor("#B5B5B5"));
}
else {
textViewOutput.setText("It is Bright");
constraintLayoutMain.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
sensorManager.registerListener(sensorEventListenerLight, sensorLight, SensorManager.SENSOR_DELAY_NORMAL);
}

public void buttonSetThreshold(View view){
if (editTextThreshold.getText().toString().isEmpty()){
return;
}
floatThreshold = Float.valueOf(editTextThreshold.getText().toString());
}
}
<?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/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="72dp"
android:onClick="buttonSetThreshold"
android:text="@string/set_threshold"
app:layout_constraintStart_toEndOf="@+id/editTextThreshold"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editTextThreshold"
android:layout_width="173dp"
android:layout_height="47dp"
android:layout_marginStart="40dp"
android:layout_marginTop="72dp"
android:ems="10"
android:hint="@string/set_threshold_value"
android:inputType="numberDecimal"
android:text="@string/_1"
android:textAlignment="center"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="" />

</androidx.constraintlayout.widget.ConstraintLayout>
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

apply plugin: 'com.android.application'

android {
compileSdkVersion 30
buildToolsVersion "29.0.3"

defaultConfig {
applicationId "com.programmerworld.ambientlightapp"
minSdkVersion 26
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

Leave a Reply

%d bloggers like this: