Search code examples
androidscreenlockedsleep-mode

Prevent my android app starts automatically when the device/screen is sleeping/locked


The problem is that if my app is running and the device (screen) is locked, the app is restarted while the device is locked (I know because I can hear the sound of my app at startup).

[Edit]

This seems very complicated. I think it would be easier to turn off sounds in the app, but I do not know how to do this only when the device is asleep:

public void playSound(int id){
    if(!DEVICE_IS_ASLEEP())
        snds[id].play(soundID[id], 1, 1, 0, 0, 1);
}

Solution

  • you may registerReceiver using Context (probably inside Service)

    //assuming user starting Service by press smth in app (or simple open it), so the screen will be on for sure
    boolean screenOn=true;
    
    //put this inside your onCreate
    private void initBroadcasts(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        //new feature from API 17 - screensaver (?)
        if(android.os.Build.VERSION.SDK_INT>=17){
            filter.addAction(Intent.ACTION_DREAMING_STARTED);
            filter.addAction(Intent.ACTION_DREAMING_STOPPED);
        }
    
        screenOn = getScreenUnlocked();
        this.registerReceiver(screenBroadcastReceiver, filter);
    }
    

    screenBroadcastReceiver is a BroadcastReceiver as below:

    private BroadcastReceiver screenBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent myIntent) {
            if(myIntent.getAction().equals(Intent.ACTION_SCREEN_ON))
                screenOn=getScreenUnlocked();
            else if(myIntent.getAction().equals(Intent.ACTION_SCREEN_OFF))
                screenOn=false;
            else if(myIntent.getAction().equals(Intent.ACTION_USER_PRESENT))
                screenOn=true;
            else if(android.os.Build.VERSION.SDK_INT>=17){
                if(myIntent.getAction().equals(Intent.ACTION_DREAMING_STARTED))
                    screenOn=false;
                else if(myIntent.getAction().equals(Intent.ACTION_DREAMING_STOPPED))
                    screenOn=getScreenUnlocked();
            }
        }
    };
    

    check if screen is unlocked:

    private boolean getScreenUnlocked(){
        KeyguardManager kgMgr = 
                (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        return !kgMgr.inKeyguardRestrictedInputMode();
    }