src目录下MainActivity.java代码如下: 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 Activity { 16 17 private SensorManager sensorManager; 18 private TextView lightLevel; 19 20 @Override 21 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.getDefaultSensor(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 @Override 40 public void onSensorChanged(SensorEvent event) { 41 // valuse 数组中第一个下标的值就是当前的光照强度 42 float value = event.values[0]; 43 lightLevel.setText("当前光照强度为" + value + "勒克斯"); 44 } 45 46 @Override 47 public void onAccuracyChanged(Sensor sensor, int accuracy) { 48 49 } 50 }; 51 } 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/light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"
/>
</RelativeLayout>
时间: 2024-10-22 17:44:07