From 6ef44c422553bedf858b82df4ceb06250abcf529 Mon Sep 17 00:00:00 2001 From: kathychenx <75821931+kathychenx@users.noreply.github.com> Date: Mon, 26 Apr 2021 13:12:33 -0700 Subject: [PATCH] Add files via upload --- CONTRIBUTING.md | 28 +++ LICENSE | 202 +++++++++++++++ README.md | 9 + build.gradle | 41 +++ complete/build.gradle | 90 +++++++ complete/proguard-rules.pro | 35 +++ complete/src/main/AndroidManifest.xml | 68 +++++ .../example/sleepcodelab/MainActivity.kt | 237 ++++++++++++++++++ .../example/sleepcodelab/MainApplication.kt | 43 ++++ .../example/sleepcodelab/MainViewModel.kt | 55 ++++ .../sleepcodelab/data/SleepRepository.kt | 72 ++++++ .../data/datastore/SleepSubscriptionStatus.kt | 49 ++++ .../data/db/SleepClassifyEventDao.kt | 44 ++++ .../data/db/SleepClassifyEventEntity.kt | 54 ++++ .../sleepcodelab/data/db/SleepDatabase.kt | 60 +++++ .../data/db/SleepSegmentEventDao.kt | 44 ++++ .../data/db/SleepSegmentEventEntity.kt | 47 ++++ .../sleepcodelab/receiver/BootReceiver.kt | 116 +++++++++ .../sleepcodelab/receiver/SleepReceiver.kt | 102 ++++++++ .../drawable-v24/ic_launcher_foreground.xml | 46 ++++ .../res/drawable/ic_launcher_background.xml | 185 ++++++++++++++ .../src/main/res/layout/activity_main.xml | 59 +++++ .../res/mipmap-anydpi-v26/ic_launcher.xml | 20 ++ .../mipmap-anydpi-v26/ic_launcher_round.xml | 20 ++ .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 3593 bytes .../res/mipmap-hdpi/ic_launcher_round.png | Bin 0 -> 5339 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 2636 bytes .../res/mipmap-mdpi/ic_launcher_round.png | Bin 0 -> 3388 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 4926 bytes .../res/mipmap-xhdpi/ic_launcher_round.png | Bin 0 -> 7472 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 7909 bytes .../res/mipmap-xxhdpi/ic_launcher_round.png | Bin 0 -> 11873 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 10652 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.png | Bin 0 -> 16570 bytes complete/src/main/res/values-night/themes.xml | 32 +++ complete/src/main/res/values/colors.xml | 25 ++ complete/src/main/res/values/strings.xml | 33 +++ complete/src/main/res/values/themes.xml | 32 +++ gradle.properties | 35 +++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 54329 bytes gradle/wrapper/gradle-wrapper.properties | 20 ++ gradlew | 172 +++++++++++++ gradlew.bat | 84 +++++++ settings.gradle | 17 ++ start/build.gradle | 90 +++++++ start/proguard-rules.pro | 35 +++ start/src/main/AndroidManifest.xml | 65 +++++ .../example/sleepcodelab/MainActivity.kt | 213 ++++++++++++++++ .../example/sleepcodelab/MainApplication.kt | 43 ++++ .../example/sleepcodelab/MainViewModel.kt | 55 ++++ .../sleepcodelab/data/SleepRepository.kt | 72 ++++++ .../data/datastore/SleepSubscriptionStatus.kt | 49 ++++ .../data/db/SleepClassifyEventDao.kt | 44 ++++ .../data/db/SleepClassifyEventEntity.kt | 54 ++++ .../sleepcodelab/data/db/SleepDatabase.kt | 60 +++++ .../data/db/SleepSegmentEventDao.kt | 44 ++++ .../data/db/SleepSegmentEventEntity.kt | 47 ++++ .../sleepcodelab/receiver/BootReceiver.kt | 109 ++++++++ .../sleepcodelab/receiver/SleepReceiver.kt | 91 +++++++ .../drawable-v24/ic_launcher_foreground.xml | 46 ++++ .../res/drawable/ic_launcher_background.xml | 185 ++++++++++++++ start/src/main/res/layout/activity_main.xml | 59 +++++ .../res/mipmap-anydpi-v26/ic_launcher.xml | 20 ++ .../mipmap-anydpi-v26/ic_launcher_round.xml | 20 ++ .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 3593 bytes .../res/mipmap-hdpi/ic_launcher_round.png | Bin 0 -> 5339 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 2636 bytes .../res/mipmap-mdpi/ic_launcher_round.png | Bin 0 -> 3388 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 4926 bytes .../res/mipmap-xhdpi/ic_launcher_round.png | Bin 0 -> 7472 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 7909 bytes .../res/mipmap-xxhdpi/ic_launcher_round.png | Bin 0 -> 11873 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 10652 bytes .../res/mipmap-xxxhdpi/ic_launcher_round.png | Bin 0 -> 16570 bytes start/src/main/res/values-night/themes.xml | 32 +++ start/src/main/res/values/colors.xml | 25 ++ start/src/main/res/values/strings.xml | 33 +++ start/src/main/res/values/themes.xml | 32 +++ 78 files changed, 3699 insertions(+) create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.gradle create mode 100644 complete/build.gradle create mode 100644 complete/proguard-rules.pro create mode 100644 complete/src/main/AndroidManifest.xml create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/MainActivity.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/MainApplication.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/MainViewModel.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/SleepRepository.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/datastore/SleepSubscriptionStatus.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventDao.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepDatabase.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventDao.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventEntity.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/receiver/BootReceiver.kt create mode 100644 complete/src/main/java/com/android/example/sleepcodelab/receiver/SleepReceiver.kt create mode 100644 complete/src/main/res/drawable-v24/ic_launcher_foreground.xml create mode 100644 complete/src/main/res/drawable/ic_launcher_background.xml create mode 100644 complete/src/main/res/layout/activity_main.xml create mode 100644 complete/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 complete/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 complete/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 complete/src/main/res/mipmap-hdpi/ic_launcher_round.png create mode 100644 complete/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 complete/src/main/res/mipmap-mdpi/ic_launcher_round.png create mode 100644 complete/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 complete/src/main/res/mipmap-xhdpi/ic_launcher_round.png create mode 100644 complete/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 complete/src/main/res/mipmap-xxhdpi/ic_launcher_round.png create mode 100644 complete/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 complete/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png create mode 100644 complete/src/main/res/values-night/themes.xml create mode 100644 complete/src/main/res/values/colors.xml create mode 100644 complete/src/main/res/values/strings.xml create mode 100644 complete/src/main/res/values/themes.xml create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 start/build.gradle create mode 100644 start/proguard-rules.pro create mode 100644 start/src/main/AndroidManifest.xml create mode 100644 start/src/main/java/com/android/example/sleepcodelab/MainActivity.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/MainApplication.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/MainViewModel.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/SleepRepository.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/datastore/SleepSubscriptionStatus.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventDao.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/db/SleepDatabase.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventDao.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventEntity.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/receiver/BootReceiver.kt create mode 100644 start/src/main/java/com/android/example/sleepcodelab/receiver/SleepReceiver.kt create mode 100644 start/src/main/res/drawable-v24/ic_launcher_foreground.xml create mode 100644 start/src/main/res/drawable/ic_launcher_background.xml create mode 100644 start/src/main/res/layout/activity_main.xml create mode 100644 start/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 start/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 start/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 start/src/main/res/mipmap-hdpi/ic_launcher_round.png create mode 100644 start/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 start/src/main/res/mipmap-mdpi/ic_launcher_round.png create mode 100644 start/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 start/src/main/res/mipmap-xhdpi/ic_launcher_round.png create mode 100644 start/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 start/src/main/res/mipmap-xxhdpi/ic_launcher_round.png create mode 100644 start/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 start/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png create mode 100644 start/src/main/res/values-night/themes.xml create mode 100644 start/src/main/res/values/colors.xml create mode 100644 start/src/main/res/values/strings.xml create mode 100644 start/src/main/res/values/themes.xml diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..db177d4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,28 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution; +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +## Community Guidelines + +This project follows +[Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d0ca196 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +Sleep API Codelab Repository +====================== +The Sleep API allows apps to estimate when the user goes to sleep and wakes up. + +This repository is to be used with the Sleep API codelab: +https://codelabs.developers.google.com/codelabs/android-sleep-api + +Documentation on the Sleep APIs can be found here: +https://developers.google.com/location-context/sleep diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..82f2ae1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + ext.kotlin_version = "1.4.21" + repositories { + google() + jcenter() + } + dependencies { + classpath "com.android.tools.build:gradle:4.1.2" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/complete/build.gradle b/complete/build.gradle new file mode 100644 index 0000000..73a3325 --- /dev/null +++ b/complete/build.gradle @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +plugins { + id 'com.android.application' + id 'kotlin-android' + id 'kotlin-kapt' +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + applicationId "com.android.example.sleepsamplekotlin" + minSdkVersion 29 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } + buildFeatures { + viewBinding true + } +} + +dependencies { + + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.core:core-ktx:1.3.2' + implementation 'com.google.android.material:material:1.2.1' + implementation 'androidx.constraintlayout:constraintlayout:2.0.4' + + // Required for new permission APIs + implementation 'androidx.appcompat:appcompat:1.3.0-beta01' + implementation 'androidx.activity:activity-ktx:1.2.0-rc01' + + // Room components + implementation "androidx.room:room-ktx:2.2.6" + implementation 'androidx.room:room-runtime:2.2.6' + kapt "androidx.room:room-compiler:2.2.6" + androidTestImplementation "androidx.room:room-testing:2.2.6" + + // DataStore components + implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06" + + // Lifecycle components + implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" + implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0" + implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0" + implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" + + // Kotlin components + api "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2" + api "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2" + + // TODO: Review play services library required for activity recognition. + implementation 'com.google.android.gms:play-services-location:18.0.0' + + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' +} \ No newline at end of file diff --git a/complete/proguard-rules.pro b/complete/proguard-rules.pro new file mode 100644 index 0000000..a49021a --- /dev/null +++ b/complete/proguard-rules.pro @@ -0,0 +1,35 @@ +# Copyright (C) 2021 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/complete/src/main/AndroidManifest.xml b/complete/src/main/AndroidManifest.xml new file mode 100644 index 0000000..81bc9d7 --- /dev/null +++ b/complete/src/main/AndroidManifest.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/complete/src/main/java/com/android/example/sleepcodelab/MainActivity.kt b/complete/src/main/java/com/android/example/sleepcodelab/MainActivity.kt new file mode 100644 index 0000000..e1aa40e --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/MainActivity.kt @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab + +import android.Manifest.permission +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Bundle +import android.provider.Settings +import android.util.Log +import android.view.View +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import com.android.example.sleepcodelab.databinding.ActivityMainBinding +import com.android.example.sleepcodelab.receiver.SleepReceiver +import com.google.android.gms.location.ActivityRecognition +import com.google.android.gms.location.SleepSegmentRequest +import com.google.android.material.snackbar.Snackbar +import java.util.Calendar + +/** + * Demos Android's Sleep APIs; subscribe/unsubscribe to sleep data, save that data, and display it. + */ +class MainActivity : AppCompatActivity() { + + private lateinit var binding: ActivityMainBinding + + private val mainViewModel: MainViewModel by lazy { + MainViewModel((application as MainApplication).repository) + } + + // Used to construct the output from multiple tables (very basic implementation just to show + // the live data coming in). + private var sleepSegmentOutput: String = "" + private var sleepClassifyOutput: String = "" + + // Status of subscription to sleep data. This is stored in [SleepSubscriptionStatus] which saves + // the data in a [DataStore] in case the user navigates away from the app. + private var subscribedToSleepData = false + set(newSubscribedToSleepData) { + field = newSubscribedToSleepData + if (newSubscribedToSleepData) { + binding.button.text = getString(R.string.sleep_button_unsubscribe_text) + } else { + binding.button.text = getString(R.string.sleep_button_subscribe_text) + } + updateOutput() + } + + private lateinit var sleepPendingIntent: PendingIntent + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + + mainViewModel.subscribedToSleepDataLiveData.observe(this) { newSubscribedToSleepData -> + if (subscribedToSleepData != newSubscribedToSleepData) { + subscribedToSleepData = newSubscribedToSleepData + } + } + + // Adds observers on LiveData from [SleepRepository]. Data is saved to the database via + // [SleepReceiver] and when that data changes, we get notified of changes. + // Note: The data returned is Entity versions of the sleep classes, so they don't contain + // all the data, as I just saved the minimum to show it's being saved. + mainViewModel.allSleepSegments.observe(this) { sleepSegmentEventEntities -> + Log.d(TAG, "sleepSegmentEventEntities: $sleepSegmentEventEntities") + + if (sleepSegmentEventEntities.isNotEmpty()) { + // Constructor isn't accessible for [SleepSegmentEvent], so we just output the + // database table version. + sleepSegmentOutput = sleepSegmentEventEntities.joinToString { + "\t$it\n" + } + updateOutput() + } + } + + mainViewModel.allSleepClassifyEventEntities.observe(this) { + sleepClassifyEventEntities -> + Log.d(TAG, "sleepClassifyEventEntities: $sleepClassifyEventEntities") + + if (sleepClassifyEventEntities.isNotEmpty()) { + // Constructor isn't accessible for [SleepClassifyEvent], so we just output the + // database table version. + sleepClassifyOutput = sleepClassifyEventEntities.joinToString { + "\t$it\n" + } + updateOutput() + } + } + + // TODO: Create a PendingIntent for Sleep API events + sleepPendingIntent = + SleepReceiver.createSleepReceiverPendingIntent(context = applicationContext) + } + + // TODO: Enable/Disable sleep tracking and ask for permissions if needed. + fun onClickRequestSleepData(view: View) { + if (activityRecognitionPermissionApproved()) { + if (subscribedToSleepData) { + unsubscribeToSleepSegmentUpdates(applicationContext, sleepPendingIntent) + } else { + subscribeToSleepSegmentUpdates(applicationContext, sleepPendingIntent) + } + } else { + requestPermissionLauncher.launch(permission.ACTIVITY_RECOGNITION) + } + } + + // Permission is checked before this method is called. + @SuppressLint("MissingPermission") + private fun subscribeToSleepSegmentUpdates(context: Context, pendingIntent: PendingIntent) { + Log.d(TAG, "requestSleepSegmentUpdates()") + // TODO: Request Sleep API updates + val task = ActivityRecognition.getClient(context).requestSleepSegmentUpdates( + pendingIntent, + // Registers for both [SleepSegmentEvent] and [SleepClassifyEvent] data. + SleepSegmentRequest.getDefaultSleepSegmentRequest() + ) + + task.addOnSuccessListener { + mainViewModel.updateSubscribedToSleepData(true) + Log.d(TAG, "Successfully subscribed to sleep data.") + } + task.addOnFailureListener { exception -> + Log.d(TAG, "Exception when subscribing to sleep data: $exception") + } + } + + private fun unsubscribeToSleepSegmentUpdates(context: Context, pendingIntent: PendingIntent) { + Log.d(TAG, "unsubscribeToSleepSegmentUpdates()") + val task = ActivityRecognition.getClient(context).removeSleepSegmentUpdates(pendingIntent) + + task.addOnSuccessListener { + mainViewModel.updateSubscribedToSleepData(false) + Log.d(TAG, "Successfully unsubscribed to sleep data.") + } + task.addOnFailureListener { exception -> + Log.d(TAG, "Exception when unsubscribing to sleep data: $exception") + } + } + + // TODO: Review Activity Recognition permission checking. + private fun activityRecognitionPermissionApproved(): Boolean { + // Because this app targets 29 and above (recommendation for using the Sleep APIs), we + // don't need to check if this is on a device before runtime permissions, that is, a device + // prior to 29 / Q. + return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission( + this, + permission.ACTIVITY_RECOGNITION + ) + } + + private val requestPermissionLauncher: ActivityResultLauncher = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> + if (!isGranted) { + // Permission denied on Android platform that supports runtime permissions. + displayPermissionSettingsSnackBar() + } else { + // Permission was granted (either by approval or Android version below Q). + binding.outputTextView.text = getString(R.string.permission_approved) + } + } + + private fun displayPermissionSettingsSnackBar() { + Snackbar.make( + binding.mainActivity, + R.string.permission_rational, + Snackbar.LENGTH_LONG + ) + .setAction(R.string.action_settings) { + // Build intent that displays the App settings screen. + val intent = Intent() + intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS + val uri = Uri.fromParts( + "package", + BuildConfig.APPLICATION_ID, + null + ) + intent.data = uri + intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK + startActivity(intent) + } + .show() + } + + /** + * Redimentary implementation of the output from multiple tables. The [LiveData] observers just + * save their data to one of the strings (segmentOutput or classifyOutput) and triggers this + * function. + */ + private fun updateOutput() { + Log.d(TAG, "updateOutput()") + + val header = if (subscribedToSleepData) { + val timestamp = Calendar.getInstance().time.toString() + getString(R.string.main_output_header1_subscribed_sleep_data, timestamp) + } else { + getString(R.string.main_output_header1_unsubscribed_sleep_data) + } + + val sleepData = getString( + R.string.main_output_header2_and_sleep_data, + sleepSegmentOutput, + sleepClassifyOutput + ) + + val newOutput = header + sleepData + binding.outputTextView.text = newOutput + } + + companion object { + private const val TAG = "MainActivity" + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/MainApplication.kt b/complete/src/main/java/com/android/example/sleepcodelab/MainApplication.kt new file mode 100644 index 0000000..5813e6f --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/MainApplication.kt @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab + +import android.app.Application +import androidx.datastore.preferences.createDataStore +import com.android.example.sleepcodelab.data.SleepRepository +import com.android.example.sleepcodelab.data.datastore.SLEEP_PREFERENCES_NAME +import com.android.example.sleepcodelab.data.datastore.SleepSubscriptionStatus +import com.android.example.sleepcodelab.data.db.SleepDatabase + +/** + * Sets up repository for all sleep data. + */ +class MainApplication : Application() { + // Both database and repository use lazy so they aren't created when the app starts, but only + // when repository is first needed. + private val database by lazy { + SleepDatabase.getDatabase(applicationContext) + } + + val repository by lazy { + SleepRepository( + sleepSubscriptionStatus = SleepSubscriptionStatus( + applicationContext.createDataStore(name = SLEEP_PREFERENCES_NAME)), + sleepSegmentEventDao = database.sleepSegmentEventDao(), + sleepClassifyEventDao = database.sleepClassifyEventDao() + ) + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/MainViewModel.kt b/complete/src/main/java/com/android/example/sleepcodelab/MainViewModel.kt new file mode 100644 index 0000000..66dea2c --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/MainViewModel.kt @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab + +import androidx.lifecycle.LiveData +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.asLiveData +import androidx.lifecycle.viewModelScope +import com.android.example.sleepcodelab.data.SleepRepository +import com.android.example.sleepcodelab.data.db.SleepClassifyEventEntity +import com.android.example.sleepcodelab.data.db.SleepSegmentEventEntity +import kotlinx.coroutines.launch + +class MainViewModel(private val repository: SleepRepository) : ViewModel() { + + val subscribedToSleepDataLiveData = repository.subscribedToSleepDataFlow.asLiveData() + + fun updateSubscribedToSleepData(subscribed: Boolean) = viewModelScope.launch { + repository.updateSubscribedToSleepData(subscribed) + } + + // Using LiveData and caching what allWords returns has several benefits: + // - We can put an observer on the data (instead of polling for changes) and only update the + // UI when the data actually changes. + // - Repository is completely separated from the UI through the ViewModel. + val allSleepSegments: LiveData> = + repository.allSleepSegmentEvents.asLiveData() + + val allSleepClassifyEventEntities: LiveData> = + repository.allSleepClassifyEvents.asLiveData() +} + +class MainViewModelFactory(private val repository: SleepRepository) : ViewModelProvider.Factory { + override fun create(modelClass: Class): T { + if (modelClass.isAssignableFrom(MainViewModel::class.java)) { + @Suppress("UNCHECKED_CAST") + return MainViewModel(repository) as T + } + throw IllegalArgumentException("Unknown ViewModel class") + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/SleepRepository.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/SleepRepository.kt new file mode 100644 index 0000000..34880f8 --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/SleepRepository.kt @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data + +import com.android.example.sleepcodelab.data.datastore.SleepSubscriptionStatus +import com.android.example.sleepcodelab.data.db.SleepClassifyEventDao +import com.android.example.sleepcodelab.data.db.SleepClassifyEventEntity +import com.android.example.sleepcodelab.data.db.SleepSegmentEventDao +import com.android.example.sleepcodelab.data.db.SleepSegmentEventEntity +import kotlinx.coroutines.flow.Flow + +class SleepRepository( + private val sleepSubscriptionStatus: SleepSubscriptionStatus, + private val sleepSegmentEventDao: SleepSegmentEventDao, + private val sleepClassifyEventDao: SleepClassifyEventDao +) { + + // Methods for SleepSubscriptionStatus + // Uses [DataStore] to save the subscription to sleep data status. This is used to check if the + // app is still listening to changes in sleep data when the app is brought back into + // the foreground. + val subscribedToSleepDataFlow: Flow = sleepSubscriptionStatus.subscribedToSleepDataFlow + + suspend fun updateSubscribedToSleepData(subscribedToSleepData: Boolean) = + sleepSubscriptionStatus.updateSubscribedToSleepData(subscribedToSleepData) + + // Methods for SleepSegmentEventDao + // Room executes all queries on a separate thread. + // Observed Flow will notify the observer when the data has changed. + val allSleepSegmentEvents: Flow> = + sleepSegmentEventDao.getAll() + + // By default Room runs suspend queries off the main thread. Therefore, we don't need to + // implement anything else to ensure we're not doing long-running database work off the + // main thread. + suspend fun insertSleepSegment(sleepSegmentEventEntity: SleepSegmentEventEntity) { + sleepSegmentEventDao.insert(sleepSegmentEventEntity) + } + + // By default Room runs suspend queries off the main thread. Therefore, we don't need to + // implement anything else to ensure we're not doing long-running database work off the + // main thread. + suspend fun insertSleepSegments(sleepSegmentEventEntities: List) { + sleepSegmentEventDao.insertAll(sleepSegmentEventEntities) + } + + // Methods for SleepClassifyEventDao + // Observed Flow will notify the observer when the data has changed. + val allSleepClassifyEvents: Flow> = + sleepClassifyEventDao.getAll() + + suspend fun insertSleepClassifyEvent(sleepClassifyEventEntity: SleepClassifyEventEntity) { + sleepClassifyEventDao.insert(sleepClassifyEventEntity) + } + + suspend fun insertSleepClassifyEvents(sleepClassifyEventEntities: List) { + sleepClassifyEventDao.insertAll(sleepClassifyEventEntities) + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/datastore/SleepSubscriptionStatus.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/datastore/SleepSubscriptionStatus.kt new file mode 100644 index 0000000..9deefa3 --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/datastore/SleepSubscriptionStatus.kt @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data.datastore + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map + +const val SLEEP_PREFERENCES_NAME = "sleep_preferences" + +/** + * Saves the sleep data subscription status into a [DataStore]. + * Used to check if the app is still listening to changes in sleep data when the app is brought + * back into the foreground. + */ +class SleepSubscriptionStatus(private val dataStore: DataStore) { + + private object PreferencesKeys { + val SUBSCRIBED_TO_SLEEP_DATA = booleanPreferencesKey("subscribed_to_sleep_data") + } + // Observed Flow will notify the observer when the the sleep subscription status has changed. + val subscribedToSleepDataFlow: Flow = dataStore.data.map { preferences -> + // Get the subscription value, defaults to false if not set: + preferences[PreferencesKeys.SUBSCRIBED_TO_SLEEP_DATA] ?: false + } + + // Updates subscription status. + suspend fun updateSubscribedToSleepData(subscribedToSleepData: Boolean) { + dataStore.edit { preferences -> + preferences[PreferencesKeys.SUBSCRIBED_TO_SLEEP_DATA] = subscribedToSleepData + } + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventDao.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventDao.kt new file mode 100644 index 0000000..69ab6b2 --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventDao.kt @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data.db + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import kotlinx.coroutines.flow.Flow + +/** + * Defines [SleepClassifyEventEntity] database operations. + */ +@Dao +interface SleepClassifyEventDao { + @Query("SELECT * FROM sleep_classify_events_table ORDER BY time_stamp_seconds DESC") + fun getAll(): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insert(sleepClassifyEventEntity: SleepClassifyEventEntity) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertAll(sleepClassifyEventEntities: List) + + @Delete + suspend fun delete(sleepClassifyEventEntity: SleepClassifyEventEntity) + + @Query("DELETE FROM sleep_classify_events_table") + suspend fun deleteAll() +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt new file mode 100644 index 0000000..b39a6fe --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data.db + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.google.android.gms.location.SleepClassifyEvent + +/** + * Entity class (table version of the class) for [SleepClassifyEvent] which represents a sleep + * classification event including the classification timestamp, the sleep confidence, and the + * supporting data such as device motion and ambient light level. Classification events are + * reported regularly. + */ +@Entity(tableName = "sleep_classify_events_table") +data class SleepClassifyEventEntity( + @PrimaryKey + @ColumnInfo(name = "time_stamp_seconds") + val timestampSeconds: Int, + + @ColumnInfo(name = "confidence") + val confidence: Int, + + @ColumnInfo(name = "motion") + val motion: Int, + + @ColumnInfo(name = "light") + val light: Int +) { + companion object { + fun from(sleepClassifyEvent: SleepClassifyEvent): SleepClassifyEventEntity { + return SleepClassifyEventEntity( + timestampSeconds = (sleepClassifyEvent.timestampMillis / 1000).toInt(), + confidence = sleepClassifyEvent.confidence, + motion = sleepClassifyEvent.motion, + light = sleepClassifyEvent.light + ) + } + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepDatabase.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepDatabase.kt new file mode 100644 index 0000000..da93217 --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepDatabase.kt @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data.db + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase + +private const val DATABASE_NAME = "sleep_segments_database" + +/** + * Stores all sleep segment data. + */ +@Database( + entities = [SleepSegmentEventEntity::class, SleepClassifyEventEntity::class], + version = 3, + exportSchema = false +) +abstract class SleepDatabase : RoomDatabase() { + + abstract fun sleepSegmentEventDao(): SleepSegmentEventDao + abstract fun sleepClassifyEventDao(): SleepClassifyEventDao + + companion object { + // For Singleton instantiation + @Volatile + private var INSTANCE: SleepDatabase? = null + + fun getDatabase(context: Context): SleepDatabase { + return INSTANCE ?: synchronized(this) { + val instance = Room.databaseBuilder( + context, + SleepDatabase::class.java, + DATABASE_NAME + ) + // Wipes and rebuilds instead of migrating if no Migration object. + // Migration is not part of this sample. + .fallbackToDestructiveMigration() + .build() + INSTANCE = instance + // return instance + instance + } + } + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventDao.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventDao.kt new file mode 100644 index 0000000..598f66a --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventDao.kt @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data.db + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import kotlinx.coroutines.flow.Flow + +/** + * Defines [SleepSegmentEventEntity] database operations. + */ +@Dao +interface SleepSegmentEventDao { + @Query("SELECT * FROM sleep_segment_events_table ORDER BY start_time_millis DESC") + fun getAll(): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insert(sleepSegmentEventEntity: SleepSegmentEventEntity) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertAll(sleepSegmentEventEntities: List) + + @Delete + suspend fun delete(sleepSegmentEventEntity: SleepSegmentEventEntity) + + @Query("DELETE FROM sleep_segment_events_table") + suspend fun deleteAll() +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventEntity.kt b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventEntity.kt new file mode 100644 index 0000000..bac0ffc --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/data/db/SleepSegmentEventEntity.kt @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.data.db + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.google.android.gms.location.SleepSegmentEvent + +/** + * Data class for Sleep Segment Events which represents the time the user slept at night. + */ +@Entity(tableName = "sleep_segment_events_table") +data class SleepSegmentEventEntity( + @PrimaryKey + @ColumnInfo(name = "start_time_millis") + val startTimeMillis: Long, + + @ColumnInfo(name = "end_time_millis") + val endTimeMillis: Long, + + @ColumnInfo(name = "status") + val status: Int +) { + companion object { + fun from(sleepSegmentEvent: SleepSegmentEvent): SleepSegmentEventEntity { + return SleepSegmentEventEntity( + startTimeMillis = sleepSegmentEvent.startTimeMillis, + endTimeMillis = sleepSegmentEvent.endTimeMillis, + status = sleepSegmentEvent.status + ) + } + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/receiver/BootReceiver.kt b/complete/src/main/java/com/android/example/sleepcodelab/receiver/BootReceiver.kt new file mode 100644 index 0000000..0c834c4 --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/receiver/BootReceiver.kt @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.receiver + +import android.Manifest +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.util.Log +import androidx.core.content.ContextCompat +import com.android.example.sleepcodelab.MainApplication +import com.android.example.sleepcodelab.data.SleepRepository +import com.google.android.gms.location.ActivityRecognition +import com.google.android.gms.location.SleepSegmentRequest +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch + +/** + * Resubscribes to Sleep data if the device is rebooted. + */ +class BootReceiver : BroadcastReceiver() { + + // Used to launch coroutines (non-blocking way to insert data). + private val scope: CoroutineScope = MainScope() + + override fun onReceive(context: Context, intent: Intent) { + Log.d(TAG, "onReceive action: " + intent.action) + + val repository: SleepRepository = (context.applicationContext as MainApplication).repository + + scope.launch { + // TODO: Request Sleep API upon boot complete + val subscribedToSleepData = repository.subscribedToSleepDataFlow.first() + if (subscribedToSleepData) { + subscribeToSleepSegmentUpdates( + context = context, + pendingIntent = SleepReceiver.createSleepReceiverPendingIntent(context) + ) + } + } + } + + /** + * Subscribes to sleep data. + * Note: Permission isn't missing, it's in the manifest but only for 29+ version. The lint + * check is the 28 and below version of the activity recognition permission (needed for + * accessing sleep data). + */ + @SuppressLint("MissingPermission") + private fun subscribeToSleepSegmentUpdates(context: Context, pendingIntent: PendingIntent) { + Log.d(TAG, "subscribeToSleepSegmentUpdates()") + if (activityRecognitionPermissionApproved(context)) { + val task = + ActivityRecognition.getClient(context).requestSleepSegmentUpdates( + pendingIntent, + // Registers for both [SleepSegmentEvent] and [SleepClassifyEvent] data. + SleepSegmentRequest.getDefaultSleepSegmentRequest() + ) + + task.addOnSuccessListener { + Log.d(TAG, "Successfully subscribed to sleep data from boot.") + } + task.addOnFailureListener { exception -> + Log.d(TAG, "Exception when subscribing to sleep data from boot: $exception") + val repository = (context.applicationContext as MainApplication).repository + unsubscribeStatusForSleepData(repository) + } + } else { + Log.d(TAG, "Failed to subscribed to sleep data from boot; Permission removed.") + val repository = (context.applicationContext as MainApplication).repository + unsubscribeStatusForSleepData(repository) + } + } + + /** + * Updates the app's boolean for sleep subscription status. + * + * Note: This happens because an exception occurred or the permission was removed, so the app + * is no longer subscribed to sleep data. + */ + private fun unsubscribeStatusForSleepData(repository: SleepRepository) = scope.launch { + repository.updateSubscribedToSleepData(false) + } + + private fun activityRecognitionPermissionApproved(context: Context): Boolean { + // Because this app targets 29 and above (recommendation for using the Sleep APIs), we + // don't need to check if this is on a device before runtime permissions, that is, a device + // prior to 29 / Q. + return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission( + context, + Manifest.permission.ACTIVITY_RECOGNITION + ) + } + + companion object { + const val TAG = "BootReceiver" + } +} diff --git a/complete/src/main/java/com/android/example/sleepcodelab/receiver/SleepReceiver.kt b/complete/src/main/java/com/android/example/sleepcodelab/receiver/SleepReceiver.kt new file mode 100644 index 0000000..e64ed7a --- /dev/null +++ b/complete/src/main/java/com/android/example/sleepcodelab/receiver/SleepReceiver.kt @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.example.sleepcodelab.receiver + +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.util.Log +import com.android.example.sleepcodelab.MainApplication +import com.android.example.sleepcodelab.data.SleepRepository +import com.android.example.sleepcodelab.data.db.SleepClassifyEventEntity +import com.android.example.sleepcodelab.data.db.SleepSegmentEventEntity +import com.google.android.gms.location.SleepClassifyEvent +import com.google.android.gms.location.SleepSegmentEvent +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.launch + +/** + * Saves Sleep Events to Database. + */ +class SleepReceiver : BroadcastReceiver() { + + // Used to launch coroutines (non-blocking way to insert data). + private val scope: CoroutineScope = MainScope() + + override fun onReceive(context: Context, intent: Intent) { + Log.d(TAG, "onReceive(): $intent") + + val repository: SleepRepository = (context.applicationContext as MainApplication).repository + + // TODO: Extract sleep information from PendingIntent. + if (SleepSegmentEvent.hasEvents(intent)) { + val sleepSegmentEvents: List = + SleepSegmentEvent.extractEvents(intent) + Log.d(TAG, "SleepSegmentEvent List: $sleepSegmentEvents") + addSleepSegmentEventsToDatabase(repository, sleepSegmentEvents) + } else if (SleepClassifyEvent.hasEvents(intent)) { + val sleepClassifyEvents: List = + SleepClassifyEvent.extractEvents(intent) + Log.d(TAG, "SleepClassifyEvent List: $sleepClassifyEvents") + addSleepClassifyEventsToDatabase(repository, sleepClassifyEvents) + } + } + + private fun addSleepSegmentEventsToDatabase( + repository: SleepRepository, + sleepSegmentEvents: List + ) { + if (sleepSegmentEvents.isNotEmpty()) { + scope.launch { + val convertedToEntityVersion: List = + sleepSegmentEvents.map { + SleepSegmentEventEntity.from(it) + } + repository.insertSleepSegments(convertedToEntityVersion) + } + } + } + + private fun addSleepClassifyEventsToDatabase( + repository: SleepRepository, + sleepClassifyEvents: List + ) { + if (sleepClassifyEvents.isNotEmpty()) { + scope.launch { + val convertedToEntityVersion: List = + sleepClassifyEvents.map { + SleepClassifyEventEntity.from(it) + } + repository.insertSleepClassifyEvents(convertedToEntityVersion) + } + } + } + + companion object { + const val TAG = "SleepReceiver" + fun createSleepReceiverPendingIntent(context: Context): PendingIntent { + val sleepIntent = Intent(context, SleepReceiver::class.java) + return PendingIntent.getBroadcast( + context, + 0, + sleepIntent, + PendingIntent.FLAG_CANCEL_CURRENT + ) + } + } +} diff --git a/complete/src/main/res/drawable-v24/ic_launcher_foreground.xml b/complete/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..e23895a --- /dev/null +++ b/complete/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + diff --git a/complete/src/main/res/drawable/ic_launcher_background.xml b/complete/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..b6ea9e0 --- /dev/null +++ b/complete/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/complete/src/main/res/layout/activity_main.xml b/complete/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..92f1568 --- /dev/null +++ b/complete/src/main/res/layout/activity_main.xml @@ -0,0 +1,59 @@ + + + + + + + + + +