问题
I have configured proximeter successfully in my code. Now I want to turn off & on screen programmatically. Code of sensor is working just fine and following method is also getting called.
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock screenWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"screenWakeLock");
if (event.values[0] == 0) {
screenWakeLock.acquire();
Log.e("onSensorChanged","NEAR");
} else {
if (screenWakeLock != null) {
if(screenWakeLock.isHeld())
screenWakeLock.release();
screenWakeLock = null;
}
Log.e("onSensorChanged","FAR");
}
}
My problem is that screen is not getting turn off. I also have added required permission in code. What else could be the reason ???
回答1:
Check the changes submitted for this code, https://github.com/jitsi/jitsi-android/compare/6d356fa637ae...7aba481d773f
getPowerManager().newWakeLock( 32, "proximity_off");
回答2:
As from my understanding wakelock
is useful to keep screen on. I wasn't successful to turn screen on & off using it.
So, first I dimmed screen brightness as low as possible and then made all GUI elements unclickable. This way I solved my problem.
Following is method:
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
WindowManager.LayoutParams params = this.getWindow().getAttributes();
if (event.values[0] == 0) {
//TODO Store original brightness value
params.screenBrightness = 0.004f;
this.getWindow().setAttributes(params);
enableDisableViewGroup((ViewGroup)findViewById(R.id.YOUR_MAIN_LAYOUT).getParent(),false);
Log.e("onSensorChanged","NEAR");
} else {
//TODO Store original brightness value
params.screenBrightness = -1.0f;
this.getWindow().setAttributes(params);
enableDisableViewGroup((ViewGroup)findViewById(R.id.YOUR_MAIN_LAYOUT).getParent(),true);
Log.e("onSensorChanged","FAR");
}
}
From here, I took reference to disable touch for entire screen's view.
回答3:
Try this shortcut:
PowerManager manager = getPowerManager();
WakeLock lock = manager.newWakeLock( 32, "proximity_off");
lock.acquire();
The above code doesn't even need the proximity sensor changed events to be listened. 32
is for a hidden WakeLock
field that is used by the InCallActivity
of the Phone
and other such similar applications.
来源:https://stackoverflow.com/questions/22809005/how-to-enable-proximity-sensor-in-android