Android: Turn Off Screen When Close to Face

Turn off screen programmatically when face is close the screen on Android

I found solution by disassembling one very famous VoIP application. This activity after pressing button1 will disable screen and hardware keys when you close sensors. After pressing button2 this function will be switched off.

Also, this function required permission:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Activity. Try it.

public class MainActivity extends Activity {

private Button button1;
private Button button2;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
private int field = 0x00000020;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

try {
// Yeah, this is hidden field.
field = PowerManager.class.getClass().getField("PROXIMITY_SCREEN_OFF_WAKE_LOCK").getInt(null);
} catch (Throwable ignored) {
}

powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(field, getLocalClassName());

setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);

button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!wakeLock.isHeld()) {
wakeLock.acquire();
}
}
});

button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(wakeLock.isHeld()) {
wakeLock.release();
}
}
});
}
}

android: turn off screen when close to face

What you are seeing is the use of a proximity sensor. For devices that have one, you access it through SensorManager.

How to temporarily disable screen in Android?

You might want to have a look at these answers

Turn off screen programmatically when face is close the screen on Android

android: turn off screen when close to face

Android: How to turn screen on and off programmatically?

Turn off the mobile screen in Android programming

You may find this useful https://developer.android.com/guide/topics/sensors/sensors_position.html

In the link the related program code you may want to look into is

@Override 
protected void onResume() {
// Register a listener for the sensor.
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);

}

This might also be a repeated stackoverflow post to: Turn off screen programmatically when face is close the screen on Android

Hope this helps!



Related Topics



Leave a reply



Submit