├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── base
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── example
│ │ └── android
│ │ └── whileinuselocation
│ │ ├── ForegroundOnlyLocationService.kt
│ │ ├── MainActivity.kt
│ │ └── Utils.kt
│ └── res
│ ├── drawable-hdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-mdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-xhdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-xxhdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-xxxhdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable
│ └── background_border.xml
│ ├── layout
│ └── activity_main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── complete
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── example
│ │ └── android
│ │ └── whileinuselocation
│ │ ├── ForegroundOnlyLocationService.kt
│ │ ├── MainActivity.kt
│ │ └── Utils.kt
│ └── res
│ ├── drawable-hdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-mdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-xhdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-xxhdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable-xxxhdpi
│ ├── ic_cancel.png
│ └── ic_launch.png
│ ├── drawable
│ └── background_border.xml
│ ├── layout
│ └── activity_main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Mac files
6 | .DS_Store
7 |
8 | # files for the dex VM
9 | *.dex
10 |
11 | # Java class files
12 | *.class
13 |
14 | # generated files
15 | bin/
16 | gen/
17 |
18 | # Ignore gradle files
19 | .gradle/
20 | build/
21 |
22 | # Local configuration file (sdk path, etc)
23 | local.properties
24 |
25 | # Proguard folder generated by Eclipse
26 | proguard/
27 | proguard-project.txt
28 |
29 | # Eclipse files
30 | .project
31 | .classpath
32 | .settings/
33 |
34 | # Android Studio/IDEA
35 | *.iml
36 | .idea
37 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to become a contributor and submit your own code
2 |
3 | ## Contributor License Agreements
4 |
5 | We'd love to accept your sample apps and patches! Before we can take them, we
6 | have to jump a couple of legal hurdles.
7 |
8 | Please fill out either the individual or corporate Contributor License Agreement
9 | (CLA).
10 |
11 | * If you are an individual writing original source code and you're sure you
12 | own the intellectual property, then you'll need to sign an [individual CLA]
13 | (https://developers.google.com/open-source/cla/individual).
14 | * If you work for a company that wants to allow you to contribute your work,
15 | then you'll need to sign a [corporate CLA]
16 | (https://developers.google.com/open-source/cla/corporate).
17 |
18 | Follow either of the two links above to access the appropriate CLA and
19 | instructions for how to sign and return it. Once we receive it, we'll be able to
20 | accept your pull requests.
21 |
22 | ## Contributing A Patch
23 |
24 | 1. Submit an issue describing your proposed change to the repo in question.
25 | 2. The repo owner will respond to your issue promptly.
26 | 3. If your proposed change is accepted, and you haven't already done so, sign a
27 | Contributor License Agreement (see details above).
28 | 4. Fork the desired repo, develop and test your code changes.
29 | 5. Ensure that your code adheres to the existing style in the sample to which
30 | you are contributing. Refer to the
31 | [Google Cloud Platform Samples Style Guide]
32 | (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the
33 | recommended coding standards for this organization.
34 | 6. Ensure that your code has an appropriate set of unit tests which all pass.
35 | 7. Submit a pull request.
36 |
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Version 2.0, January 2004
2 | http://www.apache.org/licenses/
3 |
4 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5 |
6 | 1. Definitions.
7 |
8 | "License" shall mean the terms and conditions for use, reproduction,
9 | and distribution as defined by Sections 1 through 9 of this document.
10 |
11 | "Licensor" shall mean the copyright owner or entity authorized by
12 | the copyright owner that is granting the License.
13 |
14 | "Legal Entity" shall mean the union of the acting entity and all
15 | other entities that control, are controlled by, or are under common
16 | control with that entity. For the purposes of this definition,
17 | "control" means (i) the power, direct or indirect, to cause the
18 | direction or management of such entity, whether by contract or
19 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 | outstanding shares, or (iii) beneficial ownership of such entity.
21 |
22 | "You" (or "Your") shall mean an individual or Legal Entity
23 | exercising permissions granted by this License.
24 |
25 | "Source" form shall mean the preferred form for making modifications,
26 | including but not limited to software source code, documentation
27 | source, and configuration files.
28 |
29 | "Object" form shall mean any form resulting from mechanical
30 | transformation or translation of a Source form, including but
31 | not limited to compiled object code, generated documentation,
32 | and conversions to other media types.
33 |
34 | "Work" shall mean the work of authorship, whether in Source or
35 | Object form, made available under the License, as indicated by a
36 | copyright notice that is included in or attached to the work
37 | (an example is provided in the Appendix below).
38 |
39 | "Derivative Works" shall mean any work, whether in Source or Object
40 | form, that is based on (or derived from) the Work and for which the
41 | editorial revisions, annotations, elaborations, or other modifications
42 | represent, as a whole, an original work of authorship. For the purposes
43 | of this License, Derivative Works shall not include works that remain
44 | separable from, or merely link (or bind by name) to the interfaces of,
45 | the Work and Derivative Works thereof.
46 |
47 | "Contribution" shall mean any work of authorship, including
48 | the original version of the Work and any modifications or additions
49 | to that Work or Derivative Works thereof, that is intentionally
50 | submitted to Licensor for inclusion in the Work by the copyright owner
51 | or by an individual or Legal Entity authorized to submit on behalf of
52 | the copyright owner. For the purposes of this definition, "submitted"
53 | means any form of electronic, verbal, or written communication sent
54 | to the Licensor or its representatives, including but not limited to
55 | communication on electronic mailing lists, source code control systems,
56 | and issue tracking systems that are managed by, or on behalf of, the
57 | Licensor for the purpose of discussing and improving the Work, but
58 | excluding communication that is conspicuously marked or otherwise
59 | designated in writing by the copyright owner as "Not a Contribution."
60 |
61 | "Contributor" shall mean Licensor and any individual or Legal Entity
62 | on behalf of whom a Contribution has been received by Licensor and
63 | subsequently incorporated within the Work.
64 |
65 | 2. Grant of Copyright License. Subject to the terms and conditions of
66 | this License, each Contributor hereby grants to You a perpetual,
67 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68 | copyright license to reproduce, prepare Derivative Works of,
69 | publicly display, publicly perform, sublicense, and distribute the
70 | Work and such Derivative Works in Source or Object form.
71 |
72 | 3. Grant of Patent License. Subject to the terms and conditions of
73 | this License, each Contributor hereby grants to You a perpetual,
74 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75 | (except as stated in this section) patent license to make, have made,
76 | use, offer to sell, sell, import, and otherwise transfer the Work,
77 | where such license applies only to those patent claims licensable
78 | by such Contributor that are necessarily infringed by their
79 | Contribution(s) alone or by combination of their Contribution(s)
80 | with the Work to which such Contribution(s) was submitted. If You
81 | institute patent litigation against any entity (including a
82 | cross-claim or counterclaim in a lawsuit) alleging that the Work
83 | or a Contribution incorporated within the Work constitutes direct
84 | or contributory patent infringement, then any patent licenses
85 | granted to You under this License for that Work shall terminate
86 | as of the date such litigation is filed.
87 |
88 | 4. Redistribution. You may reproduce and distribute copies of the
89 | Work or Derivative Works thereof in any medium, with or without
90 | modifications, and in Source or Object form, provided that You
91 | meet the following conditions:
92 |
93 | (a) You must give any other recipients of the Work or
94 | Derivative Works a copy of this License; and
95 |
96 | (b) You must cause any modified files to carry prominent notices
97 | stating that You changed the files; and
98 |
99 | (c) You must retain, in the Source form of any Derivative Works
100 | that You distribute, all copyright, patent, trademark, and
101 | attribution notices from the Source form of the Work,
102 | excluding those notices that do not pertain to any part of
103 | the Derivative Works; and
104 |
105 | (d) If the Work includes a "NOTICE" text file as part of its
106 | distribution, then any Derivative Works that You distribute must
107 | include a readable copy of the attribution notices contained
108 | within such NOTICE file, excluding those notices that do not
109 | pertain to any part of the Derivative Works, in at least one
110 | of the following places: within a NOTICE text file distributed
111 | as part of the Derivative Works; within the Source form or
112 | documentation, if provided along with the Derivative Works; or,
113 | within a display generated by the Derivative Works, if and
114 | wherever such third-party notices normally appear. The contents
115 | of the NOTICE file are for informational purposes only and
116 | do not modify the License. You may add Your own attribution
117 | notices within Derivative Works that You distribute, alongside
118 | or as an addendum to the NOTICE text from the Work, provided
119 | that such additional attribution notices cannot be construed
120 | as modifying the License.
121 |
122 | You may add Your own copyright statement to Your modifications and
123 | may provide additional or different license terms and conditions
124 | for use, reproduction, or distribution of Your modifications, or
125 | for any such Derivative Works as a whole, provided Your use,
126 | reproduction, and distribution of the Work otherwise complies with
127 | the conditions stated in this License.
128 |
129 | 5. Submission of Contributions. Unless You explicitly state otherwise,
130 | any Contribution intentionally submitted for inclusion in the Work
131 | by You to the Licensor shall be under the terms and conditions of
132 | this License, without any additional terms or conditions.
133 | Notwithstanding the above, nothing herein shall supersede or modify
134 | the terms of any separate license agreement you may have executed
135 | with Licensor regarding such Contributions.
136 |
137 | 6. Trademarks. This License does not grant permission to use the trade
138 | names, trademarks, service marks, or product names of the Licensor,
139 | except as required for reasonable and customary use in describing the
140 | origin of the Work and reproducing the content of the NOTICE file.
141 |
142 | 7. Disclaimer of Warranty. Unless required by applicable law or
143 | agreed to in writing, Licensor provides the Work (and each
144 | Contributor provides its Contributions) on an "AS IS" BASIS,
145 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146 | implied, including, without limitation, any warranties or conditions
147 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148 | PARTICULAR PURPOSE. You are solely responsible for determining the
149 | appropriateness of using or redistributing the Work and assume any
150 | risks associated with Your exercise of permissions under this License.
151 |
152 | 8. Limitation of Liability. In no event and under no legal theory,
153 | whether in tort (including negligence), contract, or otherwise,
154 | unless required by applicable law (such as deliberate and grossly
155 | negligent acts) or agreed to in writing, shall any Contributor be
156 | liable to You for damages, including any direct, indirect, special,
157 | incidental, or consequential damages of any character arising as a
158 | result of this License or out of the use or inability to use the
159 | Work (including but not limited to damages for loss of goodwill,
160 | work stoppage, computer failure or malfunction, or any and all
161 | other commercial damages or losses), even if such Contributor
162 | has been advised of the possibility of such damages.
163 |
164 | 9. Accepting Warranty or Additional Liability. While redistributing
165 | the Work or Derivative Works thereof, You may choose to offer,
166 | and charge a fee for, acceptance of support, warranty, indemnity,
167 | or other liability obligations and/or rights consistent with this
168 | License. However, in accepting such obligations, You may act only
169 | on Your own behalf and on Your sole responsibility, not on behalf
170 | of any other Contributor, and only if You agree to indemnify,
171 | defend, and hold each Contributor harmless for any liability
172 | incurred by, or claims asserted against, such Contributor by reason
173 | of your accepting any such warranty or additional liability.
174 |
175 | END OF TERMS AND CONDITIONS
176 |
177 | Copyright 2019 Google LLC
178 |
179 | Licensed under the Apache License, Version 2.0 (the "License");
180 | you may not use this file except in compliance with the License.
181 | You may obtain a copy of the License at
182 |
183 | http://www.apache.org/licenses/LICENSE-2.0
184 |
185 | Unless required by applicable law or agreed to in writing, software
186 | distributed under the License is distributed on an "AS IS" BASIS,
187 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
188 | See the License for the specific language governing permissions and
189 | limitations under the License.
190 |
191 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | While-in-use Location Codelab Repository
2 | ===============================
3 |
4 | This repository is to be used with the while-in-use location codelab:
5 | https://developers.google.com/codelabs/while-in-use-location
6 |
7 | It teaches you how to handle new location permissions added in Android 10.
8 |
9 | Documentation on while-in-use location:
10 | https://developer.android.com/preview/privacy/device-location
11 |
12 | License
13 | -------
14 |
15 | Copyright 2019 Google, Inc.
16 |
17 | Licensed to the Apache Software Foundation (ASF) under one or more contributor
18 | license agreements. See the NOTICE file distributed with this work for
19 | additional information regarding copyright ownership. The ASF licenses this
20 | file to you under the Apache License, Version 2.0 (the "License"); you may not
21 | use this file except in compliance with the License. You may obtain a copy of
22 | the License at
23 |
24 | http://www.apache.org/licenses/LICENSE-2.0
25 |
26 | Unless required by applicable law or agreed to in writing, software
27 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
28 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
29 | License for the specific language governing permissions and limitations under
30 | the License.
31 |
--------------------------------------------------------------------------------
/base/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/base/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | apply plugin: 'com.android.application'
17 | apply plugin: 'kotlin-android'
18 |
19 | android {
20 | // TODO: Step 2.1, Target Android 10 and then Android 11.
21 | compileSdkVersion 32
22 | defaultConfig {
23 | applicationId "com.example.android.whileinuselocation"
24 | minSdkVersion 26
25 | targetSdkVersion 32
26 | versionCode 1
27 | versionName "1.0"
28 | }
29 | buildTypes {
30 | release {
31 | minifyEnabled false
32 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
33 | }
34 | }
35 |
36 | compileOptions {
37 | sourceCompatibility JavaVersion.VERSION_1_8
38 | targetCompatibility JavaVersion.VERSION_1_8
39 | }
40 |
41 | kotlinOptions {
42 | jvmTarget = JavaVersion.VERSION_1_8.toString()
43 | }
44 |
45 | buildFeatures {
46 | viewBinding true
47 | }
48 | }
49 |
50 | dependencies {
51 | implementation fileTree(dir: 'libs', include: ['*.jar'])
52 | implementation 'androidx.appcompat:appcompat:1.4.1'
53 | implementation 'androidx.core:core-ktx:1.7.0'
54 | implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
55 | implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.1.0'
56 |
57 | implementation 'com.google.android.gms:play-services-location:19.0.1'
58 |
59 | implementation 'com.google.android.material:material:1.5.0'
60 | }
61 |
--------------------------------------------------------------------------------
/base/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Copyright 2019 Google LLC
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # https://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | # Add project specific ProGuard rules here.
16 | # You can control the set of applied configuration files using the
17 | # proguardFiles setting in build.gradle.
18 | #
19 | # For more details, see
20 | # http://developer.android.com/guide/developing/tools/proguard.html
21 | #
22 | # Add project specific ProGuard rules here.
23 | # You can control the set of applied configuration files using the
24 | # proguardFiles setting in build.gradle.
25 | #
26 | # For more details, see
27 | # http://developer.android.com/guide/developing/tools/proguard.html
28 |
29 | # If your project uses WebView with JS, uncomment the following
30 | # and specify the fully qualified class name to the JavaScript interface
31 | # class:
32 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
33 | # public *;
34 | #}
35 |
36 | # Uncomment this to preserve the line number information for
37 | # debugging stack traces.
38 | #-keepattributes SourceFile,LineNumberTable
39 |
40 | # If you keep the line number information, uncomment this to
41 | # hide the original source file name.
42 | #-renamesourcefileattribute SourceFile
43 |
--------------------------------------------------------------------------------
/base/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
20 |
21 |
22 |
23 |
24 |
25 |
27 |
28 |
34 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/base/src/main/java/com/example/android/whileinuselocation/ForegroundOnlyLocationService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.android.whileinuselocation
17 |
18 | import android.app.Notification
19 | import android.app.NotificationChannel
20 | import android.app.NotificationManager
21 | import android.app.PendingIntent
22 | import android.app.Service
23 | import android.content.Context
24 | import android.content.Intent
25 | import android.content.res.Configuration
26 | import android.location.Location
27 | import android.os.Binder
28 | import android.os.Build
29 | import android.os.IBinder
30 | import android.os.Looper
31 | import android.util.Log
32 | import androidx.core.app.NotificationCompat
33 | import androidx.localbroadcastmanager.content.LocalBroadcastManager
34 | import com.google.android.gms.location.FusedLocationProviderClient
35 | import com.google.android.gms.location.LocationCallback
36 | import com.google.android.gms.location.LocationRequest
37 | import com.google.android.gms.location.LocationResult
38 | import com.google.android.gms.location.LocationServices
39 | import java.util.concurrent.TimeUnit
40 |
41 | /**
42 | * Service tracks location when requested and updates Activity via binding. If Activity is
43 | * stopped/unbinds and tracking is enabled, the service promotes itself to a foreground service to
44 | * insure location updates aren't interrupted.
45 | *
46 | * For apps running in the background on O+ devices, location is computed much less than previous
47 | * versions. Please reference documentation for details.
48 | */
49 | class ForegroundOnlyLocationService : Service() {
50 | /*
51 | * Checks whether the bound activity has really gone away (foreground service with notification
52 | * created) or simply orientation change (no-op).
53 | */
54 | private var configurationChange = false
55 |
56 | private var serviceRunningInForeground = false
57 |
58 | private val localBinder = LocalBinder()
59 |
60 | private lateinit var notificationManager: NotificationManager
61 |
62 | // TODO: Step 1.1, Review variables (no changes).
63 | // FusedLocationProviderClient - Main class for receiving location updates.
64 | private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
65 |
66 | // LocationRequest - Requirements for the location updates, i.e., how often you should receive
67 | // updates, the priority, etc.
68 | private lateinit var locationRequest: LocationRequest
69 |
70 | // LocationCallback - Called when FusedLocationProviderClient has a new Location.
71 | private lateinit var locationCallback: LocationCallback
72 |
73 | // Used only for local storage of the last known location. Usually, this would be saved to your
74 | // database, but because this is a simplified sample without a full database, we only need the
75 | // last location to create a Notification if the user navigates away from the app.
76 | private var currentLocation: Location? = null
77 |
78 | override fun onCreate() {
79 | Log.d(TAG, "onCreate()")
80 |
81 | notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
82 |
83 | // TODO: Step 1.2, Review the FusedLocationProviderClient.
84 | fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
85 |
86 | // TODO: Step 1.3, Create a LocationRequest.
87 |
88 | // TODO: Step 1.4, Initialize the LocationCallback.
89 |
90 | }
91 |
92 | override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
93 | Log.d(TAG, "onStartCommand()")
94 |
95 | val cancelLocationTrackingFromNotification =
96 | intent.getBooleanExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, false)
97 |
98 | if (cancelLocationTrackingFromNotification) {
99 | unsubscribeToLocationUpdates()
100 | stopSelf()
101 | }
102 | // Tells the system not to recreate the service after it's been killed.
103 | return START_NOT_STICKY
104 | }
105 |
106 | override fun onBind(intent: Intent): IBinder {
107 | Log.d(TAG, "onBind()")
108 |
109 | // MainActivity (client) comes into foreground and binds to service, so the service can
110 | // become a background services.
111 | stopForeground(true)
112 | serviceRunningInForeground = false
113 | configurationChange = false
114 | return localBinder
115 | }
116 |
117 | override fun onRebind(intent: Intent) {
118 | Log.d(TAG, "onRebind()")
119 |
120 | // MainActivity (client) returns to the foreground and rebinds to service, so the service
121 | // can become a background services.
122 | stopForeground(true)
123 | serviceRunningInForeground = false
124 | configurationChange = false
125 | super.onRebind(intent)
126 | }
127 |
128 | override fun onUnbind(intent: Intent): Boolean {
129 | Log.d(TAG, "onUnbind()")
130 |
131 | // MainActivity (client) leaves foreground, so service needs to become a foreground service
132 | // to maintain the 'while-in-use' label.
133 | // NOTE: If this method is called due to a configuration change in MainActivity,
134 | // we do nothing.
135 | if (!configurationChange && SharedPreferenceUtil.getLocationTrackingPref(this)) {
136 | Log.d(TAG, "Start foreground service")
137 | val notification = generateNotification(currentLocation)
138 | startForeground(NOTIFICATION_ID, notification)
139 | serviceRunningInForeground = true
140 | }
141 |
142 | // Ensures onRebind() is called if MainActivity (client) rebinds.
143 | return true
144 | }
145 |
146 | override fun onDestroy() {
147 | Log.d(TAG, "onDestroy()")
148 | }
149 |
150 | override fun onConfigurationChanged(newConfig: Configuration) {
151 | super.onConfigurationChanged(newConfig)
152 | configurationChange = true
153 | }
154 |
155 | fun subscribeToLocationUpdates() {
156 | Log.d(TAG, "subscribeToLocationUpdates()")
157 |
158 | SharedPreferenceUtil.saveLocationTrackingPref(this, true)
159 |
160 | // Binding to this service doesn't actually trigger onStartCommand(). That is needed to
161 | // ensure this Service can be promoted to a foreground service, i.e., the service needs to
162 | // be officially started (which we do here).
163 | startService(Intent(applicationContext, ForegroundOnlyLocationService::class.java))
164 |
165 | try {
166 | // TODO: Step 1.5, Subscribe to location changes.
167 |
168 | } catch (unlikely: SecurityException) {
169 | SharedPreferenceUtil.saveLocationTrackingPref(this, false)
170 | Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely")
171 | }
172 | }
173 |
174 | fun unsubscribeToLocationUpdates() {
175 | Log.d(TAG, "unsubscribeToLocationUpdates()")
176 |
177 | try {
178 | // TODO: Step 1.6, Unsubscribe to location changes.
179 |
180 | SharedPreferenceUtil.saveLocationTrackingPref(this, false)
181 |
182 | } catch (unlikely: SecurityException) {
183 | SharedPreferenceUtil.saveLocationTrackingPref(this, true)
184 | Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely")
185 | }
186 | }
187 |
188 | /*
189 | * Generates a BIG_TEXT_STYLE Notification that represent latest location.
190 | */
191 | private fun generateNotification(location: Location?): Notification {
192 | Log.d(TAG, "generateNotification()")
193 |
194 | // Main steps for building a BIG_TEXT_STYLE notification:
195 | // 0. Get data
196 | // 1. Create Notification Channel for O+
197 | // 2. Build the BIG_TEXT_STYLE
198 | // 3. Set up Intent / Pending Intent for notification
199 | // 4. Build and issue the notification
200 |
201 | // 0. Get data
202 | val mainNotificationText = location?.toText() ?: getString(R.string.no_location_text)
203 | val titleText = getString(R.string.app_name)
204 |
205 | // 1. Create Notification Channel for O+ and beyond devices (26+).
206 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
207 |
208 | val notificationChannel = NotificationChannel(
209 | NOTIFICATION_CHANNEL_ID, titleText, NotificationManager.IMPORTANCE_DEFAULT)
210 |
211 | // Adds NotificationChannel to system. Attempting to create an
212 | // existing notification channel with its original values performs
213 | // no operation, so it's safe to perform the below sequence.
214 | notificationManager.createNotificationChannel(notificationChannel)
215 | }
216 |
217 | // 2. Build the BIG_TEXT_STYLE.
218 | val bigTextStyle = NotificationCompat.BigTextStyle()
219 | .bigText(mainNotificationText)
220 | .setBigContentTitle(titleText)
221 |
222 | // 3. Set up main Intent/Pending Intents for notification.
223 | val launchActivityIntent = Intent(this, MainActivity::class.java)
224 |
225 | val cancelIntent = Intent(this, ForegroundOnlyLocationService::class.java)
226 | cancelIntent.putExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, true)
227 |
228 | val servicePendingIntent = PendingIntent.getService(
229 | this, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT)
230 |
231 | val activityPendingIntent = PendingIntent.getActivity(
232 | this, 0, launchActivityIntent, 0)
233 |
234 | // 4. Build and issue the notification.
235 | // Notification Channel Id is ignored for Android pre O (26).
236 | val notificationCompatBuilder =
237 | NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID)
238 |
239 | return notificationCompatBuilder
240 | .setStyle(bigTextStyle)
241 | .setContentTitle(titleText)
242 | .setContentText(mainNotificationText)
243 | .setSmallIcon(R.mipmap.ic_launcher)
244 | .setDefaults(NotificationCompat.DEFAULT_ALL)
245 | .setOngoing(true)
246 | .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
247 | .addAction(
248 | R.drawable.ic_launch, getString(R.string.launch_activity),
249 | activityPendingIntent
250 | )
251 | .addAction(
252 | R.drawable.ic_cancel,
253 | getString(R.string.stop_location_updates_button_text),
254 | servicePendingIntent
255 | )
256 | .build()
257 | }
258 |
259 | /**
260 | * Class used for the client Binder. Since this service runs in the same process as its
261 | * clients, we don't need to deal with IPC.
262 | */
263 | inner class LocalBinder : Binder() {
264 | internal val service: ForegroundOnlyLocationService
265 | get() = this@ForegroundOnlyLocationService
266 | }
267 |
268 | companion object {
269 | private const val TAG = "ForegroundOnlyLocationService"
270 |
271 | private const val PACKAGE_NAME = "com.example.android.whileinuselocation"
272 |
273 | internal const val ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST =
274 | "$PACKAGE_NAME.action.FOREGROUND_ONLY_LOCATION_BROADCAST"
275 |
276 | internal const val EXTRA_LOCATION = "$PACKAGE_NAME.extra.LOCATION"
277 |
278 | private const val EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION =
279 | "$PACKAGE_NAME.extra.CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION"
280 |
281 | private const val NOTIFICATION_ID = 12345678
282 |
283 | private const val NOTIFICATION_CHANNEL_ID = "while_in_use_channel_01"
284 | }
285 | }
286 |
--------------------------------------------------------------------------------
/base/src/main/java/com/example/android/whileinuselocation/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.android.whileinuselocation
17 |
18 | import android.Manifest
19 | import android.content.BroadcastReceiver
20 | import android.content.ComponentName
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.content.IntentFilter
24 | import android.content.ServiceConnection
25 | import android.content.SharedPreferences
26 | import android.content.pm.PackageManager
27 | import android.location.Location
28 | import android.net.Uri
29 | import android.os.Bundle
30 | import android.os.IBinder
31 | import android.provider.Settings
32 | import android.util.Log
33 | import android.widget.Button
34 | import android.widget.TextView
35 | import androidx.appcompat.app.AppCompatActivity
36 | import androidx.core.app.ActivityCompat
37 | import androidx.localbroadcastmanager.content.LocalBroadcastManager
38 | import com.google.android.material.snackbar.Snackbar
39 |
40 | private const val TAG = "MainActivity"
41 | private const val REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE = 34
42 |
43 | /**
44 | * This app allows a user to receive location updates without the background permission even when
45 | * the app isn't in focus. This is the preferred approach for Android.
46 | *
47 | * It does this by creating a foreground service (tied to a Notification) when the
48 | * user navigates away from the app. Because of this, it only needs foreground or "while in use"
49 | * location permissions. That is, there is no need to ask for location in the background (which
50 | * requires additional permissions in the manifest).
51 | *
52 | * Note: Users have the following options in Android 11+ regarding location:
53 | *
54 | * * Allow all the time
55 | * * Allow while app is in use, i.e., while app is in foreground (new in Android 10)
56 | * * Allow one time use (new in Android 11)
57 | * * Not allow location at all
58 | *
59 | * It is generally recommended you only request "while in use" location permissions (location only
60 | * needed in the foreground), e.g., fine and coarse. If your app has an approved use case for
61 | * using location in the background, request that permission in context and separately from
62 | * fine/coarse location requests. In addition, if the user denies the request or only allows
63 | * "while-in-use", handle it gracefully. To see an example of background location, please review
64 | * {@link https://github.com/android/location-samples/tree/master/LocationUpdatesBackgroundKotlin}.
65 | *
66 | * Android 10 and higher also now requires developers to specify foreground service type in the
67 | * manifest (in this case, "location").
68 | *
69 | * For the feature that requires location in the foreground, this sample uses a long-running bound
70 | * and started service for location updates. The service is aware of foreground status of this
71 | * activity, which is the only bound client in this sample.
72 | *
73 | * While getting location in the foreground, if the activity ceases to be in the foreground (user
74 | * navigates away from the app), the service promotes itself to a foreground service and continues
75 | * receiving location updates.
76 | *
77 | * When the activity comes back to the foreground, the foreground service stops, and the
78 | * notification associated with that foreground service is removed.
79 | *
80 | * While the foreground service notification is displayed, the user has the option to launch the
81 | * activity from the notification. The user can also remove location updates directly from the
82 | * notification. This dismisses the notification and stops the service.
83 | */
84 | class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
85 | private var foregroundOnlyLocationServiceBound = false
86 |
87 | // Provides location updates for while-in-use feature.
88 | private var foregroundOnlyLocationService: ForegroundOnlyLocationService? = null
89 |
90 | // Listens for location broadcasts from ForegroundOnlyLocationService.
91 | private lateinit var foregroundOnlyBroadcastReceiver: ForegroundOnlyBroadcastReceiver
92 |
93 | private lateinit var sharedPreferences: SharedPreferences
94 |
95 | private lateinit var foregroundOnlyLocationButton: Button
96 |
97 | private lateinit var outputTextView: TextView
98 |
99 | // Monitors connection to the while-in-use service.
100 | private val foregroundOnlyServiceConnection = object : ServiceConnection {
101 |
102 | override fun onServiceConnected(name: ComponentName, service: IBinder) {
103 | val binder = service as ForegroundOnlyLocationService.LocalBinder
104 | foregroundOnlyLocationService = binder.service
105 | foregroundOnlyLocationServiceBound = true
106 | }
107 |
108 | override fun onServiceDisconnected(name: ComponentName) {
109 | foregroundOnlyLocationService = null
110 | foregroundOnlyLocationServiceBound = false
111 | }
112 | }
113 |
114 | override fun onCreate(savedInstanceState: Bundle?) {
115 | super.onCreate(savedInstanceState)
116 |
117 | setContentView(R.layout.activity_main)
118 |
119 | foregroundOnlyBroadcastReceiver = ForegroundOnlyBroadcastReceiver()
120 |
121 | sharedPreferences =
122 | getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE)
123 |
124 | foregroundOnlyLocationButton = findViewById(R.id.foreground_only_location_button)
125 | outputTextView = findViewById(R.id.output_text_view)
126 |
127 | foregroundOnlyLocationButton.setOnClickListener {
128 | val enabled = sharedPreferences.getBoolean(
129 | SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
130 |
131 | if (enabled) {
132 | foregroundOnlyLocationService?.unsubscribeToLocationUpdates()
133 | } else {
134 |
135 | // TODO: Step 1.0, Review Permissions: Checks and requests if needed.
136 | if (foregroundPermissionApproved()) {
137 | foregroundOnlyLocationService?.subscribeToLocationUpdates()
138 | ?: Log.d(TAG, "Service Not Bound")
139 | } else {
140 | requestForegroundPermissions()
141 | }
142 | }
143 | }
144 | }
145 |
146 | override fun onStart() {
147 | super.onStart()
148 |
149 | updateButtonState(
150 | sharedPreferences.getBoolean(SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
151 | )
152 | sharedPreferences.registerOnSharedPreferenceChangeListener(this)
153 |
154 | val serviceIntent = Intent(this, ForegroundOnlyLocationService::class.java)
155 | bindService(serviceIntent, foregroundOnlyServiceConnection, Context.BIND_AUTO_CREATE)
156 | }
157 |
158 | override fun onResume() {
159 | super.onResume()
160 | LocalBroadcastManager.getInstance(this).registerReceiver(
161 | foregroundOnlyBroadcastReceiver,
162 | IntentFilter(
163 | ForegroundOnlyLocationService.ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST)
164 | )
165 | }
166 |
167 | override fun onPause() {
168 | LocalBroadcastManager.getInstance(this).unregisterReceiver(
169 | foregroundOnlyBroadcastReceiver
170 | )
171 | super.onPause()
172 | }
173 |
174 | override fun onStop() {
175 | if (foregroundOnlyLocationServiceBound) {
176 | unbindService(foregroundOnlyServiceConnection)
177 | foregroundOnlyLocationServiceBound = false
178 | }
179 | sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
180 |
181 | super.onStop()
182 | }
183 |
184 | override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
185 | // Updates button states if new while in use location is added to SharedPreferences.
186 | if (key == SharedPreferenceUtil.KEY_FOREGROUND_ENABLED) {
187 | updateButtonState(sharedPreferences.getBoolean(
188 | SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
189 | )
190 | }
191 | }
192 |
193 | // TODO: Step 1.0, Review Permissions: Method checks if permissions approved.
194 | private fun foregroundPermissionApproved(): Boolean {
195 | return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
196 | this,
197 | Manifest.permission.ACCESS_FINE_LOCATION
198 | )
199 | }
200 |
201 | // TODO: Step 1.0, Review Permissions: Method requests permissions.
202 | private fun requestForegroundPermissions() {
203 | val provideRationale = foregroundPermissionApproved()
204 |
205 | // If the user denied a previous request, but didn't check "Don't ask again", provide
206 | // additional rationale.
207 | if (provideRationale) {
208 | Snackbar.make(
209 | findViewById(R.id.activity_main),
210 | R.string.permission_rationale,
211 | Snackbar.LENGTH_LONG
212 | )
213 | .setAction(R.string.ok) {
214 | // Request permission
215 | ActivityCompat.requestPermissions(
216 | this@MainActivity,
217 | arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
218 | REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
219 | )
220 | }
221 | .show()
222 | } else {
223 | Log.d(TAG, "Request foreground only permission")
224 | ActivityCompat.requestPermissions(
225 | this@MainActivity,
226 | arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
227 | REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
228 | )
229 | }
230 | }
231 |
232 | // TODO: Step 1.0, Review Permissions: Handles permission result.
233 | override fun onRequestPermissionsResult(
234 | requestCode: Int,
235 | permissions: Array,
236 | grantResults: IntArray
237 | ) {
238 | Log.d(TAG, "onRequestPermissionResult")
239 |
240 | when (requestCode) {
241 | REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE -> when {
242 | grantResults.isEmpty() ->
243 | // If user interaction was interrupted, the permission request
244 | // is cancelled and you receive empty arrays.
245 | Log.d(TAG, "User interaction was cancelled.")
246 |
247 | grantResults[0] == PackageManager.PERMISSION_GRANTED ->
248 | // Permission was granted.
249 | foregroundOnlyLocationService?.subscribeToLocationUpdates()
250 |
251 | else -> {
252 | // Permission denied.
253 | updateButtonState(false)
254 |
255 | Snackbar.make(
256 | findViewById(R.id.activity_main),
257 | R.string.permission_denied_explanation,
258 | Snackbar.LENGTH_LONG
259 | )
260 | .setAction(R.string.settings) {
261 | // Build intent that displays the App settings screen.
262 | val intent = Intent()
263 | intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
264 | val uri = Uri.fromParts(
265 | "package",
266 | BuildConfig.APPLICATION_ID,
267 | null
268 | )
269 | intent.data = uri
270 | intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
271 | startActivity(intent)
272 | }
273 | .show()
274 | }
275 | }
276 | }
277 | }
278 |
279 | private fun updateButtonState(trackingLocation: Boolean) {
280 | if (trackingLocation) {
281 | foregroundOnlyLocationButton.text = getString(R.string.stop_location_updates_button_text)
282 | } else {
283 | foregroundOnlyLocationButton.text = getString(R.string.start_location_updates_button_text)
284 | }
285 | }
286 |
287 | private fun logResultsToScreen(output: String) {
288 | val outputWithPreviousLogs = "$output\n${outputTextView.text}"
289 | outputTextView.text = outputWithPreviousLogs
290 | }
291 |
292 | /**
293 | * Receiver for location broadcasts from [ForegroundOnlyLocationService].
294 | */
295 | private inner class ForegroundOnlyBroadcastReceiver : BroadcastReceiver() {
296 |
297 | override fun onReceive(context: Context, intent: Intent) {
298 | val location = intent.getParcelableExtra(
299 | ForegroundOnlyLocationService.EXTRA_LOCATION
300 | )
301 |
302 | if (location != null) {
303 | logResultsToScreen("Foreground location: ${location.toText()}")
304 | }
305 | }
306 | }
307 | }
308 |
--------------------------------------------------------------------------------
/base/src/main/java/com/example/android/whileinuselocation/Utils.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.android.whileinuselocation
17 |
18 | import android.content.Context
19 | import android.location.Location
20 | import androidx.core.content.edit
21 |
22 | /**
23 | * Returns the `location` object as a human readable string.
24 | */
25 | fun Location?.toText(): String {
26 | return if (this != null) {
27 | "($latitude, $longitude)"
28 | } else {
29 | "Unknown location"
30 | }
31 | }
32 |
33 | /**
34 | * Provides access to SharedPreferences for location to Activities and Services.
35 | */
36 | internal object SharedPreferenceUtil {
37 |
38 | const val KEY_FOREGROUND_ENABLED = "tracking_foreground_location"
39 |
40 | /**
41 | * Returns true if requesting location updates, otherwise returns false.
42 | *
43 | * @param context The [Context].
44 | */
45 | fun getLocationTrackingPref(context: Context): Boolean =
46 | context.getSharedPreferences(
47 | context.getString(R.string.preference_file_key), Context.MODE_PRIVATE)
48 | .getBoolean(KEY_FOREGROUND_ENABLED, false)
49 |
50 | /**
51 | * Stores the location updates state in SharedPreferences.
52 | * @param requestingLocationUpdates The location updates state.
53 | */
54 | fun saveLocationTrackingPref(context: Context, requestingLocationUpdates: Boolean) =
55 | context.getSharedPreferences(
56 | context.getString(R.string.preference_file_key),
57 | Context.MODE_PRIVATE).edit {
58 | putBoolean(KEY_FOREGROUND_ENABLED, requestingLocationUpdates)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/base/src/main/res/drawable-hdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-hdpi/ic_cancel.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-hdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-hdpi/ic_launch.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-mdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-mdpi/ic_cancel.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-mdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-mdpi/ic_launch.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-xhdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-xhdpi/ic_cancel.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-xhdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-xhdpi/ic_launch.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-xxhdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-xxhdpi/ic_cancel.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-xxhdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-xxhdpi/ic_launch.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-xxxhdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-xxxhdpi/ic_cancel.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable-xxxhdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/drawable-xxxhdpi/ic_launch.png
--------------------------------------------------------------------------------
/base/src/main/res/drawable/background_border.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/base/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
25 |
26 |
38 |
39 |
53 |
54 |
--------------------------------------------------------------------------------
/base/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/base/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/base/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/base/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/base/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/base/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/base/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | #3F51B5
19 | #303F9F
20 | #FF4081
21 |
22 |
--------------------------------------------------------------------------------
/base/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
16 | 16dp
17 | 16dp
18 |
19 |
--------------------------------------------------------------------------------
/base/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | Location in Android
19 |
20 | Launch activity
21 | Location Unknown
22 | Location Updates
23 |
24 | Location permission needed for core functionality
25 | Permission was denied, but is needed for core functionality.
26 | Settings
27 | OK
28 |
29 | Start receiving location updates
30 | Stop receiving location updates
31 |
32 | Location Updated: %1$s
33 |
34 | com.example.android.while_in_use_location.PREFERENCE_FILE_KEY
35 | No current location
36 |
37 |
--------------------------------------------------------------------------------
/base/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
17 |
18 | buildscript {
19 | ext.kotlin_version = '1.6.20'
20 | repositories {
21 | google()
22 | mavenCentral()
23 | }
24 | dependencies {
25 | classpath 'com.android.tools.build:gradle:7.1.2'
26 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
27 | // NOTE: Do not place your application dependencies here; they belong
28 | // in the individual module build.gradle files
29 | }
30 | }
31 |
32 | allprojects {
33 | repositories {
34 | google()
35 | mavenCentral()
36 | }
37 | }
38 |
39 | task clean(type: Delete) {
40 | delete rootProject.buildDir
41 | }
42 |
--------------------------------------------------------------------------------
/complete/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/complete/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | apply plugin: 'com.android.application'
17 | apply plugin: 'kotlin-android'
18 |
19 | android {
20 | // TODO: Step 2.1, Target Android 10 and then Android 11.
21 | compileSdkVersion 32
22 | defaultConfig {
23 | applicationId "com.example.android.whileinuselocation"
24 | minSdkVersion 26
25 | targetSdkVersion 32
26 | versionCode 1
27 | versionName "1.0"
28 | }
29 | buildTypes {
30 | release {
31 | minifyEnabled false
32 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
33 | }
34 | }
35 |
36 | compileOptions {
37 | sourceCompatibility JavaVersion.VERSION_1_8
38 | targetCompatibility JavaVersion.VERSION_1_8
39 | }
40 |
41 | kotlinOptions {
42 | jvmTarget = JavaVersion.VERSION_1_8.toString()
43 | }
44 |
45 | buildFeatures {
46 | viewBinding true
47 | }
48 | }
49 |
50 | dependencies {
51 | implementation fileTree(dir: 'libs', include: ['*.jar'])
52 | implementation 'androidx.appcompat:appcompat:1.4.1'
53 | implementation 'androidx.core:core-ktx:1.7.0'
54 | implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
55 | implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.1.0'
56 |
57 | implementation 'com.google.android.gms:play-services-location:19.0.1'
58 |
59 | implementation 'com.google.android.material:material:1.5.0'
60 | }
61 |
--------------------------------------------------------------------------------
/complete/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Copyright 2019 Google LLC
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # https://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | # Add project specific ProGuard rules here.
16 | # You can control the set of applied configuration files using the
17 | # proguardFiles setting in build.gradle.
18 | #
19 | # For more details, see
20 | # http://developer.android.com/guide/developing/tools/proguard.html
21 | #
22 | # Add project specific ProGuard rules here.
23 | # You can control the set of applied configuration files using the
24 | # proguardFiles setting in build.gradle.
25 | #
26 | # For more details, see
27 | # http://developer.android.com/guide/developing/tools/proguard.html
28 |
29 | # If your project uses WebView with JS, uncomment the following
30 | # and specify the fully qualified class name to the JavaScript interface
31 | # class:
32 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
33 | # public *;
34 | #}
35 |
36 | # Uncomment this to preserve the line number information for
37 | # debugging stack traces.
38 | #-keepattributes SourceFile,LineNumberTable
39 |
40 | # If you keep the line number information, uncomment this to
41 | # hide the original source file name.
42 | #-renamesourcefileattribute SourceFile
43 |
--------------------------------------------------------------------------------
/complete/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
20 |
21 |
22 |
23 |
24 |
25 |
27 |
28 |
34 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/complete/src/main/java/com/example/android/whileinuselocation/ForegroundOnlyLocationService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.android.whileinuselocation
17 |
18 | import android.app.Notification
19 | import android.app.NotificationChannel
20 | import android.app.NotificationManager
21 | import android.app.PendingIntent
22 | import android.app.Service
23 | import android.content.Context
24 | import android.content.Intent
25 | import android.content.res.Configuration
26 | import android.location.Location
27 | import android.os.Binder
28 | import android.os.Build
29 | import android.os.IBinder
30 | import android.os.Looper
31 | import android.util.Log
32 | import androidx.core.app.NotificationCompat
33 | import androidx.localbroadcastmanager.content.LocalBroadcastManager
34 | import com.google.android.gms.location.FusedLocationProviderClient
35 | import com.google.android.gms.location.LocationCallback
36 | import com.google.android.gms.location.LocationRequest
37 | import com.google.android.gms.location.LocationResult
38 | import com.google.android.gms.location.LocationServices
39 | import java.util.concurrent.TimeUnit
40 |
41 | /**
42 | * Service tracks location when requested and updates Activity via binding. If Activity is
43 | * stopped/unbinds and tracking is enabled, the service promotes itself to a foreground service to
44 | * insure location updates aren't interrupted.
45 | *
46 | * For apps running in the background on O+ devices, location is computed much less than previous
47 | * versions. Please reference documentation for details.
48 | */
49 | class ForegroundOnlyLocationService : Service() {
50 | /*
51 | * Checks whether the bound activity has really gone away (foreground service with notification
52 | * created) or simply orientation change (no-op).
53 | */
54 | private var configurationChange = false
55 |
56 | private var serviceRunningInForeground = false
57 |
58 | private val localBinder = LocalBinder()
59 |
60 | private lateinit var notificationManager: NotificationManager
61 |
62 | // TODO: Step 1.1, Review variables (no changes).
63 | // FusedLocationProviderClient - Main class for receiving location updates.
64 | private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
65 |
66 | // LocationRequest - Requirements for the location updates, i.e., how often you should receive
67 | // updates, the priority, etc.
68 | private lateinit var locationRequest: LocationRequest
69 |
70 | // LocationCallback - Called when FusedLocationProviderClient has a new Location.
71 | private lateinit var locationCallback: LocationCallback
72 |
73 | // Used only for local storage of the last known location. Usually, this would be saved to your
74 | // database, but because this is a simplified sample without a full database, we only need the
75 | // last location to create a Notification if the user navigates away from the app.
76 | private var currentLocation: Location? = null
77 |
78 | override fun onCreate() {
79 | Log.d(TAG, "onCreate()")
80 |
81 | notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
82 |
83 | // TODO: Step 1.2, Review the FusedLocationProviderClient.
84 | fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
85 |
86 | // TODO: Step 1.3, Create a LocationRequest.
87 | locationRequest = LocationRequest.create().apply {
88 | // Sets the desired interval for active location updates. This interval is inexact. You
89 | // may not receive updates at all if no location sources are available, or you may
90 | // receive them less frequently than requested. You may also receive updates more
91 | // frequently than requested if other applications are requesting location at a more
92 | // frequent interval.
93 | //
94 | // IMPORTANT NOTE: Apps running on Android 8.0 and higher devices (regardless of
95 | // targetSdkVersion) may receive updates less frequently than this interval when the app
96 | // is no longer in the foreground.
97 | interval = TimeUnit.SECONDS.toMillis(60)
98 |
99 | // Sets the fastest rate for active location updates. This interval is exact, and your
100 | // application will never receive updates more frequently than this value.
101 | fastestInterval = TimeUnit.SECONDS.toMillis(30)
102 |
103 | // Sets the maximum time when batched location updates are delivered. Updates may be
104 | // delivered sooner than this interval.
105 | maxWaitTime = TimeUnit.MINUTES.toMillis(2)
106 |
107 | priority = LocationRequest.PRIORITY_HIGH_ACCURACY
108 | }
109 |
110 | // TODO: Step 1.4, Initialize the LocationCallback.
111 | locationCallback = object : LocationCallback() {
112 | override fun onLocationResult(locationResult: LocationResult) {
113 | super.onLocationResult(locationResult)
114 |
115 | // Normally, you want to save a new location to a database. We are simplifying
116 | // things a bit and just saving it as a local variable, as we only need it again
117 | // if a Notification is created (when the user navigates away from app).
118 | currentLocation = locationResult.lastLocation
119 |
120 | // Notify our Activity that a new location was added. Again, if this was a
121 | // production app, the Activity would be listening for changes to a database
122 | // with new locations, but we are simplifying things a bit to focus on just
123 | // learning the location side of things.
124 | val intent = Intent(ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST)
125 | intent.putExtra(EXTRA_LOCATION, currentLocation)
126 | LocalBroadcastManager.getInstance(applicationContext).sendBroadcast(intent)
127 |
128 | // Updates notification content if this service is running as a foreground
129 | // service.
130 | if (serviceRunningInForeground) {
131 | notificationManager.notify(
132 | NOTIFICATION_ID,
133 | generateNotification(currentLocation))
134 | }
135 | }
136 | }
137 | }
138 |
139 | override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
140 | Log.d(TAG, "onStartCommand()")
141 |
142 | val cancelLocationTrackingFromNotification =
143 | intent.getBooleanExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, false)
144 |
145 | if (cancelLocationTrackingFromNotification) {
146 | unsubscribeToLocationUpdates()
147 | stopSelf()
148 | }
149 | // Tells the system not to recreate the service after it's been killed.
150 | return START_NOT_STICKY
151 | }
152 |
153 | override fun onBind(intent: Intent): IBinder {
154 | Log.d(TAG, "onBind()")
155 |
156 | // MainActivity (client) comes into foreground and binds to service, so the service can
157 | // become a background services.
158 | stopForeground(true)
159 | serviceRunningInForeground = false
160 | configurationChange = false
161 | return localBinder
162 | }
163 |
164 | override fun onRebind(intent: Intent) {
165 | Log.d(TAG, "onRebind()")
166 |
167 | // MainActivity (client) returns to the foreground and rebinds to service, so the service
168 | // can become a background services.
169 | stopForeground(true)
170 | serviceRunningInForeground = false
171 | configurationChange = false
172 | super.onRebind(intent)
173 | }
174 |
175 | override fun onUnbind(intent: Intent): Boolean {
176 | Log.d(TAG, "onUnbind()")
177 |
178 | // MainActivity (client) leaves foreground, so service needs to become a foreground service
179 | // to maintain the 'while-in-use' label.
180 | // NOTE: If this method is called due to a configuration change in MainActivity,
181 | // we do nothing.
182 | if (!configurationChange && SharedPreferenceUtil.getLocationTrackingPref(this)) {
183 | Log.d(TAG, "Start foreground service")
184 | val notification = generateNotification(currentLocation)
185 | startForeground(NOTIFICATION_ID, notification)
186 | serviceRunningInForeground = true
187 | }
188 |
189 | // Ensures onRebind() is called if MainActivity (client) rebinds.
190 | return true
191 | }
192 |
193 | override fun onDestroy() {
194 | Log.d(TAG, "onDestroy()")
195 | }
196 |
197 | override fun onConfigurationChanged(newConfig: Configuration) {
198 | super.onConfigurationChanged(newConfig)
199 | configurationChange = true
200 | }
201 |
202 | fun subscribeToLocationUpdates() {
203 | Log.d(TAG, "subscribeToLocationUpdates()")
204 |
205 | SharedPreferenceUtil.saveLocationTrackingPref(this, true)
206 |
207 | // Binding to this service doesn't actually trigger onStartCommand(). That is needed to
208 | // ensure this Service can be promoted to a foreground service, i.e., the service needs to
209 | // be officially started (which we do here).
210 | startService(Intent(applicationContext, ForegroundOnlyLocationService::class.java))
211 |
212 | try {
213 | // TODO: Step 1.5, Subscribe to location changes.
214 | fusedLocationProviderClient.requestLocationUpdates(
215 | locationRequest, locationCallback, Looper.getMainLooper())
216 | } catch (unlikely: SecurityException) {
217 | SharedPreferenceUtil.saveLocationTrackingPref(this, false)
218 | Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely")
219 | }
220 | }
221 |
222 | fun unsubscribeToLocationUpdates() {
223 | Log.d(TAG, "unsubscribeToLocationUpdates()")
224 |
225 | try {
226 | // TODO: Step 1.6, Unsubscribe to location changes.
227 | val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)
228 | removeTask.addOnCompleteListener { task ->
229 | if (task.isSuccessful) {
230 | Log.d(TAG, "Location Callback removed.")
231 | stopSelf()
232 | } else {
233 | Log.d(TAG, "Failed to remove Location Callback.")
234 | }
235 | }
236 | SharedPreferenceUtil.saveLocationTrackingPref(this, false)
237 | } catch (unlikely: SecurityException) {
238 | SharedPreferenceUtil.saveLocationTrackingPref(this, true)
239 | Log.e(TAG, "Lost location permissions. Couldn't remove updates. $unlikely")
240 | }
241 | }
242 |
243 | /*
244 | * Generates a BIG_TEXT_STYLE Notification that represent latest location.
245 | */
246 | private fun generateNotification(location: Location?): Notification {
247 | Log.d(TAG, "generateNotification()")
248 |
249 | // Main steps for building a BIG_TEXT_STYLE notification:
250 | // 0. Get data
251 | // 1. Create Notification Channel for O+
252 | // 2. Build the BIG_TEXT_STYLE
253 | // 3. Set up Intent / Pending Intent for notification
254 | // 4. Build and issue the notification
255 |
256 | // 0. Get data
257 | val mainNotificationText = location?.toText() ?: getString(R.string.no_location_text)
258 | val titleText = getString(R.string.app_name)
259 |
260 | // 1. Create Notification Channel for O+ and beyond devices (26+).
261 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
262 |
263 | val notificationChannel = NotificationChannel(
264 | NOTIFICATION_CHANNEL_ID, titleText, NotificationManager.IMPORTANCE_DEFAULT)
265 |
266 | // Adds NotificationChannel to system. Attempting to create an
267 | // existing notification channel with its original values performs
268 | // no operation, so it's safe to perform the below sequence.
269 | notificationManager.createNotificationChannel(notificationChannel)
270 | }
271 |
272 | // 2. Build the BIG_TEXT_STYLE.
273 | val bigTextStyle = NotificationCompat.BigTextStyle()
274 | .bigText(mainNotificationText)
275 | .setBigContentTitle(titleText)
276 |
277 | // 3. Set up main Intent/Pending Intents for notification.
278 | val launchActivityIntent = Intent(this, MainActivity::class.java)
279 |
280 | val cancelIntent = Intent(this, ForegroundOnlyLocationService::class.java)
281 | cancelIntent.putExtra(EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION, true)
282 |
283 | val servicePendingIntent = PendingIntent.getService(
284 | this, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT)
285 |
286 | val activityPendingIntent = PendingIntent.getActivity(
287 | this, 0, launchActivityIntent, 0)
288 |
289 | // 4. Build and issue the notification.
290 | // Notification Channel Id is ignored for Android pre O (26).
291 | val notificationCompatBuilder =
292 | NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL_ID)
293 |
294 | return notificationCompatBuilder
295 | .setStyle(bigTextStyle)
296 | .setContentTitle(titleText)
297 | .setContentText(mainNotificationText)
298 | .setSmallIcon(R.mipmap.ic_launcher)
299 | .setDefaults(NotificationCompat.DEFAULT_ALL)
300 | .setOngoing(true)
301 | .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
302 | .addAction(
303 | R.drawable.ic_launch, getString(R.string.launch_activity),
304 | activityPendingIntent
305 | )
306 | .addAction(
307 | R.drawable.ic_cancel,
308 | getString(R.string.stop_location_updates_button_text),
309 | servicePendingIntent
310 | )
311 | .build()
312 | }
313 |
314 | /**
315 | * Class used for the client Binder. Since this service runs in the same process as its
316 | * clients, we don't need to deal with IPC.
317 | */
318 | inner class LocalBinder : Binder() {
319 | internal val service: ForegroundOnlyLocationService
320 | get() = this@ForegroundOnlyLocationService
321 | }
322 |
323 | companion object {
324 | private const val TAG = "ForegroundOnlyLocationService"
325 |
326 | private const val PACKAGE_NAME = "com.example.android.whileinuselocation"
327 |
328 | internal const val ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST =
329 | "$PACKAGE_NAME.action.FOREGROUND_ONLY_LOCATION_BROADCAST"
330 |
331 | internal const val EXTRA_LOCATION = "$PACKAGE_NAME.extra.LOCATION"
332 |
333 | private const val EXTRA_CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION =
334 | "$PACKAGE_NAME.extra.CANCEL_LOCATION_TRACKING_FROM_NOTIFICATION"
335 |
336 | private const val NOTIFICATION_ID = 12345678
337 |
338 | private const val NOTIFICATION_CHANNEL_ID = "while_in_use_channel_01"
339 | }
340 | }
341 |
--------------------------------------------------------------------------------
/complete/src/main/java/com/example/android/whileinuselocation/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.android.whileinuselocation
17 |
18 | import android.Manifest
19 | import android.content.BroadcastReceiver
20 | import android.content.ComponentName
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.content.IntentFilter
24 | import android.content.ServiceConnection
25 | import android.content.SharedPreferences
26 | import android.content.pm.PackageManager
27 | import android.location.Location
28 | import android.net.Uri
29 | import android.os.Bundle
30 | import android.os.IBinder
31 | import android.provider.Settings
32 | import android.util.Log
33 | import android.widget.Button
34 | import android.widget.TextView
35 | import androidx.appcompat.app.AppCompatActivity
36 | import androidx.core.app.ActivityCompat
37 | import androidx.localbroadcastmanager.content.LocalBroadcastManager
38 | import com.google.android.material.snackbar.Snackbar
39 |
40 | private const val TAG = "MainActivity"
41 | private const val REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE = 34
42 |
43 | /**
44 | * This app allows a user to receive location updates without the background permission even when
45 | * the app isn't in focus. This is the preferred approach for Android.
46 | *
47 | * It does this by creating a foreground service (tied to a Notification) when the
48 | * user navigates away from the app. Because of this, it only needs foreground or "while in use"
49 | * location permissions. That is, there is no need to ask for location in the background (which
50 | * requires additional permissions in the manifest).
51 | *
52 | * Note: Users have the following options in Android 11+ regarding location:
53 | *
54 | * * Allow all the time
55 | * * Allow while app is in use, i.e., while app is in foreground (new in Android 10)
56 | * * Allow one time use (new in Android 11)
57 | * * Not allow location at all
58 | *
59 | * It is generally recommended you only request "while in use" location permissions (location only
60 | * needed in the foreground), e.g., fine and coarse. If your app has an approved use case for
61 | * using location in the background, request that permission in context and separately from
62 | * fine/coarse location requests. In addition, if the user denies the request or only allows
63 | * "while-in-use", handle it gracefully. To see an example of background location, please review
64 | * {@link https://github.com/android/location-samples/tree/master/LocationUpdatesBackgroundKotlin}.
65 | *
66 | * Android 10 and higher also now requires developers to specify foreground service type in the
67 | * manifest (in this case, "location").
68 | *
69 | * For the feature that requires location in the foreground, this sample uses a long-running bound
70 | * and started service for location updates. The service is aware of foreground status of this
71 | * activity, which is the only bound client in this sample.
72 | *
73 | * While getting location in the foreground, if the activity ceases to be in the foreground (user
74 | * navigates away from the app), the service promotes itself to a foreground service and continues
75 | * receiving location updates.
76 | *
77 | * When the activity comes back to the foreground, the foreground service stops, and the
78 | * notification associated with that foreground service is removed.
79 | *
80 | * While the foreground service notification is displayed, the user has the option to launch the
81 | * activity from the notification. The user can also remove location updates directly from the
82 | * notification. This dismisses the notification and stops the service.
83 | */
84 | class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
85 | private var foregroundOnlyLocationServiceBound = false
86 |
87 | // Provides location updates for while-in-use feature.
88 | private var foregroundOnlyLocationService: ForegroundOnlyLocationService? = null
89 |
90 | // Listens for location broadcasts from ForegroundOnlyLocationService.
91 | private lateinit var foregroundOnlyBroadcastReceiver: ForegroundOnlyBroadcastReceiver
92 |
93 | private lateinit var sharedPreferences: SharedPreferences
94 |
95 | private lateinit var foregroundOnlyLocationButton: Button
96 |
97 | private lateinit var outputTextView: TextView
98 |
99 | // Monitors connection to the while-in-use service.
100 | private val foregroundOnlyServiceConnection = object : ServiceConnection {
101 |
102 | override fun onServiceConnected(name: ComponentName, service: IBinder) {
103 | val binder = service as ForegroundOnlyLocationService.LocalBinder
104 | foregroundOnlyLocationService = binder.service
105 | foregroundOnlyLocationServiceBound = true
106 | }
107 |
108 | override fun onServiceDisconnected(name: ComponentName) {
109 | foregroundOnlyLocationService = null
110 | foregroundOnlyLocationServiceBound = false
111 | }
112 | }
113 |
114 | override fun onCreate(savedInstanceState: Bundle?) {
115 | super.onCreate(savedInstanceState)
116 |
117 | setContentView(R.layout.activity_main)
118 |
119 | foregroundOnlyBroadcastReceiver = ForegroundOnlyBroadcastReceiver()
120 |
121 | sharedPreferences =
122 | getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE)
123 |
124 | foregroundOnlyLocationButton = findViewById(R.id.foreground_only_location_button)
125 | outputTextView = findViewById(R.id.output_text_view)
126 |
127 | foregroundOnlyLocationButton.setOnClickListener {
128 | val enabled = sharedPreferences.getBoolean(
129 | SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
130 |
131 | if (enabled) {
132 | foregroundOnlyLocationService?.unsubscribeToLocationUpdates()
133 | } else {
134 | // TODO: Step 1.0, Review Permissions: Checks and requests if needed.
135 | if (foregroundPermissionApproved()) {
136 | foregroundOnlyLocationService?.subscribeToLocationUpdates()
137 | ?: Log.d(TAG, "Service Not Bound")
138 | } else {
139 | requestForegroundPermissions()
140 | }
141 | }
142 | }
143 | }
144 |
145 | override fun onStart() {
146 | super.onStart()
147 |
148 | updateButtonState(
149 | sharedPreferences.getBoolean(SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
150 | )
151 | sharedPreferences.registerOnSharedPreferenceChangeListener(this)
152 |
153 | val serviceIntent = Intent(this, ForegroundOnlyLocationService::class.java)
154 | bindService(serviceIntent, foregroundOnlyServiceConnection, Context.BIND_AUTO_CREATE)
155 | }
156 |
157 | override fun onResume() {
158 | super.onResume()
159 | LocalBroadcastManager.getInstance(this).registerReceiver(
160 | foregroundOnlyBroadcastReceiver,
161 | IntentFilter(
162 | ForegroundOnlyLocationService.ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST)
163 | )
164 | }
165 |
166 | override fun onPause() {
167 | LocalBroadcastManager.getInstance(this).unregisterReceiver(
168 | foregroundOnlyBroadcastReceiver
169 | )
170 | super.onPause()
171 | }
172 |
173 | override fun onStop() {
174 | if (foregroundOnlyLocationServiceBound) {
175 | unbindService(foregroundOnlyServiceConnection)
176 | foregroundOnlyLocationServiceBound = false
177 | }
178 | sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
179 |
180 | super.onStop()
181 | }
182 |
183 | override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
184 | // Updates button states if new while in use location is added to SharedPreferences.
185 | if (key == SharedPreferenceUtil.KEY_FOREGROUND_ENABLED) {
186 | updateButtonState(sharedPreferences.getBoolean(
187 | SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
188 | )
189 | }
190 | }
191 |
192 | // TODO: Step 1.0, Review Permissions: Method checks if permissions approved.
193 | private fun foregroundPermissionApproved(): Boolean {
194 | return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
195 | this,
196 | Manifest.permission.ACCESS_FINE_LOCATION
197 | )
198 | }
199 |
200 | // TODO: Step 1.0, Review Permissions: Method requests permissions.
201 | private fun requestForegroundPermissions() {
202 | val provideRationale = foregroundPermissionApproved()
203 |
204 | // If the user denied a previous request, but didn't check "Don't ask again", provide
205 | // additional rationale.
206 | if (provideRationale) {
207 | Snackbar.make(
208 | findViewById(R.id.activity_main),
209 | R.string.permission_rationale,
210 | Snackbar.LENGTH_LONG
211 | )
212 | .setAction(R.string.ok) {
213 | // Request permission
214 | ActivityCompat.requestPermissions(
215 | this@MainActivity,
216 | arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
217 | REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
218 | )
219 | }
220 | .show()
221 | } else {
222 | Log.d(TAG, "Request foreground only permission")
223 | ActivityCompat.requestPermissions(
224 | this@MainActivity,
225 | arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
226 | REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
227 | )
228 | }
229 | }
230 |
231 | // TODO: Step 1.0, Review Permissions: Handles permission result.
232 | override fun onRequestPermissionsResult(
233 | requestCode: Int,
234 | permissions: Array,
235 | grantResults: IntArray
236 | ) {
237 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
238 | Log.d(TAG, "onRequestPermissionResult")
239 |
240 | when (requestCode) {
241 | REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE -> when {
242 | grantResults.isEmpty() ->
243 | // If user interaction was interrupted, the permission request
244 | // is cancelled and you receive empty arrays.
245 | Log.d(TAG, "User interaction was cancelled.")
246 | grantResults[0] == PackageManager.PERMISSION_GRANTED ->
247 | // Permission was granted.
248 | foregroundOnlyLocationService?.subscribeToLocationUpdates()
249 | else -> {
250 | // Permission denied.
251 | updateButtonState(false)
252 |
253 | Snackbar.make(
254 | findViewById(R.id.activity_main),
255 | R.string.permission_denied_explanation,
256 | Snackbar.LENGTH_LONG
257 | )
258 | .setAction(R.string.settings) {
259 | // Build intent that displays the App settings screen.
260 | val intent = Intent()
261 | intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
262 | val uri = Uri.fromParts(
263 | "package",
264 | BuildConfig.APPLICATION_ID,
265 | null
266 | )
267 | intent.data = uri
268 | intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
269 | startActivity(intent)
270 | }
271 | .show()
272 | }
273 | }
274 | }
275 | }
276 |
277 | private fun updateButtonState(trackingLocation: Boolean) {
278 | if (trackingLocation) {
279 | foregroundOnlyLocationButton.text = getString(R.string.stop_location_updates_button_text)
280 | } else {
281 | foregroundOnlyLocationButton.text = getString(R.string.start_location_updates_button_text)
282 | }
283 | }
284 |
285 | private fun logResultsToScreen(output: String) {
286 | val outputWithPreviousLogs = "$output\n${outputTextView.text}"
287 | outputTextView.text = outputWithPreviousLogs
288 | }
289 |
290 | /**
291 | * Receiver for location broadcasts from [ForegroundOnlyLocationService].
292 | */
293 | private inner class ForegroundOnlyBroadcastReceiver : BroadcastReceiver() {
294 |
295 | override fun onReceive(context: Context, intent: Intent) {
296 | val location = intent.getParcelableExtra(
297 | ForegroundOnlyLocationService.EXTRA_LOCATION
298 | )
299 |
300 | if (location != null) {
301 | logResultsToScreen("Foreground location: ${location.toText()}")
302 | }
303 | }
304 | }
305 | }
306 |
--------------------------------------------------------------------------------
/complete/src/main/java/com/example/android/whileinuselocation/Utils.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2019 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.android.whileinuselocation
17 |
18 | import android.content.Context
19 | import android.location.Location
20 | import androidx.core.content.edit
21 |
22 | /**
23 | * Returns the `location` object as a human readable string.
24 | */
25 | fun Location?.toText(): String {
26 | return if (this != null) {
27 | "($latitude, $longitude)"
28 | } else {
29 | "Unknown location"
30 | }
31 | }
32 |
33 | /**
34 | * Provides access to SharedPreferences for location to Activities and Services.
35 | */
36 | internal object SharedPreferenceUtil {
37 |
38 | const val KEY_FOREGROUND_ENABLED = "tracking_foreground_location"
39 |
40 | /**
41 | * Returns true if requesting location updates, otherwise returns false.
42 | *
43 | * @param context The [Context].
44 | */
45 | fun getLocationTrackingPref(context: Context): Boolean =
46 | context.getSharedPreferences(
47 | context.getString(R.string.preference_file_key), Context.MODE_PRIVATE)
48 | .getBoolean(KEY_FOREGROUND_ENABLED, false)
49 |
50 | /**
51 | * Stores the location updates state in SharedPreferences.
52 | * @param requestingLocationUpdates The location updates state.
53 | */
54 | fun saveLocationTrackingPref(context: Context, requestingLocationUpdates: Boolean) =
55 | context.getSharedPreferences(
56 | context.getString(R.string.preference_file_key),
57 | Context.MODE_PRIVATE).edit {
58 | putBoolean(KEY_FOREGROUND_ENABLED, requestingLocationUpdates)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-hdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-hdpi/ic_cancel.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-hdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-hdpi/ic_launch.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-mdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-mdpi/ic_cancel.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-mdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-mdpi/ic_launch.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-xhdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-xhdpi/ic_cancel.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-xhdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-xhdpi/ic_launch.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-xxhdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-xxhdpi/ic_cancel.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-xxhdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-xxhdpi/ic_launch.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-xxxhdpi/ic_cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-xxxhdpi/ic_cancel.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable-xxxhdpi/ic_launch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/drawable-xxxhdpi/ic_launch.png
--------------------------------------------------------------------------------
/complete/src/main/res/drawable/background_border.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/complete/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
25 |
26 |
38 |
39 |
53 |
54 |
--------------------------------------------------------------------------------
/complete/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/complete/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/complete/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/complete/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/complete/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/complete/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/complete/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | #3F51B5
19 | #303F9F
20 | #FF4081
21 |
22 |
--------------------------------------------------------------------------------
/complete/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
16 | 16dp
17 | 16dp
18 |
19 |
--------------------------------------------------------------------------------
/complete/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | Location in Android
19 |
20 | Launch activity
21 | Location Unknown
22 | Location Updates
23 |
24 | Location permission needed for core functionality
25 | Permission was denied, but is needed for core functionality.
26 | Settings
27 | OK
28 |
29 | Start receiving location updates
30 | Stop receiving location updates
31 |
32 | Location Updated: %1$s
33 |
34 | com.example.android.while_in_use_location.PREFERENCE_FILE_KEY
35 | No current location
36 |
37 |
--------------------------------------------------------------------------------
/complete/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Copyright 2019 Google LLC
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # https://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 | #
15 | # Project-wide Gradle settings.
16 | # IDE (e.g. Android Studio) users:
17 | # Gradle settings configured through the IDE *will override*
18 | # any settings specified in this file.
19 | # For more details on how to configure your build environment visit
20 | # http://www.gradle.org/docs/current/userguide/build_environment.html
21 | # Specifies the JVM arguments used for the daemon process.
22 | # The setting is particularly useful for tweaking memory settings.
23 | org.gradle.jvmargs=-Xmx1536m
24 | # When configured, Gradle will run in incubating parallel mode.
25 | # This option should only be used with decoupled projects. More details, visit
26 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
27 | # org.gradle.parallel=true
28 | # AndroidX package structure to make it clearer which packages are bundled with the
29 | # Android operating system, and which are packaged with your app's APK
30 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
31 | android.useAndroidX=true
32 | # Automatically convert third-party libraries to use AndroidX
33 | android.enableJetifier=true
34 | # Kotlin code style for this project: "official" or "obsolete":
35 | kotlin.code.style=official
36 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/android/codelab-while-in-use-location/1a91373eb792f85e5ad1bc1c19fc434a6a1fc749/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Jan 30 09:54:36 PST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':complete', ':base'
2 |
--------------------------------------------------------------------------------