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) {}

2 つ目の問題は、TextView が UI スレッドで更新されていないことです。そのため、メッセージを受信して​​テキストを設定するように Hnadler を設定するか、runOnUiThread で使用するように定義された Runnables を設定する必要があります。

于 2012-10-14T15:55:37.790 に答える