简体   繁体   中英

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

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

When configuration changes happens with app like screen lock, the activity is restarted. You will get so many answers on stackoverflow to avoid this problem like this ; but according to Google Engineers , it is bad practice to retain the activity. You will get the proper answer about how to avoid this problem here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM