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

Solkin picture Solkin · Feb 19, 2014 · Viewed 23.1k times · Source

My app is a dialer and when user holding the phone near his head I need to turn screen off and prevent clicking on the controls - like native Android dialer behavior. What API level I need and how can I do this in right way?

Answer

Solkin picture Solkin · Feb 20, 2014

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();
                }
            }
        });
    }
}