你的位置:首页 > 操作系统

[操作系统]显示当前光照强度

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 @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.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 @Override40 public void onSensorChanged(SensorEvent event) {41 // valuse 数组中第一个下标的值就是当前的光照强度42 float value = event.values[0];43 lightLevel.setText("当前光照强度为" + value + "勒克斯");44 }45 46 @Override47 public void onAccuracyChanged(Sensor sensor, int accuracy) {48 49 }50 };51 }activity_main.

<?<RelativeLayout     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>