• [置顶] Android代码传感器光传感


    一个简单的小Demo 测试手机光传感:

    具体代码如下:


    [java代码]Sample.java

    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

    <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

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


  • 相关阅读:
    Pycharm 设置python文件自动生成头部信息模板
    Python3.0 调用HTMLTestRunner生成的报告中不能显示用例中print函数的输出
    Python3.0 操作MySQL数据库执行SQL语句
    js时间戳转为日期格式
    Vue脚手架(vue-cli)安装总结
    Vue的生命周期
    常用的ES6语法
    学习python登录demo
    CSS的垂直居中和水平居中总结
    CSS清除浮动方法总结
  • 原文地址:https://www.cnblogs.com/anjon520/p/3249941.html
Copyright © 2020-2023  润新知