手机屏幕锁定时如何暂停天文钟

时间:2018-08-15 06:47:58

标签: java android chronometer

我试图开发一个可以记录人们在手机上花费时间的应用程序。它假设我打开应用程序后启动计时器,并在屏幕锁定时暂停。问题是我可以使用暂停按钮将其停止,但不能通过锁定手机来完成。

package com.example.tony.screentimecounter812;

import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;

public class MainActivity extends AppCompatActivity {
    public Chronometer chronometer;
    private long pauseOffset;
    public boolean running = false;
    boolean screenStill = true;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void screenStill () {
        chronometer.start();
        while (screenStill) {
            KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);

            if (running) {
                assert mKeyguardManager != null;
                if (mKeyguardManager.isKeyguardLocked()) {
                    chronometer.stop();
                    pauseOffset = SystemClock.elapsedRealtime() - chronometer.getBase();
                    running = false;
                }
            }
            if (!running) {
                assert mKeyguardManager != null;
                if (!mKeyguardManager.isKeyguardLocked()) {
                    chronometer.start();
                    chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
                    running = true;
                }
            }
        }
    }



    @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chronometer = findViewById(R.id.chronometer);
        screenStill ();


}

1 个答案:

答案 0 :(得分:0)

您可以检查手机屏幕是否已打开,而不是被锁定

这可以通过使用:

PowerManager powermanager = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = powermanager.isInteractive();
  

“当此方法返回true时,设备处于唤醒状态并准备好与用户进行交互(尽管不能保证用户此时才与该设备进行积极的交互)。通常,在在这种状态下。”   https://developer.android.com/reference/android/os/PowerManager#isInteractive()

这是一种解决方法,但结果可能略有不同。例如,我不确定由于通知打开屏幕时,此方法是否也返回true!