Displays the current light intensity and current light intensity.
The MainActivity. java code in the src directory is as follows:
1 package com. example. guangzhao; 2 3 4 5 import android. OS. bundle; 6 import android. app. activity; 7 import android. content. context; 8 import android. hardware. sensor; 9 import android. hardware. sensorEvent; 10 import android. hardware. sensorEventListener; 11 import android. hardware. sensorManager; 12 import android. view. menu; 13 import android. widget. textView; 14 15 public class MainActivity extends Activit Y {16 17 private SensorManager sensorManager; 18 private TextView lightLevel; 19 20 @ Override21 protected void onCreate (Bundle savedInstanceState) {22 super. onCreate (savedInstanceState); 23 setContentView (R. layout. activity_main); 24 lightLevel = (TextView) findViewById (R. id. light); 25 sensorManager = (SensorManager) getSystemService (Context. SENSOR_SERVICE); 26 Sensor sensor = sensorManager. getdefasen Sen Sor (Sensor. TYPE_LIGHT); 27 Sensor sensors; 28 sensorManager. registerListener (listener, sensor, SensorManager. SENSOR_DELAY_NORMAL); 29} 30 31 protected void onDestory () {32 super. onDestroy (); 33 if (sensorManager! = Null) {34 sensorManager. unregisterListener (listener); 35} 36} 37 38 private SensorEventListener listener = new SensorEventListener () {39 @ Override40 public void onSensorChanged (SensorEvent event) {41 // the first value in the valuse array is the current illumination intensity 42 float value = event. values [0]; 43 lightLevel. setText ("current illumination intensity is" + value + "Lux"); 44} 45 46 @ Override47 public void onAccuracyChanged (Sensor sensor, int accuracy) {48 49} 50 }; 51}
The activity_main.xml code is as follows:
<? 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/light"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_centerInParent = "true"
Android: textSize = "20sp"
/>
</RelativeLayout>