0

我在检查传感器的长时间覆盖时遇到了一些问题(用于在手机靠近耳朵时关闭屏幕)。我想检测这个传感器的长短覆盖(例如通过我的手指)。这是我的代码,我可以检测到封面,但我无法检查它是长还是短(我认为我的线程中有错误,但我不知道是什么)

public class NextActivity extends Activity implements SensorEventListener {

    private static final String TAG = "DISTANCE";
    private SensorManager mSensorManager;
    private Sensor mProximity;
    public TextView tv;
    public TextView tv2;
    public int check=0;
    float distance=0;
    public float eventTime;
    public MyThread thread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);  

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

        tv = (TextView)findViewById(R.id.textView1);
        tv2= (TextView)findViewById(R.id.textView2);
        thread = new MyThread();
        thread.start();
    }


  public final void onSensorChanged(SensorEvent event) {
    distance = event.values[0];
        tv.setText(""+thread.isAlive());
  }



  @Override
  protected void onResume() {
    // Register a listener for the sensor.
    super.onResume();
    mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    // Be sure to unregister the sensor when the activity pauses.
    super.onPause();
    mSensorManager.unregisterListener(this);
  }

    public class MyThread extends Thread {

        @Override
        public void run() {
            while(true){
            if(distance<1) 
            {
                long time = System.currentTimeMillis();
                while(System.currentTimeMillis()<time+300);
                if(distance<1)
                {   
                    tv.setText("DOUBLE -> NEXT"); 
                    distance=5;
                } else tv.setText("ONCE -> BACK");      
            }else tv.setText("NONE CLICKED");
            }}
    }

}
4

1 回答 1

0

现在,线程不断旋转,这对电池不利,可能对其他所有设备的性能都不利。

           long time = System.currentTimeMillis();
           while(System.currentTimeMillis()<time+300);

应替换为:

           try {
               Thread.sleep(300);
           } catch(InterruptedException ie) {}

第二个问题是 TextViews 没有在 UI 线程中更新。因此,必须设置一个 Hnadler 来接收消息以设置文本,或者定义为与 runOnUiThread 一起使用的 Runnables。

于 2012-10-14T15:55:37.790 回答