0

我有一个单一的活动计时器应用程序,其中我重写了 onPause() 方法以在用户按下主页或返回按钮时暂停计时器。但是,我希望计时器在用户手动关闭屏幕的情况下继续移动,但我知道这也会调用 onPause() 方法。有没有办法解决这个问题?

4

2 回答 2

0

您可以覆盖onBackPressed以允许您在按下后退按钮时添加一些额外的逻辑。但是,更好的方法可能是将代码放入 中onStop(),仅当另一个 Activity 移到前台时才会调用它。

有关更多详细信息,请参阅Android 文档

于 2013-01-02T03:02:17.870 回答
0

我最终通过检测并忽略 onPause() 方法中的屏幕关闭事件来做到这一点。可以在此处找到有关如何执行此操作的说明:http: //thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

具体来说,我使用了评论中的这段代码(由 Kyle 提供):

    @Override
    protected void onCreate() {
        // initialize receiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
        //NEW
        PowerManager pm =(PowerManager) getSystemService(Context.POWER_SERVICE);
        // your code
    }
    @Override
    protected void onPause() {
        // when the screen is about to turn off
        // Use the PowerManager to see if the screen is turning off
        if (pm.isScreenOn() == false) {
            // this is the case when onPause() is called by the system due to the screen turning off
            System.out.println(“SCREEN TURNED OFF”);
        } else {
            // this is when onPause() is called when the screen has not turned off
        }
        super.onPause();
    }
于 2013-01-02T18:53:55.903 回答