【发布时间】:2013-02-24 01:05:26
【问题描述】:
我在尝试生成的 Android 代码方面遇到了一些麻烦。我想要做的只是在用户想要解锁他们的手机时打印一个 1,当程序第一次启动时,当用户按下屏幕锁定来锁定他们的手机时打印一个 0。我认为这与 Android 生命周期有关,所以我尝试使用 onPause 和 onResume,但我的程序只打印出 0,而不是 1。 logTime 方法简单地打印出 1 或 0,而 MainActivity 中的 onCreate 方法调用一次 onResume()。这是我的代码:
主活动:
protected void onPause(){
if(ScreenReceiver.screenOn){
logTime(ScreenReceiver.screenOn);
super.onPause();
}
protected void onResume()
if(!ScreenReceiver.screenOn){
logTime(!ScreenReceiver.screenOn);
super.onResume();
}
屏幕接收器:
public class ScreenReceiver extends BroadcastReceiver{
public static boolean screenOn;
@Override
public void onReceive(Context context, Intent intent){
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
screenOn = false;
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
screenOn = true;
}
}
}
我不确定为什么它只打印出 0。可能有人知道为什么吗?谢谢!
【问题讨论】:
-
logTime(!ScreenReceiver.screenOn)应该只是logTime(ScreenReceiver.screenOn);没有! -
@A--C 嗯,好吧。我现在遇到了一些麻烦 - 每当我恢复我的应用程序时,我永远无法记录 1。当我解锁屏幕时,没有打印任何内容,但是当我锁定屏幕时,它打印出 0。你知道吗为什么?
-
您在哪里注册/注销接收方?你所拥有的(除了使用基本相同的参数调用
logTime())看起来是正确的。 -
我只是在我的 MainActivity 的 onCreate 部分注册了它。这就是我所拥有的: IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadcastReceiver 接收器 = new ScreenReceiver(); registerReceiver(接收器,过滤器);
-
我明白你的意思。实际接收之间存在延迟,因此您会得到奇怪的打印输出。
标签: android printing boolean android-lifecycle