Sleep API | Google for Developers (original) (raw)
Help users understand their sleep habits
The Sleep API, a library powered by Google Play services allows apps to determine when the user goes to sleep and wakes up.
After receiving permission from the user, Google Play services collects information related to surrounding brightness, device movement, and more to infer the times when the user falls asleep and wakes up. Your app can subscribe to updates to this information. That way, your app can inform users about their sleep habits and help encourage users to improve their sleep hygiene and overall well-being.
Before you begin
To prepare your app, complete the steps in the following sections.
App prerequisites
Make sure that your app's build file uses the following values:
- A
minSdkVersionof29or higher. - A
compileSdkVersionof29or higher.
.
Configure your app
In your project-level build.gradle file, include Google's Maven repository and Maven central repository in both your buildscript and allprojects sections:
buildscript { repositories { google() mavenCentral() } } allprojects { repositories { google() mavenCentral() } }
Add the Google Play services dependency for the Sleep API to your module's Gradle build file, which is commonly app/build.gradle:
dependencies { implementation 'com.google.android.gms:play-services-location:24.0.0' }
Add the ACTIVITY_RECOGNITION permission to your AndroidManifest.xml tag with android:name=”android.permission.ACTIVITY_RECOGNITION”.
Register for sleep updates
Prior to registering for updates, first check that the user has granted the ACTIVITY_RECOGNITION permission. For more information about permissions, see Request App Permissions.
Once permission has been granted, register for updates to the user's sleep behavior, including sleep segments and sleep event classification results, by calling requestSleepSegmentUpdates().
val task = ActivityRecognition.getClient(context) .requestSleepSegmentUpdates( pendingIntent, SleepSegmentRequest.getDefaultSleepSegmentRequest()) .addOnSuccessListener { viewModel.updateSubscribedToSleepData(true) Log.d(TAG, "Successfully subscribed to sleep data.") } .addOnFailureListener { exception -> Log.d(TAG, "Exception when subscribing to sleep data: $exception") }