private void updateShowSeconds() { if (mShowSeconds) { // Wait until we have a display to start trying to show seconds. if (mSecondsHandler == null && getDisplay() != null) { mSecondsHandler = new Handler(); if (getDisplay().getState() == Display.STATE_ON) { mSecondsHandler.postAtTime(mSecondTick, SystemClock.uptimeMillis() / 1000 * 1000 + 1000); } IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); mContext.registerReceiver(mScreenReceiver, filter); } } else { if (mSecondsHandler != null) { mContext.unregisterReceiver(mScreenReceiver); mSecondsHandler.removeCallbacks(mSecondTick); mSecondsHandler = null; updateClock(); } } } private final BroadcastReceiver mScreenReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { if (mSecondsHandler != null) { mSecondsHandler.removeCallbacks(mSecondTick); } } else if (Intent.ACTION_SCREEN_ON.equals(action)) { if (mSecondsHandler != null) { mSecondsHandler.postAtTime(mSecondTick, SystemClock.uptimeMillis() / 1000 * 1000 + 1000); } } } }; private final Runnable mSecondTick = new Runnable() { @Override public void run() { if (mCalendar != null) { updateClock(); } mSecondsHandler.postAtTime(this, SystemClock.uptimeMillis() / 1000 * 1000 + 1000); } }; } 编译报错,getDisplay().getState() == Display.STATE_ON用其他代替
时间: 2024-03-15 12:47:15 浏览: 68
We're trying to save the manateesPPT教案学习.pptx
根据报错信息,getDisplay().getState() == Display.STATE_ON 出错了,这是因为 Display.getState() 方法在 Android 11(API level 30)中已被弃用。您可以使用 Display.getState(int userId) 方法代替,其中 userId 可以是 UserHandle.USER_CURRENT 或 UserHandle.USER_ALL。示例代码如下:
```java
if (mShowSeconds) {
// Wait until we have a display to start trying to show seconds.
if (mSecondsHandler == null && getDisplay() != null) {
mSecondsHandler = new Handler();
DisplayManager displayManager = (DisplayManager) mContext.getSystemService(Context.DISPLAY_SERVICE);
Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
if (display.getState() == Display.STATE_ON) {
mSecondsHandler.postAtTime(mSecondTick, SystemClock.uptimeMillis() / 1000 * 1000 + 1000);
}
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
mContext.registerReceiver(mScreenReceiver, filter);
}
} else {
if (mSecondsHandler != null) {
mContext.unregisterReceiver(mScreenReceiver);
mSecondsHandler.removeCallbacks(mSecondTick);
mSecondsHandler = null;
updateClock();
}
}
```
在代码中,我们首先获取了 DisplayManager 对象,并使用 getDisplay(Display.DEFAULT_DISPLAY) 方法获取了默认显示器的 Display 对象。然后,我们使用 getState() 方法获取了显示器的状态。如果状态为 Display.STATE_ON,则开始显示秒数。
阅读全文