Search code examples
javaandroidbackground-processandroid-sensorslight-sensor

Create a app that reads a sensor data, then lock the screen


I know this can be done with some apps with Tasker and Automate, but I want to learn this by myself.

  1. Create a app that runs always in background;
  2. How to read a sensor data(in this case I would like to use the 'Ambient light sensor');
  3. Lock the screen.

I have Android Studio and everything is ready to make a app and compile, but I have no idea how to make this / where to start. Thanks for any help.


Solution

  • The questions you put covers couple of very wide topics and it is very difficult to provide tailor made answer to them. The best that someone can do is to provide some pointer which I will attempt to -

    1. To create an app in the background on Android, you basically create an Android service and keep it running in the background. Make sure it's a sticky service which means, the service will be restarted automatically if it was killed for some reason. If you want to run this app always on background (not a good idea though), you might listen for a Boot completed broadcast and start your background from the broadcast receiver. Below links are on related topics - https://developer.android.com/reference/android/content/BroadcastReceiver.html https://developer.android.com/reference/android/content/Intent.html#ACTION_BOOT_COMPLETED https://developer.android.com/guide/components/services.html https://developer.android.com/reference/android/app/Service.html#START_STICKY

    2. Reading ambient light sensor data is pretty straight forward. Follow the link provided below. Although all the samples shown in the link need your app to be in the foreground, but it is not mandatory. You can basically register for the sensor data change listener from your background service. Listening for sensor data, needs you to create an instance of the sensor manager framework service class and registering for a particular sensor (in your case Light) data change listener Source page - https://developer.android.com/guide/topics/sensors/sensors_overview.html

    3. I have no personal experience with keyguard locking/unlocking programmatically but few links which provide some sample code are worth looking - How to Lock/Unlock screen programmatically? Android screen lock/ unlock programmatically