-1

我想知道我的 onPause() 和 onStop() 方法是否因为屏幕关闭而被调用。因此我写了一个广播接收器:

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);
}
4

1 回答 1

1

好的,我知道了,我现在用

 pm =(PowerManager) getSystemService(Context.POWER_SERVICE);
 if (pm.isScreenOn() == false) { ... }
于 2013-10-08T20:26:21.260 回答