Android receive onKeyDown event even if screen is off

62 Views Asked by At

I am writing a simple program in Java that is supposed to detect volume key presses even if the phone screen turns off. When the volume up key is pressed it prints the number of times it has been pressed. This works as intended while the screen is on but when I turn off the phone it no longer prints anything. I have tried using a partial wake lock to allow my app to continue running even after the device has been turned off but this doesn't solve my problem. I do also have the WAKE_LOCK permission added in my android manifest

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;

public class MainActivity extends AppCompatActivity {


    private WakeLock wakeLock;
    private int counter = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //partial wake lock
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyApp::MyWakelockTag");
        if (this.wakeLock != null && !this.wakeLock.isHeld())
            this.wakeLock.acquire();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //I no longer see an output after turning the screen off
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
        {
            counter++;
            System.out.println(counter);
        }
        else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
        {
            //here I just want to kill my application
            wakeLock.release();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        return true;
    }

}
0

There are 0 best solutions below