Search code examples
androidtouchcallvoipproximity

Disable screen touch in android on call


I am working on a calling screen where I need to enable and disable touch events on the screen while the user is on a call.

For this I implement SensorEventListener on my activity and override the onSensorChanged() method:

public void onSensorChanged(SensorEvent sensorEvent) {
    if(sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        if(sensorEvent.values[0] == 0) { //Sleep
            sleepScreen(true);
        } else { //Wake
            sleepScreen(false);
        }
    }
}

Below is my sleepScreen() method:

protected void sleepScreen(boolean on){
    if(on == true) {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        getWindow().setAttributes(params);
    } else {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
        getWindow().setAttributes(params);
    }

}

The FLAG_NOT_TOUCHABLE works fine disabling touch events. However, I am not able to re-enable the touch events again.

Pls help!


Solution

  • STEP 1: Add this in onCreate before calling setContentView()

    int powerValue = 0x00000020;
    
        try {
            powerValue = PowerManager.class.getClass().getField("PROXIMITY_SCREEN_OFF_WAKE_LOCK").getInt(null);
        } catch (Throwable ignored) {
        }
    
        mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(field, getLocalClassName());
    

    STEP 2: Override the method by implementing SensorEventListener

    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
            if (sensorEvent.values[0] == 0) { //Sleep
                sleepScreen(true);
            } else { //Wake
                sleepScreen(false);
            }
        }
    }
    

    STEP 3: Include this method to disable screen lock

    protected void sleepScreen(boolean on) {
    
            if (on == true) {
                if (!mWakeLock.isHeld()) {
                    mWakeLock.acquire();
                }
            } else {
                if (mWakeLock.isHeld()) {
                    mWakeLock.release();
                }
            }
    }
    

    STEP 4: Add the wake lock permission to AndroidManifest.xml

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