0

First post here, but stackoverflow has solved soooo many problems for me. This one though, I can't seem to figure out. I'm creating an android app that de-increments and TextView value by 1 with every proximity detection. For some reason, when the Activity starts or resumes (power button), it logs 2 proximity hits. I've double-checked to ensure that I'm not close enough to the detector when pushing the power button.

Here is the code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.exercise);
    //start proximity
    startProximitySensor(sensorListener());
}

private SensorEventListener sensorListener(){
    listener = new SensorEventListener(){

        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onSensorChanged(SensorEvent event) {
            if(event.sensor.getType() == Sensor.TYPE_PROXIMITY){
                String maxRange = String.valueOf(mProximitySensor.getMaximumRange());
                if(event.values[0] == Float.parseFloat(maxRange)){
                    updateTextView();
                    Log.i(TAG,"Proximity Sensor Reading: "+ String.valueOf(event.values[0]));


                }

            }

        }

    };

    return listener;
}

private void startProximitySensor(SensorEventListener proximitySensorEventListener){
    mSensorManager = (SensorManager)getSystemService(getApplicationContext().SENSOR_SERVICE);
    mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    if(mProximitySensor == null){
        Log.i(TAG,"No proximity sensor found!");
    }else{
        proximityStarted = true;
        Log.i(TAG,"Proximity started");
        mSensorManager.registerListener(proximitySensorEventListener,mProximitySensor,SensorManager.SENSOR_DELAY_UI);
    }
}

I've managed to get around it by creating a timeStamp in onResume, and comparing that to the SystemTime generated on each sensor change. If they differ for anything less than 1 second, then the TextView won't update. This works, but I'd still like to know if I'm missing something.

Thanks in advance

user1977217
  • 401
  • 1
  • 4
  • 4
  • do you unregister the listener in the onDestroy event? it might be registered multiple times due to multiple create calls (count the create calls in a static variable for example to see if it gets called multiple times). – x4rf41 Jan 14 '13 at 12:31
  • Thanks. I've tested this and although I haven't specifically unregistered the listener in onDestroy, the static count still only counts once when started. Also, even when the app is first installed, as soon as the activity that starts the listener begins, it logs 2 proximity hits... unusual! thanks anyways – user1977217 Jan 22 '13 at 06:08

0 Answers0