当设备/屏幕处于休眠/锁定状态时,防止我的Android应用程序自动启动

时间:2015-01-15 07:32:29

标签: android screen locked sleep-mode

问题是如果我的应用程序正在运行并且设备(屏幕)被锁定,则在设备锁定时重新启动应用程序(我知道因为我可以在启动时听到我的应用程序的声音)。

[编辑]

这看起来很复杂。我认为在应用程序中关闭声音会更容易,但我不知道如何在设备处于睡眠状态时执行此操作:

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

2 个答案:

答案 0 :(得分:0)

您可以registerReceiver使用Context(可能在服务内部)

//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是一个BroadcastReceiver,如下所示:

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

检查屏幕是否已解锁:

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

答案 1 :(得分:0)

当应用程序如屏幕锁定发生配置更改时,活动将重新启动。您将在stackoverflow上获得如此多的答案,以避免像this这样的问题;但根据Google Engineers,保留活动是不好的做法。您将获得有关如何避免此问题的正确答案here