在屏幕关闭时执行操作,但在应用程序转到后台时关闭

时间:2015-05-14 09:31:27

标签: android button service screen lifecycle

我必须允许我的应用程序在用户关闭屏幕时执行操作,但是当用户转到主屏幕(或其他应用程序)时我必须停止服务。

我试图处理电源按钮,但它无法正常工作。 然后我像这样创建ScreenReceiver:

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        wasScreenOn = false;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        wasScreenOn = true;
    }
}

但它改变了 wasScreenOn 值太晚了(在调用onStop方法之后)

@Override
protected void onStop() {
    super.onStop();
    Log.i(TAG, "onStop");
    if (powerButtonClicked)
        return;
    if (mBound) {
        mMediaService.onStop();
    }
}

电源按钮总是假的......它变化太晚了

如何正确地做到这一点?

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案。 您需要做的就是声明PowerManager

PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

和onStop()

if (!powerManager.isScreenOn()) 
{
    // Screen is off
}
相关问题