0

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

[编辑]

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

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

2 回答 2

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 是一个广播接收器,如下所示:

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();
}
于 2015-01-15T07:44:06.800 回答
0

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

于 2015-01-15T07:48:52.177 回答