Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Last active December 31, 2015 19:28
Show Gist options
  • Save daichan4649/8033301 to your computer and use it in GitHub Desktop.
Save daichan4649/8033301 to your computer and use it in GitHub Desktop.
ロック状態検知 (Android)
// permission は特に必要なし
// アプリ起動時に登録
private void registerKeyguardReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SCREEN_OFF);
context.registerReceiver(mKeyguardReceiver, filter);
}
// アプリ終了時に解除
private void unregisterKeyguardReceiver() {
try {
context.unregisterReceiver(mKeyguardReceiver);
} catch (Exception e) {
// 何もしない
}
}
private BroadcastReceiver mKeyguardReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// キーガード状態判定フラグ
if (TextUtils.equals(action, Intent.ACTION_USER_PRESENT)) {
// Activity#onResume はロック中に画面ONにしただけでも飛んでくるため、
// ロック中かどうかの判定はこのintentで判断する必要あり
}
else if (TextUtils.equals(action, Intent.ACTION_SCREEN_OFF)) {
// スクリーンOFF=ロック中
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment