Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active November 26, 2023 15:21
Show Gist options
  • Save sunmeat/a25c3094401f29ddc7b01b9e53481573 to your computer and use it in GitHub Desktop.
Save sunmeat/a25c3094401f29ddc7b01b9e53481573 to your computer and use it in GitHub Desktop.
light sensor example android
MainActivity.java:
package com.alex.sensors;
import android.app.Activity;
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.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
SensorManager sm;
SensorEventListener listener;
Sensor light;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
light = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Toast.makeText(MainActivity.this, "accuracy changed!", Toast.LENGTH_SHORT).show();
}
@Override
public void onSensorChanged(SensorEvent event) {
tv.setText(String.valueOf(event.values[0]));
int grayShade = (int) event.values[0];
if (grayShade > 255) grayShade = 255;
// http://www.android-examples.com/set-change-screen-brightness-in-android-programmatically/
// Settings.System.putInt(MainActivity.this.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, grayShade);
tv.setTextColor(Color.rgb(255 - grayShade, 255 - grayShade, 255 - grayShade));
tv.setBackgroundColor(Color.rgb(grayShade, grayShade, grayShade));
}
};
sm.registerListener(listener, light, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sm.unregisterListener(listener, light);
}
}
==============================================================================================================
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="60sp" />
</RelativeLayout>
==============================================================================================================
AndroidManifest.xml:
...
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-feature android:name="android.hardware.sensor.light"/>
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment