Sample.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.example.test_sensor_light; 
   
import org.openintents.sensorsimulator.hardware.Sensor; 
import android.app.Activity; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.widget.TextView; 
   
public  class Sample extends Activity implements  android.hardware.SensorEventListener { 
       
    private TextView myTextView1; 
   
    private SensorManager mySensorManager; 
   
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        myTextView1 = (TextView) findViewById(R.id.myTextView1); 
        mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
   
    
   
    @Override 
    protected void onResume() { 
        mySensorManager.registerListener( 
                this
                mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), 
                SensorManager.SENSOR_DELAY_GAME 
                ); 
        super.onResume(); 
    
   
    @Override 
    protected void onStop() { 
        // TODO Auto-generated method stub 
        mySensorManager.unregisterListener(this); 
        super.onStop(); 
    
    @Override 
    protected void onPause() { 
        mySensorManager.unregisterListener(this); 
        super.onPause(); 
    
   
    @Override 
    public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) { 
        // TODO Auto-generated method stub 
           
    
   
    @Override 
    public void onSensorChanged(android.hardware.SensorEvent event) { 
        // TODO Auto-generated method stub 
        float[] values = event.values; 
        int sensorType = event.sensor.TYPE_LIGHT; 
        if (sensorType == Sensor.TYPE_LIGHT) { 
            myTextView1.setText("当前光的强度为:"+values[0]);       
        
    
   
}

 

 
 
[xml代码]main.xml

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"
   
    <TextView 
        android:id="@+id/myTextView1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
     /> 
     
</LinearLayout>

string.xml

1
2
3
4
5
6
7
8
<resources
   
    <string name="app_name">Sample</string
    <string name="title">光传感器</string
    <string name="hello_world">Hello world!</string
    <string name="menu_settings">Settings</string
   
</resources>
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()