💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
最近做的项目要用到距离传感器,所以写下这篇文章记录下心得。 其实心得只有一点,看官方的说明文档真的灰常重要。完了。。 贴上代码: ~~~ package com.example.mysensor; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private myListener listener; private SensorManager sm; private TextView tv; private Sensor sensor; private Handler handler = new Handler() { @Override public void handleMessage ( android.os.Message msg) { float data = (Float)msg.obj; String str = String.valueOf(data); tv.setText(str); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listener = new myListener(); tv = (TextView)this.findViewById(R.id.text); new Thread(new myThread()).start(); } private class myListener implements SensorEventListener { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub float value = event.values[0]; Message message = Message.obtain(); message.obj = value; handler.sendMessage(message); } } @Override protected void onDestroy() { sm.unregisterListener(listener); listener = null; super.onDestroy(); } private class myThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub sm = (SensorManager)getSystemService(SENSOR_SERVICE); sensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY); sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME); } } } ~~~