gpt4 book ai didi

java - 如何在手机屏幕锁定时暂停计时器

转载 作者:太空宇宙 更新时间:2023-11-04 10:14:50 25 4
gpt4 key购买 nike

我尝试开发一款应用程序,可以记录人们使用手机的时间。一旦我打开应用程序,它就会启动计时器,并在屏幕锁定时暂停。问题是我可以用暂停按钮停止它,但我不能用锁定手机来做到这一点。

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 ();


}

最佳答案

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

这可以通过使用来完成:

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

"When this method returns true, the device is awake and ready to interact with the user (although this is not a guarantee that the user is actively interacting with the device just this moment). The main screen is usually turned on while in this state." https://developer.android.com/reference/android/os/PowerManager#isInteractive()

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

关于java - 如何在手机屏幕锁定时暂停计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51854127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com