【问题标题】:How to distinguish between the screen going off and the activity being sent in background in android如何区分屏幕熄灭和android在后台发送的活动
【发布时间】:2015-04-12 17:43:09
【问题描述】:

我正在编写一个与用户对话和倾听的应用程序。基本上是一款无需查看或触摸设备即可拨打电话的应用程序(信不信由你,我在市场上没有找到任何设备!)。 这里的重点是我想要:

  • 在屏幕熄灭时继续运行
  • 当用户切换到另一个活动时停止运行

而且我没有看到一个简单的方法来理解这一点。 我已经调查过了:How to stop a background thread when the screen in android device goes off

但事件的触发顺序错误(来自我的日志):

  • onPause:屏幕状态未知
  • onStop:屏幕状态未知
  • 屏幕事件:关闭

    public class ScreenReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            wasScreenOn = ScreenStatus.OFF;
            Log.d(TAG,"screen event OFF");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            wasScreenOn = ScreenStatus.ON;
            Log.d(TAG,"screen event ON");
        }
    }
    }
    

【问题讨论】:

  • 我怀疑 Screen on off 和 A​​ctivity 生命周期方法彼此同步运行。

标签: java android


【解决方案1】:

尝试使用 PowerManager,如本文所示,希望对您有所帮助。好像是你需要的,

how to check screen on/off status in onStop()?

【讨论】:

  • 抱歉 Android Killer:这将不会解决我的问题。如果用户离开应用程序和屏幕变黑,onStop() 都会被调用。如上所述,我实际上是在问如何区分这两件事
  • @SimoneAvogadro 编辑了答案,请检查。我认为这可以通过我们的 BroadcastReceiver 来完成。
  • 这正是我所需要的。在我的参考设备上,它完全符合我的需要。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 2015-07-19
  • 2017-08-25
相关资源
最近更新 更多