Handling Screen OFF and Screen ON Intents

4952 ワード

他の放送パッケージとは違ってACTION_SCREEN_OFFとIntent.ACTION_SCREEN_ONはmanifestでは説明できませんが、コードで登録する必要があります.
Receiverコードは次のとおりです.
public class ScreenReceiver extends BroadcastReceiver {

// thanks Jason
public static boolean wasScreenOn = true;

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}

}

例activityは次のとおりです.
public class ExampleActivity extends Activity {

@Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// your code
}

@Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}

@Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
super.onResume();
}

}

以下を参照してください.
Handling Screen OFF and Screen ON Intents
android.intent.action.SCREEN_ON doesn't work as a receiver intent filter