检查传感器的长盖

时间:2012-08-28 12:05:50

标签: android detection android-sensors

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

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");
            }}
    }

}

1 个答案:

答案 0 :(得分:0)

现在,线程不断旋转,这对电池和其他一切的性能都有害。

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

应替换为:

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

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