Android Proximity Sensor近距离传感器P-Sensor详解手机开发

package zhangphil.sensor; 
 
import android.content.Context; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
 
public class MainActivity extends AppCompatActivity { 
    private SensorManager mSensorManager; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
 
        startSensor(); 
    } 
 
    /** 
     * 启动传感器。 
     */ 
    private void startSensor() { 
        mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE); 
        Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); 
 
        if (mSensorManager == null || mSensor == null) { 
            throw new UnsupportedOperationException("设备不支持"); 
        } 
 
        boolean isRegister = mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL); 
        if (!isRegister) { 
            throw new UnsupportedOperationException("设备不支持"); 
        } 
    } 
 
    private SensorEventListener mSensorEventListener = new SensorEventListener() { 
 
        @Override 
        public void onSensorChanged(SensorEvent sensorEvent) { 
            float proximity=sensorEvent.values[0]; 
            Log.d("近距离", String.valueOf(proximity)); 
        } 
 
        @Override 
        public void onAccuracyChanged(Sensor sensor, int i) { 
 
        } 
    }; 
 
    @Override 
    protected void onDestroy() { 
        super.onDestroy(); 
        mSensorManager.unregisterListener(mSensorEventListener); 
    } 
}

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/3123.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论