Skip to content

Instantly share code, notes, and snippets.

@ishitcno1
Last active December 25, 2023 04:26
Show Gist options
  • Save ishitcno1/7261765 to your computer and use it in GitHub Desktop.
Save ishitcno1/7261765 to your computer and use it in GitHub Desktop.
Detect android device screen on, screen off and user present, then to do something.
public class MainActivity extends Activity {
private ScreenStateReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new ScreenStateReceiver();
registerReceiver(mReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
}
}
public class ScreenStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)) {
//code
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
//code
}
}
}
@DungPham14
Copy link

How can the above service work when the app is completely shut down and running on the latest version of Android?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment