Last active
December 25, 2023 04:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can the above service work when the app is completely shut down and running on the latest version of Android?