【问题标题】:Prevent my android app starts automatically when the device/screen is sleeping/locked防止我的 android 应用程序在设备/屏幕处于睡眠/锁定状态时自动启动
【发布时间】:2015-01-15 07:32:28
【问题描述】:

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

[编辑]

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

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

【问题讨论】:

  • 你写过onPause方法的代码吗?
  • 为了减少杀戮和重新启动应用程序,您可以尝试使用内部应用程序运行服务。但这并不能阻止重新启动您的应用,只会降低机会

标签: android screen locked sleep-mode


【解决方案1】:

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

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

【讨论】:

  • 这看起来很复杂。我认为在应用程序中关闭声音会更容易,但我不知道如何仅在设备处于睡眠状态时执行此操作: public void playSound(int id){ if(!DEVICE_IS_ASLEEP()) snds[id].播放(声音ID [id],1,1,0,0,1); }
  • 只需将以上所有 sn-ps 复制到您的服务或活动中,然后在 onCreate 中调用 initBroadcasts()。如果屏幕关闭时活动仍然存在(不应该顺便说一句。) - 锁定/关闭/屏幕保护程序打开 - 那么您可以将 screenOn 布尔值传递给您的 playSound(int id, boolean screenOn) 和内部 if(screenOn){...}
【解决方案2】:

当屏幕锁定等应用发生配置更改时,Activity 会重新启动。你会在 stackoverflow 上得到很多答案来避免这个问题,比如this;但根据Google Engineers,保留活动是不好的做法。你会得到关于如何避免这个问题的正确答案here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多