I have this code
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (event.values[0] == 0) {
//near
Toast.makeText(getApplicationContext(), "near", Toast.LENGTH_SHORT).show();
turnOffScreen();
} else {
//far
Toast.makeText(getApplicationContext(), "far", Toast.LENGTH_SHORT).show();
turnOnScreen();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void turnOffScreen() {
mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
mWakeLock.acquire();
}
public void turnOnScreen() {
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
mWakeLock.acquire();
}
}
When the app is sleeping or goes to other activity, the sensor still work. Any idea?
In your initial code you have not handled releasing the wake lock properly. When your activity is in onStop , unregister your listener and also release the wake lock held.
I took other way to fix this problem, because no one knows how to fixed this, So with this code I don't need to use SensorManager. Now I use two functions for starting and stoping sensor, I think is the only one solution.
And this is my activity_main.xml
Thanks...
Also you can check this example in GitHub
Use the function
wakeLock.setReferenceCounted(false)
. I have used it, and it works.