在onStop()onPause()中询问屏幕是否打开/关闭

时间:2013-10-08 19:50:02

标签: android android-intent android-lifecycle android-broadcast

我想知道我的onPause()和onStop()方法是否因为屏幕熄灭而被调用。因此我写了一个broadcastReceiver:

public class ScreenReceiver extends BroadcastReceiver {


    public static boolean screenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

            screenOn = false;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

            screenOn = true;
        }
    }

}

public class ExampleActivity extends Activity {

   @Override
    protected void onCreate() {

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);

    }

    @Override
    protected void onPause() {

        if (ScreenReceiver.screenOn) {

            System.out.println("SCREEN TURNED OFF");
        } else {

        }
        super.onPause();
    }

    @Override
    protected void onResume() {

        if (!ScreenReceiver.screenOn) {

            System.out.println("SCREEN TURNED ON");
        } else {

        }
        super.onResume();
    }

}

如果因为关闭屏幕而调用onPause(),怎么可能?

也许这个?

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_POWER) {
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

1 个答案:

答案 0 :(得分:1)

好吧,我现在使用它了

 pm =(PowerManager) getSystemService(Context.POWER_SERVICE);
 if (pm.isScreenOn() == false) { ... }