├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── drawable
│ │ │ │ ├── ic_baseline_smartphone_24.xml
│ │ │ │ ├── ic_baseline_contact_support_24.xml
│ │ │ │ ├── ic_baseline_phonelink_ring_24.xml
│ │ │ │ ├── ic_baseline_phone_24.xml
│ │ │ │ ├── ic_baseline_phonelink_lock_24.xml
│ │ │ │ ├── ic_baseline_settings_24.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── values
│ │ │ │ ├── themes.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── strings.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── layout
│ │ │ │ ├── activity_welcome.xml
│ │ │ │ └── activity_home.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── ape
│ │ │ │ └── apps
│ │ │ │ └── sample
│ │ │ │ └── baypilot
│ │ │ │ ├── App.kt
│ │ │ │ ├── util
│ │ │ │ ├── extension
│ │ │ │ │ └── ImageView.kt
│ │ │ │ ├── sharedpreferences
│ │ │ │ │ └── SharedPreferenceLiveData.kt
│ │ │ │ ├── boot
│ │ │ │ │ └── BootReceiver.kt
│ │ │ │ ├── firebase
│ │ │ │ │ ├── FirebaseDatabaseManager.kt
│ │ │ │ │ └── BayPilotFirebaseMessagingService.kt
│ │ │ │ ├── alarm
│ │ │ │ │ ├── AlarmReceiver.kt
│ │ │ │ │ └── AlarmSetter.kt
│ │ │ │ ├── date
│ │ │ │ │ └── DateTimeHelper.kt
│ │ │ │ ├── dlc
│ │ │ │ │ ├── DeviceLockServiceProtocol.kt
│ │ │ │ │ └── DeviceLockMessenger.kt
│ │ │ │ ├── network
│ │ │ │ │ └── InternetConnectivity.kt
│ │ │ │ └── worker
│ │ │ │ │ └── DatabaseSyncWorker.kt
│ │ │ │ ├── data
│ │ │ │ ├── FieldNames.kt
│ │ │ │ ├── creditplan
│ │ │ │ │ └── CreditPlanInfo.kt
│ │ │ │ └── sharedprefs
│ │ │ │ │ └── SharedPreferencesManager.kt
│ │ │ │ └── ui
│ │ │ │ ├── home
│ │ │ │ ├── HomeViewModel.kt
│ │ │ │ └── HomeActivity.kt
│ │ │ │ └── welcome
│ │ │ │ ├── WelcomeActivity.kt
│ │ │ │ └── WelcomeViewModel.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── ape
│ │ │ └── apps
│ │ │ └── sample
│ │ │ └── baypilot
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── ape
│ │ └── apps
│ │ └── sample
│ │ └── baypilot
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── docs
└── imgs
│ └── kioskapprefere--ugvo40yvr9l.png
├── settings.gradle
├── gradle.properties
├── CONTRIBUTING.md
├── gradlew.bat
├── README.md
├── bay-pilot
└── .idea
│ └── workspace.xml
├── gradlew
└── LICENSE.md
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/docs/imgs/kioskapprefere--ugvo40yvr9l.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/docs/imgs/kioskapprefere--ugvo40yvr9l.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/kiosk-app-reference-implementation/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Nov 08 05:07:09 UTC 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/App.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot
18 |
19 | import android.app.Application
20 |
21 | class App : Application() {
22 |
23 | companion object {
24 | private const val TAG = "BayPilotApplication"
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | // Copyright 2022 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 | // http://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 | dependencyResolutionManagement {
16 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
17 | repositories {
18 | google()
19 | mavenCentral()
20 | jcenter() // Warning: this repository is going to shut down soon
21 | }
22 | }
23 | rootProject.name = "Bay Pilot"
24 | include ':app'
25 |
--------------------------------------------------------------------------------
/app/src/test/java/com/ape/apps/sample/baypilot/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot
18 |
19 | import org.junit.Assert.assertEquals
20 | import org.junit.Test
21 |
22 | /**
23 | * Example local unit test, which will execute on the development machine (host).
24 | *
25 | * See [testing documentation](http://d.android.com/tools/testing).
26 | */
27 | class ExampleUnitTest {
28 | @Test
29 | fun addition_isCorrect() {
30 | assertEquals(4, 2 + 2)
31 | }
32 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_baseline_smartphone_24.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/extension/ImageView.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.extension
18 |
19 | import android.content.res.ColorStateList
20 | import android.widget.ImageView
21 | import androidx.annotation.ColorRes
22 | import androidx.core.content.ContextCompat
23 | import androidx.core.widget.ImageViewCompat
24 |
25 | fun ImageView.setTint(@ColorRes colorRes: Int) {
26 | ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/data/FieldNames.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.data
18 |
19 | object FieldNames {
20 |
21 | const val imei = "Imei"
22 | const val firebaseToken = "FirebaseToken"
23 |
24 | object CreditPlanInfo {
25 | const val plan = "Plan"
26 |
27 | object Plan {
28 | const val totalAmount = "Total Amount"
29 | const val dueDate = "Due Date"
30 | const val nextInstallmentAmount = "Next Installment Amount"
31 | const val planType = "Plan Type"
32 | const val totalPaidAmount = "Total Paid Amount"
33 | }
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_baseline_contact_support_24.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_baseline_phonelink_ring_24.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_baseline_phone_24.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_baseline_phonelink_lock_24.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/ape/apps/sample/baypilot/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot
18 |
19 | import androidx.test.ext.junit.runners.AndroidJUnit4
20 | import androidx.test.platform.app.InstrumentationRegistry
21 | import org.junit.Assert.assertEquals
22 | import org.junit.Test
23 | import org.junit.runner.RunWith
24 |
25 | /**
26 | * Instrumented test, which will execute on an Android device.
27 | *
28 | * See [testing documentation](http://d.android.com/tools/testing).
29 | */
30 | @RunWith(AndroidJUnit4::class)
31 | class ExampleInstrumentedTest {
32 | @Test
33 | fun useAppContext() {
34 | // Context of the app under test.
35 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
36 | assertEquals("com.ape.apps.sample.baypilot", appContext.packageName)
37 | }
38 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
34 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
34 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | #FFBB86FC
20 | #FF6200EE
21 | #FF3700B3
22 | #FF03DAC5
23 | #FF018786
24 | #FF000000
25 | #FFFFFFFF
26 |
27 | #2196F3
28 | #1976D2
29 | #388E3C
30 | #EEEEEE
31 | #616161
32 | #F44336
33 |
34 | @color/blue_500
35 | @color/blue_700
36 | @color/green_700
37 | @color/grey_700
38 | @color/grey_300
39 | @color/red_500
40 |
41 |
--------------------------------------------------------------------------------
/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](https://developers.google.com/open-source/cla/individual).
13 | * If you work for a company that wants to allow you to contribute your work,
14 | then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate).
15 |
16 | Follow either of the two links above to access the appropriate CLA and
17 | instructions for how to sign and return it. Once we receive it, we'll be able to
18 | accept your pull requests.
19 |
20 | ## Contributing A Patch
21 |
22 | 1. Submit an issue describing your proposed change to the repo in question.
23 | 2. The repo owner will respond to your issue promptly.
24 | 3. If your proposed change is accepted, and you haven't already done so, sign a
25 | Contributor License Agreement (see details above).
26 | 4. Fork the desired repo, develop and test your code changes.
27 | 5. Ensure that your code adheres to the existing style in the sample to which
28 | you are contributing. Refer to the
29 | [Android Code Style Guide](https://source.android.com/source/code-style.html) for the
30 | recommended coding standards for this organization.
31 | 6. Ensure that your code has an appropriate set of unit tests which all pass.
32 | 7. Submit a pull request.
33 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_baseline_settings_24.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/sharedpreferences/SharedPreferenceLiveData.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.sharedpreferences
18 |
19 | import android.content.SharedPreferences
20 | import androidx.lifecycle.LiveData
21 |
22 | abstract class SharedPreferenceLiveData(
23 | val sharedPrefs: SharedPreferences,
24 | private val key: String,
25 | private val defValue: T
26 | ) : LiveData() {
27 |
28 | private val preferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
29 | if (key == this.key) {
30 | value = getValueFromPreferences(key, defValue)
31 | }
32 | }
33 |
34 | abstract fun getValueFromPreferences(key: String, defValue: T): T
35 |
36 | override fun onActive() {
37 | super.onActive()
38 |
39 | value = getValueFromPreferences(key, defValue)
40 | sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener)
41 | }
42 |
43 | override fun onInactive() {
44 | sharedPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener)
45 | super.onInactive()
46 | }
47 | }
48 |
49 | class SharedPreferenceIntLiveData(sharedPrefs: SharedPreferences, key: String, defValue: Int) :
50 | SharedPreferenceLiveData(sharedPrefs, key, defValue) {
51 | override fun getValueFromPreferences(key: String, defValue: Int): Int = sharedPrefs.getInt(key, defValue)
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/ui/home/HomeViewModel.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.ui.home
18 |
19 | import android.content.Context
20 | import android.util.Log
21 | import androidx.lifecycle.*
22 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
23 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
24 | import com.ape.apps.sample.baypilot.util.sharedpreferences.SharedPreferenceIntLiveData
25 | import kotlinx.coroutines.flow.collect
26 | import kotlinx.coroutines.launch
27 |
28 | class HomeViewModel : ViewModel() {
29 |
30 | companion object {
31 | private const val TAG = "BayPilotHomeViewModel"
32 | }
33 |
34 | private val _creditPlanInfo = MutableLiveData()
35 | val creditPlanInfo: LiveData
36 | get() = _creditPlanInfo
37 |
38 | fun observeCreditPlanInfo(context: Context) {
39 | Log.d(TAG, "observeCreditPlanInfo() called with: context")
40 |
41 | val sharedPreferencesManager = SharedPreferencesManager(context)
42 |
43 | viewModelScope.launch {
44 | SharedPreferenceIntLiveData(
45 | sharedPreferencesManager.sharedPreferences,
46 | SharedPreferencesManager.KEY_CREDIT_PLAN_SAVE_ID,
47 | 0
48 | ).asFlow().collect {
49 | Log.d(TAG, "observeCreditPlanInfo() asFlow().collect called with: creditPlanSaveId = $it")
50 |
51 | _creditPlanInfo.value = sharedPreferencesManager.readCreditPlan()
52 | }
53 | }
54 | }
55 |
56 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/boot/BootReceiver.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.boot
18 |
19 | import android.content.BroadcastReceiver
20 | import android.content.Context
21 | import android.content.Intent
22 | import android.util.Log
23 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
24 | import com.ape.apps.sample.baypilot.util.alarm.AlarmSetter
25 | import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker
26 |
27 | // Class to reset LOCK/Notification alarms after phone is restarted.
28 | // When phone is restarted it loses all pending alarms so we need to Register for BootReceiver and set the alarms again.
29 | class BootReceiver : BroadcastReceiver() {
30 |
31 | companion object {
32 | private const val TAG = "BayPilotBootReceiver"
33 | }
34 |
35 | override fun onReceive(context: Context, intent: Intent?) {
36 | // Get CreditPlanInfo stored locally in device in sharedPreferences.
37 | val sharedPreferencesManager = SharedPreferencesManager(context)
38 | val creditPlanInfo = sharedPreferencesManager.readCreditPlan() ?: return
39 |
40 | // Set Alarms
41 | Log.d(TAG, "Setting Alarms after boot")
42 | val alarmSetter = AlarmSetter(context)
43 | alarmSetter.setCreditAlarms(creditPlanInfo)
44 |
45 | // Schedule a sync to server when Internet connectivity available to make
46 | // sure we don't lose any update in case phone was switched on after long time.
47 | DatabaseSyncWorker.scheduleSync(context)
48 | }
49 |
50 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
23 |
24 |
25 |
31 |
34 |
37 |
38 |
39 |
40 |
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/data/creditplan/CreditPlanInfo.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.data.creditplan
18 |
19 | import com.google.gson.Gson
20 |
21 | enum class CreditPlanType {
22 | MONTHLY, WEEKLY, DAILY;
23 |
24 | companion object {
25 | fun toString(creditPlanType: CreditPlanType?): String? {
26 | return when (creditPlanType) {
27 | MONTHLY -> "MONTHLY"
28 | WEEKLY -> "WEEKLY"
29 | DAILY -> "DAILY"
30 | else -> null
31 | }
32 | }
33 |
34 | fun toCreditPlanType(planType: String?): CreditPlanType? {
35 | return when (planType) {
36 | "DAILY" -> DAILY
37 | "WEEKLY" -> WEEKLY
38 | "MONTHLY" -> MONTHLY
39 | else -> null
40 | }
41 | }
42 | }
43 | }
44 |
45 | // Class to store all details related to device credit plan.
46 | // TODO: Currently it has only few essential members for testing, add others.
47 | class CreditPlanInfo(
48 | val totalAmount: Int? = 0,
49 | val totalPaidAmount: Int? = 0,
50 | val dueDate: String? = null,
51 | val nextDueAmount: Int? = 0,
52 | val planType: CreditPlanType? = null
53 | ) {
54 |
55 | companion object {
56 | // Serialize a single object.
57 | fun serializeToJson(cpi: CreditPlanInfo?): String? {
58 | val gson = Gson()
59 | return gson.toJson(cpi)
60 | }
61 |
62 | // Deserialize to single object.
63 | fun deserializeFromJson(jsonString: String?): CreditPlanInfo? {
64 | val gson = Gson()
65 | return gson.fromJson(jsonString, CreditPlanInfo::class.java)
66 | }
67 | }
68 |
69 | fun toDebugString(): String {
70 | return "Credit Plan details: Due Date = $dueDate, Total device cost = $totalAmount, " +
71 | "Amount paid till now: $totalPaidAmount Next installment due = $nextDueAmount, Plan type = $planType"
72 | }
73 |
74 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/firebase/FirebaseDatabaseManager.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.firebase
18 |
19 | import android.content.Context
20 | import android.util.Log
21 | import com.ape.apps.sample.baypilot.data.FieldNames
22 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
23 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
24 | import com.google.firebase.database.FirebaseDatabase
25 | import kotlinx.coroutines.tasks.await
26 |
27 | // Class to connect app to Realtime Database.
28 | // Used to fetch credit plan details for device IMEI and store FCM token device in database.
29 | class FirebaseDatabaseManager {
30 |
31 | companion object {
32 | private const val TAG = "BayPilotFirebaseDatabaseManager"
33 | }
34 |
35 | private val firebaseDatabase = FirebaseDatabase.getInstance()
36 |
37 | // Read credit plan details from Database.
38 | suspend fun readCreditPlanInfoFromDatabase(context: Context, deviceImei: String): CreditPlanInfo? {
39 | Log.d(TAG, "readCreditPlanInfoFromDatabase() called with: context, deviceImei = $deviceImei")
40 |
41 | return try {
42 | val result = firebaseDatabase.getReference(deviceImei).get().await()
43 |
44 | result?.child(FieldNames.CreditPlanInfo.plan)?.getValue(CreditPlanInfo::class.java)
45 | } catch (exception: Exception) {
46 | Log.d(
47 | TAG,
48 | "readCreditPlanInfoFromDatabase firebaseDatabase.getReference or result?.child called with exception = $exception"
49 | )
50 |
51 | SharedPreferencesManager(context).setCreditPlanInvalid()
52 | null
53 | }
54 | }
55 |
56 | // Store FCM token in database under device imei.
57 | fun storeFcmToken(token: String, imei: String) {
58 | val imeiRef = firebaseDatabase.getReference(imei)
59 | imeiRef.child(FieldNames.firebaseToken).setValue(token)
60 | }
61 |
62 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_welcome.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
24 |
25 |
36 |
37 |
48 |
49 |
59 |
60 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/alarm/AlarmReceiver.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.alarm
18 |
19 | import android.content.BroadcastReceiver
20 | import android.content.Context
21 | import android.content.Intent
22 | import android.util.Log
23 | import androidx.work.OneTimeWorkRequestBuilder
24 | import androidx.work.WorkManager
25 | import androidx.work.workDataOf
26 | import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker
27 |
28 | class AlarmReceiver : BroadcastReceiver() {
29 |
30 | companion object {
31 | private const val TAG = "BayPilotAlarmReceiver"
32 |
33 | const val EXTRA_REQUEST_CODE = "requestCode"
34 | const val EXTRA_DUE_DATE = "DUE_DATE"
35 |
36 | const val ACTION_LOCK = "LOCK"
37 | const val ACTION_NOTIFICATION = "NOTIFICATION"
38 | }
39 |
40 | override fun onReceive(context: Context, intent: Intent) {
41 | Log.d(
42 | TAG, "Lock onReceive() called with: action ${intent.action} with " +
43 | "${intent.getIntExtra(EXTRA_REQUEST_CODE, 0)}"
44 | )
45 |
46 | val dueDate = intent.getStringExtra(EXTRA_DUE_DATE)
47 | val workAction = when (intent.action) {
48 | ACTION_LOCK -> DatabaseSyncWorker.ACTION_LOCK_DEVICE
49 | ACTION_NOTIFICATION -> DatabaseSyncWorker.ACTION_SEND_NOTIFICATION
50 | else -> return
51 | }
52 |
53 | startWorker(context, workAction, dueDate ?: "")
54 | }
55 |
56 | private fun startWorker(context: Context, workAction: String, dueDate: String) {
57 | val inputData = workDataOf(
58 | DatabaseSyncWorker.WORK_ACTION to workAction,
59 | DatabaseSyncWorker.ALARM_DUE_DATE to dueDate
60 | )
61 | val uploadWorkRequest =
62 | OneTimeWorkRequestBuilder().apply {
63 | setInputData(inputData)
64 | // setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
65 | }.build()
66 |
67 | WorkManager
68 | .getInstance(context)
69 | .enqueue(uploadWorkRequest)
70 | }
71 |
72 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
39 |
40 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
52 |
53 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "com.android.application"
3 | id "kotlin-android"
4 | id "com.google.gms.google-services"
5 | }
6 |
7 | android {
8 | compileSdk 31
9 |
10 | defaultConfig {
11 | applicationId "com.ape.apps.sample.baypilot"
12 | minSdk 30
13 | targetSdk 31
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 |
20 | buildFeatures {
21 | viewBinding true
22 | }
23 |
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
28 | }
29 | }
30 |
31 | compileOptions {
32 | sourceCompatibility JavaVersion.VERSION_1_8
33 | targetCompatibility JavaVersion.VERSION_1_8
34 | }
35 |
36 | kotlinOptions {
37 | jvmTarget = "1.8"
38 | }
39 | }
40 |
41 | dependencies {
42 | implementation "androidx.core:core-ktx:1.7.0"
43 |
44 | implementation "androidx.appcompat:appcompat:1.4.1"
45 |
46 | implementation "androidx.activity:activity-ktx:1.4.0"
47 |
48 | implementation "androidx.constraintlayout:constraintlayout:2.1.3"
49 |
50 | // Material Components
51 | implementation "com.google.android.material:material:1.5.0"
52 |
53 | // Jetpack ViewModel
54 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"
55 | implementation "androidx.lifecycle:lifecycle-common-java8:2.4.0"
56 |
57 | // Jetpack WorkManager
58 | implementation "androidx.work:work-runtime-ktx:2.7.1"
59 |
60 | // Firebase Android BoM (Bill of Materials)
61 | implementation platform("com.google.firebase:firebase-bom:29.0.0")
62 |
63 | // Firebase Analytics
64 | implementation "com.google.firebase:firebase-analytics-ktx"
65 |
66 | // Firebase Cloud Messaging
67 | implementation "com.google.firebase:firebase-messaging-ktx"
68 |
69 | // Firebase Realtime Database
70 | implementation "com.google.firebase:firebase-database-ktx"
71 |
72 | // Firebase Authentication library
73 | implementation 'com.google.firebase:firebase-auth-ktx'
74 |
75 | // Jetpack WorkManager
76 | implementation "androidx.work:work-runtime-ktx:2.7.1"
77 |
78 | // Kotlinx Coroutines Play Services
79 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.0-RC"
80 |
81 | // LiveData
82 | implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.0"
83 |
84 | implementation "com.google.code.gson:gson:2.8.6"
85 |
86 | testImplementation "junit:junit:4.13.2"
87 |
88 | androidTestImplementation "androidx.test.ext:junit:1.1.3"
89 | androidTestImplementation "androidx.test.espresso:espresso-core:3.4.0"
90 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/date/DateTimeHelper.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.date
18 |
19 | import android.content.Context
20 | import com.ape.apps.sample.baypilot.R
21 | import java.time.ZoneId
22 | import java.time.ZonedDateTime
23 | import java.time.format.DateTimeFormatter
24 | import java.time.temporal.ChronoUnit
25 | import java.util.*
26 | import kotlin.math.abs
27 |
28 | // Object containing utility functions for DueDate.
29 | object DateTimeHelper {
30 |
31 | // Convert dueDate string to same zone ZonedDateTime.
32 | private fun getZonedDateTimeForDueDate(dueDate: String): ZonedDateTime {
33 | val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("MMM dd HH:mm:ss ZZ yyyy", Locale.ENGLISH)
34 | return ZonedDateTime.parse(dueDate, formatter)
35 | }
36 |
37 | // Convert dueDate string to ZonedDateTIme in device default zone.
38 | fun getDeviceZonedDueDateTime(dueDate: String): ZonedDateTime {
39 | val zonedDateTime = getZonedDateTimeForDueDate(dueDate)
40 | return zonedDateTime.withZoneSameInstant(ZoneId.systemDefault())
41 | }
42 |
43 | // Checks if given dateTime is in future.
44 | fun isInFuture(dateTime: ZonedDateTime): Boolean {
45 | return dateTime.isAfter(ZonedDateTime.now(dateTime.zone))
46 | }
47 |
48 | // Converts dueDate to ZonedDateTime and checks if it is future.
49 | fun isDueDateInFuture(dueDate: String): Boolean {
50 | return isInFuture(getDeviceZonedDueDateTime(dueDate))
51 | }
52 |
53 | // Formats dueDate to string. Used to show Due Date in UI
54 | fun formattedDateTime(dueDateTime: ZonedDateTime): String {
55 | return dueDateTime.format(DateTimeFormatter.ofPattern("dd MMMM, hh:mm a"))
56 | }
57 |
58 | // Get time diff between given zonedDateTime and now till. Returns in hour if diff is less than 1 day.
59 | fun getTimeDiff(context: Context, zonedDueDateTime: ZonedDateTime): String {
60 | var remainingTime: Long = abs(ZonedDateTime.now().until(zonedDueDateTime, ChronoUnit.DAYS))
61 | var timeUnit = context.getString(R.string.days)
62 | // Get remaining time in hours if less than a day is left
63 | if (remainingTime == 0L) {
64 | remainingTime = abs(ZonedDateTime.now().until(zonedDueDateTime, ChronoUnit.HOURS))
65 | timeUnit = context.getString(R.string.hours)
66 | }
67 | return "$remainingTime $timeUnit"
68 | }
69 |
70 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/dlc/DeviceLockServiceProtocol.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.dlc
18 |
19 | import android.os.Bundle
20 |
21 | object DeviceLockServiceProtocol {
22 |
23 | const val SERVICE_ACTION = "com.google.android.apps.devicelock.service.DeviceLockService.BIND"
24 | const val SERVICE_PACKAGE_NAME = "com.google.android.apps.devicelock"
25 | const val SERVICE_CLASS_NAME = "com.google.android.apps.devicelock.service.DeviceLockService"
26 |
27 | /**
28 | * The [Bundle] key client can use to read IMEI from the [Message] passed to it.
29 | *
30 | * @see .CLIENT_MSG_QUERY_IMEI
31 | *
32 | * @see Message.getData
33 | */
34 | const val KEY_IMEI = "imei"
35 |
36 | /*
37 | * Version used by client;
38 | * - arg1 : client version
39 | */
40 | const val CLIENT_MSG_VERSION = 1
41 |
42 | /*
43 | * Command to enter lock task mode
44 | */
45 | const val CLIENT_MSG_LOCK_DEVICE = 2
46 |
47 | /*
48 | * Command to leave lock task mode
49 | */
50 | const val CLIENT_MSG_UNLOCK_DEVICE = 3
51 |
52 | /*
53 | * Clear Device owner. This is irreversible.
54 | */
55 | const val CLIENT_MSG_CLEAR_OWNER = 4
56 |
57 | /**
58 | * Query if device is locked. Client needs to set [android.os.Message.replyTo] field to a
59 | * Messenger object. The DLC will send a response on this [android.os.Messenger] object with
60 | * the [android.os.Message.arg1] set to 1 if locked or 0 if not locked.
61 | */
62 | const val CLIENT_MSG_IS_DEVICE_LOCKED = 5
63 |
64 | /**
65 | * Client can register with DeviceLockService to be re-launched if the app gets killed. When the
66 | * device is in locked state, any crashes on the lock screen activity can cause the device to drop
67 | * out of locked state. Client should send this message by setting a [ ][android.os.Message.replyTo] messenger. DeviceLockService will monitor client death using [ ][android.os.IBinder.linkToDeath] and restart the activity if the client dies.
68 | */
69 | const val CLIENT_MSG_REGISTER_RELAUNCH_ON_DEATH = 6
70 |
71 | /**
72 | * The message client can use to query the IMEI of the device.
73 | *
74 | *
75 | * Client needs to set [android.os.Message.replyTo] field to a [ ] object. DLC will send a response on the [android.os.Messenger]
76 | * object with the IMEI being included in the [Bundle].
77 | *
78 | * @see .KEY_IMEI
79 | *
80 | * @see Message.setData
81 | * @see Message.getData
82 | */
83 | const val CLIENT_MSG_QUERY_IMEI = 7
84 |
85 | /*
86 | * Service version
87 | */
88 | const val SERVICE_VERSION_1 = 1
89 |
90 | const val CURRENT_SERVICE_VERSION = SERVICE_VERSION_1
91 |
92 | }
93 |
94 | fun Int.toDeviceLockServiceProtocol(): String = when {
95 | this == 1 -> "CLIENT_MSG_VERSION"
96 | this == 2 -> "CLIENT_MSG_LOCK_DEVICE"
97 | this == 3 -> "CLIENT_MSG_UNLOCK_DEVICE"
98 | this == 4 -> "CLIENT_MSG_CLEAR_OWNER"
99 | this == 5 -> "CLIENT_MSG_IS_DEVICE_LOCKED"
100 | this == 6 -> "CLIENT_MSG_REGISTER_RELAUNCH_ON_DEATH"
101 | this == 7 -> "CLIENT_MSG_QUERY_IMEI"
102 | else -> "Unknown DeviceLockServiceProtocol"
103 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/network/InternetConnectivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.network
18 |
19 | import android.content.Context
20 | import android.net.ConnectivityManager
21 | import android.net.Network
22 | import android.net.NetworkCapabilities
23 | import android.net.NetworkRequest
24 | import android.util.Log
25 | import androidx.lifecycle.LiveData
26 |
27 | enum class InternetStatus {
28 | ONLINE, OFFLINE;
29 | }
30 |
31 | class InternetConnectivity(context: Context) : LiveData() {
32 |
33 | companion object {
34 | private const val TAG = "BayPilotInternetConnectivity"
35 | fun isConnectedToInternet(context: Context): Boolean {
36 | val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
37 | val activeNetwork = connectivityManager.activeNetwork ?: return false
38 | return connectivityManager.getNetworkCapabilities(activeNetwork)
39 | ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
40 | }
41 | }
42 |
43 | val connectivityManager: ConnectivityManager =
44 | context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
45 |
46 | var connectionList = mutableSetOf()
47 |
48 | fun emitStatus() {
49 | if (connectionList.isNotEmpty()) {
50 | postValue(InternetStatus.ONLINE)
51 | } else {
52 | postValue(InternetStatus.OFFLINE)
53 | }
54 |
55 | }
56 |
57 | override fun onActive() {
58 | super.onActive()
59 | val networkRequest = NetworkRequest
60 | .Builder()
61 | .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
62 | .build()
63 | connectivityManager.registerNetworkCallback(networkRequest, getNetworkCallback())
64 | }
65 |
66 | override fun onInactive() {
67 | super.onInactive()
68 | try {
69 | connectivityManager.unregisterNetworkCallback(getNetworkCallback())
70 | } catch (e: Exception) {
71 | Log.d(TAG, "Network callback was already unregistered")
72 | }
73 | }
74 |
75 | private fun getNetworkCallback() = object : ConnectivityManager.NetworkCallback() {
76 | override fun onAvailable(network: Network) {
77 | Log.d(TAG, "New Network Available $network")
78 | val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
79 | val isInternetAvailable =
80 | networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
81 | if (isInternetAvailable) {
82 | connectionList.add(network)
83 | emitStatus()
84 | }
85 | }
86 |
87 | override fun onLost(network: Network) {
88 | Log.d(TAG, "Network Lost $network")
89 | connectionList.remove(network)
90 | emitStatus()
91 | }
92 |
93 | override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
94 | if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
95 | connectionList.add(network)
96 | } else {
97 | connectionList.remove(network)
98 | }
99 | }
100 | }
101 |
102 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | Bay Pilot
19 |
20 |
21 | Creditor Bay Pilot
22 |
23 | Welcome
24 |
25 | Loading...
26 |
27 | $%d due in %s
28 | $%d overdue by %s
29 | Installment of $%d is due on %s
30 | Installment of $%d was due on %s
31 | hours
32 | days
33 | $%d Payment overdue %d days
34 | $%d Payment due in %d days
35 | No additional payment due
36 |
37 | Pay now
38 |
39 | Your Device is Offline.
40 | Please Connect to Internet to get latest update.
41 |
42 | Please connect to Internet
43 |
44 | phone
45 | Device unlocked
46 | Device locked - Payment overdue
47 | Credit fully paid
48 |
49 | Total Cost $%d
50 | Paid $%d
51 | Remaining $%d
52 |
53 | $%,.2f
54 | Paid of $%,.2f
55 |
56 | Next payment of $%d due: %s
57 | Payment of $%d was due: %s
58 | No additional payments required
59 |
60 | Last payment on %s
61 |
62 | Connect to Internet
63 | Get Support
64 | Make a call
65 | Settings
66 | Refresh
67 |
68 |
69 | Device is Locked
70 |
71 | Device is Unlocked
72 |
73 |
74 | Firebase Token
75 | Due Date
76 | Total Amount
77 | Paid Amount
78 | Next Installment Amount
79 |
80 |
81 | Phone installment due date in few days
82 |
83 | Phone installment is due in %s on %s
84 | Payment Due
85 | Error with Credit Plan. Please contact your provider.
86 |
87 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/ui/welcome/WelcomeActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.ui.welcome
18 |
19 | import android.content.Intent
20 | import android.os.Bundle
21 | import android.provider.Settings
22 | import android.util.Log
23 | import android.widget.Toast
24 | import androidx.activity.viewModels
25 | import androidx.appcompat.app.AppCompatActivity
26 | import com.ape.apps.sample.baypilot.R
27 | import com.ape.apps.sample.baypilot.databinding.ActivityWelcomeBinding
28 | import com.ape.apps.sample.baypilot.ui.home.HomeActivity
29 | import com.ape.apps.sample.baypilot.util.network.InternetConnectivity
30 | import com.google.firebase.auth.FirebaseAuth
31 | import com.google.firebase.auth.ktx.auth
32 | import com.google.firebase.ktx.Firebase
33 |
34 | class WelcomeActivity : AppCompatActivity() {
35 |
36 | companion object {
37 | private const val TAG = "BayPilotWelcomeActivity"
38 | }
39 |
40 | private lateinit var binding: ActivityWelcomeBinding
41 | private lateinit var auth: FirebaseAuth
42 |
43 | private val viewModel: WelcomeViewModel by viewModels()
44 |
45 | override fun onCreate(savedInstanceState: Bundle?) {
46 | Log.d(TAG, "onCreate() called with: savedInstanceState")
47 | super.onCreate(savedInstanceState)
48 |
49 | auth = Firebase.auth
50 |
51 | binding = ActivityWelcomeBinding.inflate(layoutInflater)
52 |
53 | val view = binding.root
54 | setContentView(view)
55 |
56 | binding.buttonInternet.setOnClickListener {
57 | startActivity(Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY))
58 | }
59 | }
60 |
61 | override fun onStart() {
62 | super.onStart()
63 |
64 | val currentUser = auth.currentUser
65 | if (currentUser == null) {
66 | Log.d(TAG, "Creating new Anonymous user")
67 | signIn()
68 | } else {
69 | Log.d(TAG, "Current firebase auth is not null. Checking if its still first run...")
70 | viewModel.checkFirstRun(applicationContext)
71 |
72 | Log.d(TAG, "Not first run. Starting Main Activity")
73 | val intent = Intent(this, HomeActivity::class.java).apply {
74 | flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
75 | }
76 | startActivity(intent)
77 | }
78 | }
79 |
80 | private fun signIn() {
81 | // Try signing in Anonymously.
82 | auth.signInAnonymously()
83 | .addOnCompleteListener(this) { task ->
84 | if (task.isSuccessful) {
85 | // Sign in success
86 | Log.d(TAG, "signInAnonymously:success. Starting initial Setup after sign in success")
87 | viewModel.initialSetup(applicationContext)
88 |
89 | Log.d(TAG, "Starting Main Activity after sign in Success")
90 | val intent = Intent(this, HomeActivity::class.java).apply {
91 | flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
92 | }
93 | startActivity(intent)
94 | } else {
95 | // TODO: Add checks for specific errors.
96 | // If sign in failed, display a message to the user.
97 | Log.e(TAG, "signInAnonymously:failure", task.exception)
98 | Toast.makeText(
99 | baseContext, "Authentication failed." + task.exception,
100 | Toast.LENGTH_SHORT
101 | ).show()
102 | binding.textViewErrorMsg.setText(R.string.connect_to_internet_welcome)
103 |
104 | // Trying SignIn Again when internet connection is available.
105 | InternetConnectivity(this).observe(this) {
106 | signIn()
107 | }
108 | }
109 | }
110 | }
111 |
112 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/data/sharedprefs/SharedPreferencesManager.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.data.sharedprefs
18 |
19 | import android.content.Context
20 | import android.content.SharedPreferences
21 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
22 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanType
23 |
24 | class SharedPreferencesManager(context: Context) {
25 |
26 | companion object {
27 | private const val TAG = "BayPilotSharedPreferencesManager"
28 |
29 | private const val SHARED_PREFS = "shared_prefs"
30 |
31 | private const val KEY_IS_FIRST_RUN = "is_first_run"
32 |
33 | private const val KEY_IMEI = "imei"
34 |
35 | private const val KEY_CREDIT_PLAN_SAVED = "credit_plan_saved"
36 | private const val KEY_VALID_CREDIT_PLAN = "valid_credit_plan"
37 | private const val KEY_DEVICE_RELEASED = "device_released"
38 |
39 | // Used to observe changes; creditPlanSaveId = lastCreditPlanSaveId + 1
40 | const val KEY_CREDIT_PLAN_SAVE_ID = "credit_plan_save_id"
41 |
42 | private const val KEY_TOTAL_AMOUNT = "total_amount"
43 | private const val KEY_PAID_AMOUNT = "paid_amount"
44 | private const val KEY_DUE_DATE = "due_date"
45 | private const val KEY_NEXT_DUE_AMOUNT = "next_due_amount"
46 | private const val KEY_PLAN_TYPE = "plan_type"
47 | }
48 |
49 | var sharedPreferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE)
50 |
51 | fun isFirstRun(): Boolean = sharedPreferences.getBoolean(KEY_IS_FIRST_RUN, true)
52 |
53 | fun writeFirstRun(firstRun: Boolean) = with(sharedPreferences.edit()) {
54 | putBoolean(KEY_IS_FIRST_RUN, firstRun)
55 | commit()
56 | }
57 |
58 | fun readIMEI(): String = sharedPreferences.getString(KEY_IMEI, "") ?: ""
59 |
60 | fun writeIMEI(imei: String) = with(sharedPreferences.edit()) {
61 | putString(KEY_IMEI, imei)
62 | commit()
63 | }
64 |
65 | fun isCreditPlanSaved(): Boolean = sharedPreferences.getBoolean(KEY_CREDIT_PLAN_SAVED, false)
66 |
67 | fun isValidCreditPlan(): Boolean = sharedPreferences.getBoolean(KEY_VALID_CREDIT_PLAN, false)
68 |
69 | fun isDeviceReleased(): Boolean = sharedPreferences.getBoolean(KEY_DEVICE_RELEASED, false)
70 |
71 | fun markDeviceReleased() = with(sharedPreferences.edit()) {
72 | incrementCreditPlanSaveId()
73 | putBoolean(KEY_DEVICE_RELEASED, true)
74 | commit()
75 | }
76 |
77 | fun setCreditPlanInvalid() = with(sharedPreferences.edit()) {
78 | incrementCreditPlanSaveId()
79 | putBoolean(KEY_CREDIT_PLAN_SAVED, true)
80 | putBoolean(KEY_VALID_CREDIT_PLAN, false)
81 | commit()
82 | }
83 |
84 | fun readCreditPlan(): CreditPlanInfo? {
85 | if (sharedPreferences.getBoolean(KEY_CREDIT_PLAN_SAVED, false).not()) return null
86 | if (sharedPreferences.getBoolean(KEY_VALID_CREDIT_PLAN, false).not()) return null
87 |
88 | return CreditPlanInfo(
89 | sharedPreferences.getInt(KEY_TOTAL_AMOUNT, 0),
90 | sharedPreferences.getInt(KEY_PAID_AMOUNT, 0),
91 | sharedPreferences.getString(KEY_DUE_DATE, ""),
92 | sharedPreferences.getInt(KEY_NEXT_DUE_AMOUNT, 0),
93 | CreditPlanType.toCreditPlanType(sharedPreferences.getString(KEY_PLAN_TYPE, ""))
94 | )
95 | }
96 |
97 | fun writeCreditPlan(creditPlanInfo: CreditPlanInfo) = with(sharedPreferences.edit()) {
98 | incrementCreditPlanSaveId()
99 | putBoolean(KEY_CREDIT_PLAN_SAVED, true)
100 | putBoolean(KEY_VALID_CREDIT_PLAN, true)
101 | putInt(KEY_TOTAL_AMOUNT, creditPlanInfo.totalAmount ?: 0)
102 | putInt(KEY_PAID_AMOUNT, creditPlanInfo.totalPaidAmount ?: 0)
103 | putString(KEY_DUE_DATE, creditPlanInfo.dueDate ?: "")
104 | putInt(KEY_NEXT_DUE_AMOUNT, creditPlanInfo.nextDueAmount ?: 0)
105 | putString(KEY_PLAN_TYPE, CreditPlanType.toString(creditPlanInfo.planType) ?: "")
106 | commit()
107 | }
108 |
109 | // Used to observe changes; creditPlanSaveId = lastCreditPlanSaveId + 1
110 | private fun SharedPreferences.Editor.incrementCreditPlanSaveId() {
111 | putInt(KEY_CREDIT_PLAN_SAVE_ID, sharedPreferences.getInt(KEY_CREDIT_PLAN_SAVE_ID, 0) + 1)
112 | }
113 |
114 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/alarm/AlarmSetter.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.alarm
18 |
19 | import android.app.AlarmManager
20 | import android.app.PendingIntent
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.util.Log
24 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
25 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanType
26 | import com.ape.apps.sample.baypilot.util.date.DateTimeHelper
27 | import java.time.ZonedDateTime
28 |
29 | class AlarmSetter(private val context: Context) {
30 |
31 | companion object {
32 | private const val TAG = "BayPilotAlarmSetter"
33 |
34 | private const val MAX_NOTIFICATION_ALARMS = 3
35 | }
36 |
37 | private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
38 |
39 | fun setCreditAlarms(creditPlanInfo: CreditPlanInfo) {
40 | Log.d(TAG, "setCreditAlarms() for ${creditPlanInfo.toDebugString()}")
41 |
42 | val dueDateString = creditPlanInfo.dueDate ?: ""
43 | val dueDateTime = DateTimeHelper.getDeviceZonedDueDateTime(dueDateString)
44 | setAlarm(AlarmReceiver.ACTION_LOCK, dueDateTime, dueDateString, 0)
45 | setNotificationAlarms(dueDateTime, dueDateString, creditPlanInfo.planType ?: CreditPlanType.MONTHLY)
46 | }
47 |
48 | private fun setNotificationAlarms(dueDateTime: ZonedDateTime, dueDateString: String, creditPlanType: CreditPlanType) {
49 | val notificationDues = getNotificationsSchedule(dueDateTime, creditPlanType)
50 | // Cancel pending alarms which won't be overwritten.
51 | var alarmNumber = MAX_NOTIFICATION_ALARMS
52 | while (alarmNumber > notificationDues.size) {
53 | alarmManager.cancel(getPendingIntent(AlarmReceiver.ACTION_NOTIFICATION, dueDateString, alarmNumber - 1))
54 | alarmNumber--
55 | }
56 | notificationDues.forEachIndexed { requestNumber, notificationDateTime ->
57 | setAlarm(AlarmReceiver.ACTION_NOTIFICATION, notificationDateTime, dueDateString, requestNumber)
58 | }
59 | }
60 |
61 | // Notification requirements for Kiosk App
62 | // https://docs.partner.android.com/gms/building/integrating/device-lock/requirements#unlocked-reqs
63 | private fun getNotificationsSchedule(
64 | dueDateTime: ZonedDateTime,
65 | creditPlanType: CreditPlanType
66 | ): MutableList {
67 | val notificationDues = mutableListOf()
68 | when (creditPlanType) {
69 | CreditPlanType.MONTHLY -> {
70 | notificationDues.add(dueDateTime.minusDays(7))
71 | notificationDues.add(dueDateTime.minusDays(3))
72 | notificationDues.add(dueDateTime.minusDays(1))
73 | }
74 | CreditPlanType.WEEKLY -> {
75 | notificationDues.add(dueDateTime.minusDays(3))
76 | notificationDues.add(dueDateTime.minusDays(1))
77 | notificationDues.add(dueDateTime.minusHours(3))
78 | }
79 | CreditPlanType.DAILY -> {
80 | notificationDues.add(dueDateTime.minusHours(3))
81 | notificationDues.add(dueDateTime.minusHours(1))
82 | }
83 | }
84 | // Remove past due reminder notifications.
85 | notificationDues.retainAll { date -> DateTimeHelper.isInFuture(date) }
86 | return notificationDues
87 | }
88 |
89 | private fun setAlarm(alarmAction: String, time: ZonedDateTime, dueDateString: String, alarmRequestCode: Int) {
90 | val timeInMilliseconds: Long = time.toOffsetDateTime().toInstant().toEpochMilli()
91 | Log.d(
92 | TAG,
93 | "$alarmAction $alarmRequestCode Alarm set for $timeInMilliseconds, it will go after" +
94 | "${timeInMilliseconds - System.currentTimeMillis()} ms"
95 | )
96 | val pendingIntent = getPendingIntent(alarmAction, dueDateString, alarmRequestCode)
97 | alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMilliseconds, pendingIntent)
98 | }
99 |
100 | private fun getPendingIntent(alarmAction: String, dueDateString: String, alarmRequestCode: Int): PendingIntent {
101 | val intent = Intent(context, AlarmReceiver::class.java).apply {
102 | action = alarmAction
103 | }.putExtra(AlarmReceiver.EXTRA_REQUEST_CODE, alarmRequestCode)
104 | .putExtra(AlarmReceiver.EXTRA_DUE_DATE, dueDateString)
105 | return PendingIntent.getBroadcast(context, alarmRequestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT)
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/firebase/BayPilotFirebaseMessagingService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.firebase
18 |
19 | import android.util.Log
20 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
21 | import com.ape.apps.sample.baypilot.util.dlc.DeviceLockMessenger
22 | import com.ape.apps.sample.baypilot.util.dlc.DeviceLockServiceProtocol
23 | import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker
24 | import com.google.firebase.messaging.FirebaseMessagingService
25 | import com.google.firebase.messaging.RemoteMessage
26 | import kotlinx.coroutines.Dispatchers
27 | import kotlinx.coroutines.GlobalScope
28 | import kotlinx.coroutines.launch
29 |
30 | // Class to process messages from Firebase Cloud Messaging(FCM).
31 | // Whenever a new FCM token is generated for the device(this will happen after factory reset) this class
32 | // will register that token with the database to send future credit plan details updates to app.
33 | class BayPilotFirebaseMessagingService : FirebaseMessagingService() {
34 |
35 | companion object {
36 | private const val TAG = "BayPilotFirebaseMsgService"
37 |
38 | // Key used by FCM to send SYNC command to app to fetch latest credit plan details from database.
39 | // This is send whenver there has been an update in database corresponding to device's IMEI entry.
40 | const val DLC_COMMAND = "dlcCommand"
41 | }
42 |
43 | // Stores connection to DLC.
44 | private lateinit var messenger: DeviceLockMessenger
45 |
46 | override fun onCreate() {
47 | super.onCreate()
48 |
49 | messenger = DeviceLockMessenger()
50 | }
51 |
52 | override fun onNewToken(token: String) {
53 | Log.d(TAG, "onNewToken() called with: token = $token")
54 |
55 | // Register this token in Database.
56 | sendRegistrationToServer(token)
57 | }
58 |
59 | // Process new messages send from FCM. We are sending Data Messages so they can received irrespective of
60 | // whether the app is in foreground or background.
61 | override fun onMessageReceived(remoteMessage: RemoteMessage) {
62 | Log.d(TAG, "onMessageReceived() called with: remoteMessage = $remoteMessage")
63 |
64 | remoteMessage.data.let { data ->
65 | data[DLC_COMMAND]?.let { dlcCommand ->
66 | // Send LOCK and UNLOCK command to DLC according to message received.
67 | when (dlcCommand) {
68 | // TODO: Remove LOCK and UNLOCK. They were added just for testing we don't want to support forced locking/unlocking.
69 | "LOCK" -> {
70 | Log.d(TAG, "LOCK received")
71 | GlobalScope.launch(Dispatchers.IO) {
72 | messenger.bindAndSendMessage(applicationContext, DeviceLockMessenger.LOCK)
73 | }
74 | }
75 | "UNLOCK" -> {
76 | Log.d(TAG, "UNLOCK received")
77 | GlobalScope.launch(Dispatchers.IO) {
78 | messenger.bindAndSendMessage(applicationContext, DeviceLockMessenger.UNLOCK)
79 | }
80 | }
81 | "SYNC" -> {
82 | Log.d(TAG, "SYNC received. Fetching credit details from database")
83 | DatabaseSyncWorker.scheduleSync(applicationContext)
84 | }
85 | "RELEASE" -> {
86 | Log.d(TAG, "RELEASE received. Releasing the device from financed mode.")
87 | GlobalScope.launch(Dispatchers.IO) {
88 | messenger.bindToDlcAndWait(applicationContext)
89 | messenger.sendMessage(DeviceLockServiceProtocol.CLIENT_MSG_CLEAR_OWNER)
90 | val sharedPreferencesManager = SharedPreferencesManager(applicationContext)
91 | sharedPreferencesManager.markDeviceReleased()
92 | }
93 | }
94 | else -> Log.d(TAG, "Unknown Command = $dlcCommand")
95 | }
96 | }
97 | }
98 | }
99 |
100 | // Register FCM token with Database.
101 | private fun sendRegistrationToServer(token: String) {
102 | val sharedPreferencesManager = SharedPreferencesManager(applicationContext)
103 |
104 | // TODO: add empty IMEI handling.
105 | // Retrieve IMEI from sharedPreferences.
106 | val imei = sharedPreferencesManager.readIMEI()
107 | Log.d(TAG, "Setting Token for imei: $imei to $token")
108 |
109 | // Store the token in database under device IMEI.
110 | val databaseManager = FirebaseDatabaseManager()
111 | databaseManager.storeFcmToken(token, imei)
112 | }
113 |
114 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Kiosk app reference implementation
2 |
3 | This is a reference implementation of DLC Kiosk app, intended to help Android
4 | ecosystem partners (carriers, OEMs, SIs) understand how to integrate their own
5 | Kiosk app with DLC APIs. It serves both as a sample Kiosk app and as a testing &
6 | development application for DLC APIs. It supports devices running Android 11.0
7 | and above.
8 |
9 | ### Getting started
10 |
11 | - You can directly import this repo into Android Studio or download/clone
12 | it and build using `gradle`
13 | - You will need an Android 12 device or a DLC compatible Android 11 device
14 |
15 | You can find more information about DLC in the partner documentation at https://docs.partner.android.com/gms/building/integrating/device-lock & https://docs.partner.android.com/gms/building/integrating/device-lock/requirements
16 |
17 | ### Prepare
18 |
19 | We have used Firebase cloud messaging to send lock / unlock commands to the
20 | device, however this is entirely optional. You can implement your logic and use
21 | your preferred service provider for push messaging.
22 | If you need to simply try out the Kiosk app reference implementation as is, you
23 | need to configure the project as follows:
24 |
25 | 1. Create a new Firebase project at
26 | [https://console.firebase.google.com/](https://console.firebase.google.com/)
27 | 1. Add an Android app in your project
28 | 1. The default package name is `com.ape.apps.sample.baypilot`. If
29 | you are creating your own app, then you might need to refactor the
30 | package name in Android Studio. Enter the package name in the firebase console.
31 | 1. Select a nickname of your choice.
32 | 1. Register.
33 | 1. Download the generated `google-services.json` file and copy it in
34 | your project folder as directed in Firebase console / documentation.
35 | 1. Finish the remaining setup. Firebase sdk libraries have already
36 | been added to the projects.
37 |
38 | 1. Turn on Anonymous authentication for your app in Firebase.
39 |
40 | ### Build
41 |
42 | 1. From the `bay-pilot` folder, build the kiosk app
43 |
44 | ```
45 | ./gradlew clean build
46 | ```
47 |
48 | This will build the apk and output it at
49 | `app/build/outputs/apk/debug/app_debug.apk`
50 |
51 | ### Deploy
52 |
53 | #### Using QR Code
54 |
55 | Note: This method does not currently work on Android 12. You will need a
56 | compatible Android 11 userdebug build.
57 |
58 | 1. Factory reset the device
59 | 1. Sideload the kiosk app and dev DLC apk on the device. Contact your Google
60 | poc for the dev DLC apk.
61 |
62 | ```
63 | adb install app-debug.apk
64 | adb install devicelock_dev.apk
65 | ```
66 |
67 | 1. Tap anywhere on the screen six times to start the QR code scanner
68 | 1. The following is a sample config, for a test QR code:
69 |
70 | ```
71 | {
72 | 'android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED': true,
73 | 'android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS': false,
74 | 'android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE': {
75 | 'com.google.android.apps.devicelock.CREDITOR_PACKAGE': 'com.ape.apps.sample.baypilot',
76 | 'com.google.android.apps.devicelock.CREDITOR_SETUP_ACTIVITY': 'com.ape.apps.sample.baypilot/com.ape.apps.sample.baypilot.ui.welcome.WelcomeActivity',
77 | 'com.google.android.apps.devicelock.CREDITOR_NAME': 'Bay Pilot Creditor',
78 | 'com.google.android.apps.devicelock.CREDITOR_ALLOWLIST_0': 'com.android.chrome',
79 | 'com.google.android.apps.devicelock.EXTRA_CREDITOR_READ_IMEI_ALLOWED': true
80 | }
81 | }
82 | ```
83 |
84 | QR Code:
85 | 
86 |
87 | You can modify the config but make sure to re-generate the QR Code using any QR
88 | Code tool of your choice,
89 |
90 | 1. Complete the Setup Wizard and you should see the kiosk app setup activity.
91 |
92 | #### ZeroTouch
93 |
94 | - You need to sign an Android Enterprise ZeroTouch agreement to obtain
95 | access to the ZeroTouch portal.
96 | - Once you have access to the ZeroTouch portal, you can enroll your
97 | device's IMEI and add the configuration in the portal.
98 | - After that, factory reset the device and set up as usual to trigger DLC
99 | provisioning.
100 |
101 | ### Features
102 |
103 | The sample Kiosk app demonstrates the following features:
104 |
105 | 1. Kiosk app Onboarding flow
106 | 1. Home screen, with device payment info, upcoming due date, locking status,
107 | a "pay now" button to redirect to FoP of choice, quick access to settings,
108 | dialer, refreshing the screen and getting support
109 | 1. Locking / Unlocking capabilities
110 | 1. Show Notifications per device lock guidelines
111 |
112 | ### Support
113 |
114 | If you've found an error in this sample, please file an issue:
115 | https://github.com/google/kiosk-app-reference-implementation/issues
116 | Patches are encouraged, and may be submitted by forking this project and
117 | submitting a pull request through GitHub.
118 |
119 | ### License
120 |
121 | The code is published under Apache License 2.0. See LICENSE.md for details
122 |
123 | ### How to make contributions?
124 |
125 | Please read and follow the steps in the CONTRIBUTING.md file.
126 |
127 | ### Disclaimer
128 |
129 | This is not an official Google project. If you plan to incorporate the features
130 | demonstrated, please carefully review the code and proceed at your own risk.
131 |
--------------------------------------------------------------------------------
/bay-pilot/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 | 1636347688851
103 |
104 |
105 | 1636347688851
106 |
107 |
108 |
109 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/ui/welcome/WelcomeViewModel.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.ui.welcome
18 |
19 | import android.content.Context
20 | import android.os.Handler
21 | import android.os.Looper
22 | import android.os.Message
23 | import android.os.Messenger
24 | import android.util.Log
25 | import androidx.lifecycle.ViewModel
26 | import androidx.lifecycle.viewModelScope
27 | import com.ape.apps.sample.baypilot.R
28 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
29 | import com.ape.apps.sample.baypilot.util.dlc.DeviceLockMessenger
30 | import com.ape.apps.sample.baypilot.util.dlc.DeviceLockServiceProtocol
31 | import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker
32 | import com.google.firebase.database.FirebaseDatabase
33 | import com.google.firebase.messaging.FirebaseMessaging
34 | import kotlinx.coroutines.launch
35 |
36 | class WelcomeViewModel : ViewModel() {
37 |
38 | companion object {
39 | private const val TAG = "BayPilotWelcomeViewModel"
40 | }
41 |
42 | override fun onCleared() {
43 | super.onCleared()
44 |
45 | Log.d(TAG, "onCleared() called")
46 | }
47 |
48 | fun checkFirstRun(context: Context) {
49 | val sharedPreferencesManager = SharedPreferencesManager(context)
50 |
51 | val isFirstRun = sharedPreferencesManager.isFirstRun()
52 | if (isFirstRun) {
53 | Log.d(TAG, "Reached here means there was error in first initial setup.")
54 |
55 | initialSetup(context)
56 | } else {
57 | Log.d(TAG, "Not first run...")
58 | }
59 | }
60 |
61 | // Initial Setup to be run when app is first run.
62 | // Get IMEI from DLC -> Store it in SharedPreferences
63 | // -> Fetch CreditPlan details from Database
64 | // -> Store firebase token for device in database.
65 | fun initialSetup(context: Context) {
66 | Log.d(TAG, "initialSetup() called with: context")
67 |
68 | val messenger = DeviceLockMessenger()
69 |
70 | viewModelScope.launch {
71 | val connected = messenger.bindToDlcAndWait(context)
72 |
73 | if (connected) {
74 | Log.d(TAG, "Connected to DLC. Getting IMEI")
75 |
76 | // Messenger to handle reply from DLC for imei and run further setup.
77 | val replyMessenger = Messenger(object : Handler(Looper.getMainLooper()) {
78 | override fun handleMessage(msg: Message) {
79 | super.handleMessage(msg)
80 |
81 | Log.d(TAG, "handleMessage() called with: msg = $msg")
82 |
83 | if (msg.what == DeviceLockServiceProtocol.CLIENT_MSG_QUERY_IMEI) {
84 | // Retrieve imei from reply.
85 | val bundle = msg.data
86 | val imei = bundle.getString(DeviceLockServiceProtocol.KEY_IMEI) ?: ""
87 | Log.d(TAG, "Received IMEI = $imei")
88 |
89 | // Write IMEI to sharedPreferences to access easily for future references.
90 | val sharedPreferencesManager = SharedPreferencesManager(context)
91 | sharedPreferencesManager.writeIMEI(imei)
92 | Log.d(TAG, "Wrote IMEI to sharedPreferences. Scheduling Sync")
93 |
94 | // Schedule first sync to fetch credit details from Realtime DB
95 | DatabaseSyncWorker.scheduleSync(context)
96 |
97 | // Get unique token for Firebase Cloud Messaging and store it in Realtime DB under device IMEI
98 | // to send updates to device whenever credit plan is updated.
99 | FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
100 | Log.d(TAG, "Setting FCM Token for imei: $imei to $token during initial setup")
101 |
102 | // Token fetched successfully, Connect to Realtime DB and store FCM token.
103 | val database = FirebaseDatabase.getInstance()
104 | val imeiRef = database.getReference(imei)
105 | imeiRef.child(context.getString(R.string.firebase_token_column)).setValue(token).addOnSuccessListener {
106 | Log.d(TAG, "FCM token successfully stored in Database. Setting first run to false in sharedPrefs")
107 | sharedPreferencesManager.writeFirstRun(false)
108 | }
109 | }.addOnFailureListener { error ->
110 | Log.e(TAG, "Failed to connect to firebase to get FCM token: $error")
111 | // TODO: Add some retry. currently working when restarting app once.
112 | }
113 | }
114 | }
115 | })
116 |
117 | // Send messenger to query IMEI and use above messenger to handle reply.
118 | messenger.sendMessage(DeviceLockServiceProtocol.CLIENT_MSG_QUERY_IMEI, replyMessenger)
119 | } else {
120 | Log.e(TAG, "Couldn't connect to DLC")
121 | }
122 | }
123 | }
124 |
125 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
176 |
181 |
186 |
187 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/dlc/DeviceLockMessenger.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.dlc
18 |
19 | import android.content.ComponentName
20 | import android.content.Context
21 | import android.content.Intent
22 | import android.content.ServiceConnection
23 | import android.os.*
24 | import android.util.Log
25 | import android.widget.Toast
26 | import com.ape.apps.sample.baypilot.R
27 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
28 | import kotlin.coroutines.resume
29 | import kotlin.coroutines.suspendCoroutine
30 |
31 | // Class to connect to Device Lock Controller(DLC) and send LOCK/UNLOCK commands, get device status and imei.
32 | class DeviceLockMessenger {
33 |
34 | companion object {
35 | private const val TAG = "BayPilotDeviceLockMessenger"
36 |
37 | const val LOCK = "LOCK"
38 | const val UNLOCK = "UNLOCK"
39 | }
40 |
41 | // Messenger for DLC connection.
42 | private var messenger: Messenger? = null
43 |
44 | // Used to check DLC connection status
45 | private var bound = false
46 |
47 | // Default Messenger to handle replies from DLC
48 | private var incomingMessenger: Messenger? = null
49 |
50 | // Bind to DLC and block thread while binding. Uses suspend Coroutine for Synchronization.
51 | suspend fun bindToDlcAndWait(context: Context) = suspendCoroutine { continuation ->
52 | Log.d(TAG, "bindToDlcAndWait() called with: context")
53 |
54 | // Default messenger to handle replies from DLC.
55 | incomingMessenger = Messenger(IncomingHandler(Looper.getMainLooper(), context))
56 |
57 | // Service connection object for connection between App and DLC.
58 | val connection: ServiceConnection = object : ServiceConnection {
59 |
60 | // Get Messenger for DLC Service connection.
61 | override fun onServiceConnected(className: ComponentName, service: IBinder) {
62 | Log.d(TAG, "onServiceConnected() called with: className, service")
63 |
64 | messenger = Messenger(service)
65 | bound = true
66 |
67 | // Resume the calling thread.
68 | continuation.resume(true)
69 | }
70 |
71 | // Reset messenger on service disconnection.
72 | override fun onServiceDisconnected(className: ComponentName) {
73 | messenger = null
74 | bound = false
75 | }
76 | }
77 |
78 | val serviceIntent = Intent(DeviceLockServiceProtocol.SERVICE_ACTION)
79 | serviceIntent.setClassName(
80 | DeviceLockServiceProtocol.SERVICE_PACKAGE_NAME,
81 | DeviceLockServiceProtocol.SERVICE_CLASS_NAME
82 | )
83 |
84 | // Bind to DLC and get ServiceConnection in connection object.
85 | context.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE)
86 | }
87 |
88 | fun sendMessage(msgId: Int, replyMessenger: Messenger? = incomingMessenger) {
89 | Log.d(TAG, "sendMessage() called with: msgId = ${msgId.toDeviceLockServiceProtocol()}, replyMessenger")
90 | sendMessage(msgId, 0 /* arg1 */, replyMessenger)
91 | }
92 |
93 | private fun sendMessage(msgId: Int, arg1: Int, replyMessenger: Messenger?): Boolean {
94 | if (!bound) {
95 | Log.d(TAG, "Service is not bound. Returning")
96 | return false
97 | }
98 |
99 | Log.d(TAG, "Sending message ${msgId.toDeviceLockServiceProtocol()}")
100 |
101 | val msg = Message.obtain(null /* handler */, msgId, arg1, 0 /* arg2 */)
102 | msg.replyTo = replyMessenger
103 |
104 | try {
105 | messenger?.send(msg)
106 | } catch (e: RemoteException) {
107 | Log.e(TAG, "Failed to send message ${msgId.toDeviceLockServiceProtocol()}")
108 | return false
109 | }
110 |
111 | return true
112 | }
113 |
114 | private fun lockDevice() {
115 | sendMessage(DeviceLockServiceProtocol.CLIENT_MSG_LOCK_DEVICE)
116 | sendMessage(DeviceLockServiceProtocol.CLIENT_MSG_REGISTER_RELAUNCH_ON_DEATH)
117 | }
118 |
119 | private fun unlockDevice() {
120 | sendMessage(DeviceLockServiceProtocol.CLIENT_MSG_UNLOCK_DEVICE)
121 | }
122 |
123 | suspend fun bindAndSendMessage(context: Context, action: String) {
124 | if (!bound) {
125 | Log.d(TAG, "Binding to DLC")
126 | bindToDlcAndWait(context)
127 | }
128 |
129 | val replyMessenger = Messenger(LockUnlockHandler(Looper.getMainLooper(), action))
130 | sendMessage(DeviceLockServiceProtocol.CLIENT_MSG_IS_DEVICE_LOCKED, replyMessenger)
131 | }
132 |
133 | private class IncomingHandler(looper: Looper, val context: Context) : Handler(looper) {
134 |
135 | override fun handleMessage(msg: Message) {
136 | var text = ""
137 |
138 | when (msg.what) {
139 | DeviceLockServiceProtocol.CLIENT_MSG_IS_DEVICE_LOCKED -> {
140 | text = context.getString(
141 | if (msg.arg1 == 1) R.string.toast_device_locked else R.string.toast_device_unlocked
142 | )
143 | }
144 | DeviceLockServiceProtocol.CLIENT_MSG_QUERY_IMEI -> {
145 | val bundle = msg.data
146 | text = bundle.getString(DeviceLockServiceProtocol.KEY_IMEI) ?: ""
147 |
148 | val sharedPreferencesManager = SharedPreferencesManager(context)
149 | sharedPreferencesManager.writeIMEI(text)
150 | }
151 | }
152 |
153 | Toast.makeText(context.applicationContext, text, Toast.LENGTH_SHORT).show()
154 | }
155 |
156 | }
157 |
158 | // Checks current status of device.
159 | // action LOCK -> lock device if it is unlocked.
160 | // action UNLOCK -> unlock device if it is locked.
161 | // If device is already in asked state we don't do anything
162 | inner class LockUnlockHandler(looper: Looper, private val action: String) : Handler(looper) {
163 |
164 | override fun handleMessage(msg: Message) {
165 | when (msg.what) {
166 | DeviceLockServiceProtocol.CLIENT_MSG_IS_DEVICE_LOCKED -> {
167 | if (msg.arg1 == 1) {
168 | Log.d(TAG, "Device is currently locked")
169 |
170 | if (action == UNLOCK) {
171 | Log.d(TAG, "Unlocking device...")
172 | unlockDevice()
173 | }
174 | } else {
175 | Log.d(TAG, "Device is currently unlocked")
176 |
177 | if (action == LOCK) {
178 | Log.d(TAG, "Locking Device...")
179 | lockDevice()
180 | }
181 | }
182 | }
183 | }
184 | }
185 |
186 | }
187 |
188 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/util/worker/DatabaseSyncWorker.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.util.worker
18 |
19 | import android.app.NotificationChannel
20 | import android.app.NotificationManager
21 | import android.app.PendingIntent
22 | import android.content.Context
23 | import android.content.Intent
24 | import android.util.Log
25 | import androidx.core.app.NotificationCompat
26 | import androidx.core.app.NotificationManagerCompat
27 | import androidx.work.*
28 | import com.ape.apps.sample.baypilot.R
29 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
30 | import com.ape.apps.sample.baypilot.ui.home.HomeActivity
31 | import com.ape.apps.sample.baypilot.util.alarm.AlarmSetter
32 | import com.ape.apps.sample.baypilot.util.date.DateTimeHelper
33 | import com.ape.apps.sample.baypilot.util.dlc.DeviceLockMessenger
34 | import com.ape.apps.sample.baypilot.util.firebase.FirebaseDatabaseManager
35 | import com.ape.apps.sample.baypilot.util.network.InternetConnectivity
36 |
37 | class DatabaseSyncWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
38 |
39 | companion object {
40 | private const val TAG = "BayPilotDatabaseSyncWorker"
41 |
42 | private const val CHANNEL_ID = "BayPilotNotification"
43 | private const val CHANNEL_NAME = "Due payment reminder"
44 | private const val CHANNEL_DESCRIPTION = "Shows reminder for due payments"
45 |
46 | // worker input keys
47 | const val WORK_ACTION = "ACTION"
48 | const val ALARM_DUE_DATE = "ALARM_DUE_DATE"
49 |
50 | // Actions which can be passed to this worker.
51 | const val ACTION_LOCK_DEVICE = "LOCK_DEVICE"
52 | const val ACTION_SEND_NOTIFICATION = "SEND_NOTIFICATION"
53 | const val ACTION_SYNC_TO_DATABASE = "SYNC_TO_DATABASE"
54 |
55 | fun scheduleSync(context: Context) {
56 | Log.d(TAG, "scheduleSync() called with: context")
57 |
58 | val inputData = workDataOf(
59 | WORK_ACTION to ACTION_SYNC_TO_DATABASE
60 | )
61 | val constraints = Constraints.Builder()
62 | .setRequiredNetworkType(NetworkType.CONNECTED)
63 | .build()
64 |
65 | val uploadSyncRequest =
66 | OneTimeWorkRequestBuilder().apply {
67 | setInputData(inputData)
68 | setConstraints(constraints)
69 | }.build()
70 |
71 | Log.d(TAG, "setting sync request")
72 | WorkManager
73 | .getInstance(context)
74 | .enqueue(uploadSyncRequest)
75 | }
76 | }
77 |
78 | override suspend fun doWork(): Result {
79 | val messenger = DeviceLockMessenger()
80 |
81 | val sharedPreferencesManager = SharedPreferencesManager(applicationContext)
82 | var deviceImei = sharedPreferencesManager.readIMEI()
83 |
84 | // TODO TEMP
85 | if (deviceImei == "") {
86 | deviceImei = "testimei"
87 | }
88 |
89 | val workAction = inputData.getString(WORK_ACTION)
90 | val setForDueDate = inputData.getString(ALARM_DUE_DATE)
91 |
92 | if (InternetConnectivity.isConnectedToInternet(applicationContext)) {
93 | Log.d(TAG, "Internet Connection Available. Syncing with Database for IMEI $deviceImei.")
94 | val databaseManager = FirebaseDatabaseManager()
95 | val creditPlanInfo = databaseManager.readCreditPlanInfoFromDatabase(applicationContext, deviceImei)
96 |
97 | creditPlanInfo?.let {
98 | sharedPreferencesManager.writeCreditPlan(creditPlanInfo)
99 |
100 | // If due date fetched from database is different from the one
101 | // for which LOCK/NOTIFICATION Alarm was set, then set new alarms.
102 | if (creditPlanInfo.dueDate != null && creditPlanInfo.dueDate != setForDueDate) {
103 | // Set Alarms
104 | Log.d(TAG, "Due Date shifted setting up new Alarms while $workAction")
105 | val alarmSetter = AlarmSetter(applicationContext)
106 | alarmSetter.setCreditAlarms(creditPlanInfo)
107 | // UNLOCK device if needed.
108 | if (DateTimeHelper.isDueDateInFuture(creditPlanInfo.dueDate ?: "")) {
109 | Log.d(TAG, "Due date is in future. Unlocking the device....")
110 | messenger.bindAndSendMessage(applicationContext, DeviceLockMessenger.UNLOCK)
111 | }
112 | return Result.success()
113 | }
114 | } ?: run {
115 | Log.d(TAG, "Received null CreditPlanInfo from database this shouldn't happen")
116 | return Result.retry()
117 | }
118 | } else {
119 | Log.d(TAG, "not connected to internet")
120 | }
121 |
122 | when (workAction) {
123 | ACTION_LOCK_DEVICE -> {
124 | Log.d(TAG, "Locking the device")
125 | messenger.bindAndSendMessage(applicationContext, DeviceLockMessenger.LOCK)
126 | }
127 | ACTION_SEND_NOTIFICATION -> {
128 | Log.d(TAG, "Sending reminder notification to pay installment")
129 | createNotificationChannel(applicationContext)
130 | sendNotification(applicationContext, setForDueDate)
131 | }
132 | }
133 | return Result.success()
134 | }
135 |
136 | private fun createNotificationChannel(context: Context) {
137 | // Create the NotificationChannel
138 | val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
139 | description = CHANNEL_DESCRIPTION
140 | }
141 | // Register the channel with the system
142 | val notificationManager: NotificationManager =
143 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
144 | notificationManager.createNotificationChannel(channel)
145 | }
146 |
147 | private fun sendNotification(context: Context, dueDate: String?) {
148 | val notificationMessage = if (dueDate.isNullOrEmpty()) {
149 | context.getString(R.string.general_notification_message)
150 | } else {
151 | val zonedDateTime = DateTimeHelper.getDeviceZonedDueDateTime(dueDate)
152 | val timeLeft = DateTimeHelper.getTimeDiff(context, zonedDateTime)
153 | val formattedDate = DateTimeHelper.formattedDateTime(zonedDateTime)
154 | context.getString(R.string._detailed_notification_message, timeLeft, formattedDate)
155 | }
156 |
157 | val intent = Intent(context, HomeActivity::class.java).apply {
158 | flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
159 | }
160 |
161 | val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
162 | val notificationTitle: String = context.getString(R.string.notification_title)
163 | val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
164 | .setSmallIcon(R.drawable.ic_launcher_foreground)
165 | .setContentTitle(notificationTitle)
166 | .setContentText(notificationMessage)
167 | .setStyle(
168 | NotificationCompat.BigTextStyle().bigText(notificationMessage)
169 | )
170 | .setPriority(NotificationCompat.PRIORITY_HIGH)
171 | .setCategory(NotificationCompat.CATEGORY_MESSAGE)
172 | .setContentIntent(pendingIntent)
173 | .setAutoCancel(true)
174 |
175 | with(NotificationManagerCompat.from(context)) {
176 | // notificationId is a unique int for each notification that you must define
177 | notify(0, builder.build())
178 | }
179 | }
180 |
181 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/ape/apps/sample/baypilot/ui/home/HomeActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2022 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 | * http://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 |
17 | package com.ape.apps.sample.baypilot.ui.home
18 |
19 | import android.content.Intent
20 | import android.os.Bundle
21 | import android.provider.Settings
22 | import android.util.Log
23 | import android.widget.Toast
24 | import androidx.activity.viewModels
25 | import androidx.appcompat.app.AppCompatActivity
26 | import androidx.core.content.ContextCompat
27 | import androidx.core.view.isVisible
28 | import com.ape.apps.sample.baypilot.R
29 | import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
30 | import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
31 | import com.ape.apps.sample.baypilot.databinding.ActivityHomeBinding
32 | import com.ape.apps.sample.baypilot.util.date.DateTimeHelper
33 | import com.ape.apps.sample.baypilot.util.extension.setTint
34 | import com.ape.apps.sample.baypilot.util.network.InternetConnectivity
35 | import com.ape.apps.sample.baypilot.util.network.InternetStatus
36 | import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker
37 |
38 | class HomeActivity : AppCompatActivity() {
39 |
40 | companion object {
41 | private const val TAG = "BayPilotHomeActivity"
42 | }
43 |
44 | private lateinit var binding: ActivityHomeBinding
45 |
46 | private val viewModel: HomeViewModel by viewModels()
47 |
48 | override fun onCreate(savedInstanceState: Bundle?) {
49 | Log.d(TAG, "onCreate() called with: savedInstanceState")
50 | super.onCreate(savedInstanceState)
51 |
52 | binding = ActivityHomeBinding.inflate(layoutInflater)
53 |
54 | val view = binding.root
55 | setContentView(view)
56 |
57 | binding.buttonSettings.setOnClickListener {
58 | startActivity(Intent(Settings.ACTION_SETTINGS))
59 | }
60 |
61 | binding.buttonInternetSetting.setOnClickListener {
62 | startActivity(Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY))
63 | }
64 |
65 | binding.buttonMakeACall.setOnClickListener {
66 | startActivity(Intent(Intent.ACTION_DIAL))
67 | }
68 |
69 | binding.buttonRefresh.setOnClickListener {
70 | // Check is device is online.
71 | if (InternetConnectivity.isConnectedToInternet(applicationContext)) {
72 | // Schedule Database Sync using WorkManager
73 | DatabaseSyncWorker.scheduleSync(applicationContext)
74 | } else {
75 | // Display message to connect to internet for refresh.
76 | Toast.makeText(
77 | baseContext, R.string.connect_to_internet_welcome,
78 | Toast.LENGTH_SHORT
79 | ).show()
80 | }
81 | }
82 |
83 | // Observe changes to credit plan details stored in device locally in sharedPreferences.
84 | viewModel.creditPlanInfo.observe(this) {
85 | updateUI(it)
86 | }
87 |
88 | viewModel.observeCreditPlanInfo(applicationContext)
89 |
90 | InternetConnectivity(this@HomeActivity).observe(this) {
91 | binding.buttonInternetSetting.isVisible = it == InternetStatus.OFFLINE
92 | binding.textViewInternetStatus.isVisible = it == InternetStatus.OFFLINE
93 | }
94 | }
95 |
96 | // Update UI accordingly to LOCK status of device.
97 | private fun updateUI(creditPlanInfo: CreditPlanInfo?) {
98 | Log.d(TAG, "updateUI() called with: creditPlanInfo = $creditPlanInfo")
99 |
100 | binding.relativeDeviceReleased.isVisible = false
101 | binding.relativeLayoutLoading.isVisible = false
102 | binding.relativeLayoutMissingImei.isVisible = false
103 |
104 | val sharedPreferencesManager = SharedPreferencesManager(applicationContext)
105 |
106 | if (sharedPreferencesManager.isDeviceReleased()) {
107 | Log.d(TAG, "updateUI() called with: sharedPreferencesManager.isDeviceReleased() = true")
108 | binding.relativeDeviceReleased.isVisible = true
109 | return
110 | }
111 |
112 | if (sharedPreferencesManager.isCreditPlanSaved().not()) {
113 | Log.d(TAG, "updateUI() called with: sharedPreferencesManager.isCreditPlanSaved() = false")
114 | binding.relativeLayoutLoading.isVisible = true
115 | return
116 | }
117 |
118 | if (sharedPreferencesManager.isValidCreditPlan().not()) {
119 | Log.d(TAG, "updateUI() called with: sharedPreferencesManager.isValidCreditPlan() = false")
120 | binding.relativeLayoutMissingImei.isVisible = true
121 | return
122 | }
123 |
124 | if (creditPlanInfo == null) {
125 | Log.d(TAG, "updateUI() called with: creditPlanInfo = null. Returning")
126 | return
127 | }
128 |
129 | // Get Credit Plan details.
130 | val totalAmount = creditPlanInfo.totalAmount ?: 0
131 | val nextDueAmount = creditPlanInfo.nextDueAmount ?: 0
132 | val totalPaidAmount: Int = creditPlanInfo.totalPaidAmount ?: 0
133 | val totalDueAmount: Int = totalAmount - totalPaidAmount
134 |
135 | // Populate Ui components with credit plan details.
136 | binding.textViewTotalCost.text = getString(R.string.total_cost, totalAmount)
137 | binding.textViewPaid.text = getString(R.string.paid_so_far, totalPaidAmount)
138 | binding.textViewRemaining.text = getString(R.string.remaining, (totalAmount - totalPaidAmount))
139 |
140 | binding.progressIndicatorOwedNow.progress = (totalDueAmount.toDouble() / totalAmount.toDouble() * 100).toInt()
141 | binding.progressIndicatorPaid.progress = (totalPaidAmount.toDouble() / totalAmount.toDouble() * 100).toInt()
142 |
143 | // Get next due date.
144 | val dueDateTime = DateTimeHelper.getDeviceZonedDueDateTime(creditPlanInfo.dueDate ?: "")
145 | val timeLeft = DateTimeHelper.getTimeDiff(applicationContext, dueDateTime)
146 | // Get formatted due date to display in UI.
147 | val formattedDueDateTime = DateTimeHelper.formattedDateTime(dueDateTime)
148 |
149 | // Device must be unlocked if due date is in future.
150 | if (DateTimeHelper.isInFuture(dueDateTime)) {
151 | // Show unlocked device UI
152 | unlockUI(nextDueAmount, timeLeft, formattedDueDateTime)
153 | } else {
154 | // Show locked device UI
155 | lockUI(nextDueAmount, timeLeft, formattedDueDateTime)
156 | }
157 | }
158 |
159 | private fun unlockUI(nextDueAmount: Int, remainingTime: String, formattedDate: String) {
160 | binding.textViewNextPayment.text = getString(R.string.installment_due_on, nextDueAmount, formattedDate)
161 | binding.textViewPaymentDue.text = getString(R.string.due_in, nextDueAmount, remainingTime)
162 |
163 | // If due date is in less than an hour set background color to red.
164 | if (remainingTime == "0 hours") {
165 | binding.frameLayoutPaymentDue.setBackgroundColor(ContextCompat.getColor(this@HomeActivity, R.color.red))
166 | } else {
167 | binding.frameLayoutPaymentDue.setBackgroundColor(ContextCompat.getColor(this@HomeActivity, R.color.green))
168 | }
169 | binding.imageViewDeviceStatus.setTint(R.color.green)
170 | binding.textViewDeviceStatus.text = getString(R.string.device_unlocked)
171 | }
172 |
173 | private fun lockUI(nextDueAmount: Int, remainingTime: String, formattedDate: String) {
174 | binding.textViewNextPayment.text = getString(R.string.installment_was_due_on, nextDueAmount, formattedDate)
175 | binding.textViewPaymentDue.text = getString(R.string.overdue_by, nextDueAmount, remainingTime)
176 | binding.frameLayoutPaymentDue.setBackgroundColor(ContextCompat.getColor(this@HomeActivity, R.color.red))
177 | binding.imageViewDeviceStatus.setTint(R.color.red)
178 | binding.textViewDeviceStatus.text = getString(R.string.device_locked_payment_overdue)
179 | }
180 |
181 | }
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_home.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
24 |
25 |
28 |
29 |
35 |
36 |
37 |
38 |
43 |
44 |
54 |
55 |
64 |
65 |
73 |
74 |
75 |
76 |
86 |
87 |
94 |
95 |
105 |
106 |
116 |
117 |
118 |
119 |
128 |
129 |
137 |
138 |
151 |
152 |
161 |
162 |
171 |
172 |
173 |
174 |
180 |
181 |
190 |
191 |
200 |
201 |
202 |
208 |
209 |
218 |
219 |
220 |
221 |
226 |
227 |
232 |
233 |
241 |
242 |
243 |
244 |
250 |
251 |
258 |
259 |
260 |
261 |
272 |
273 |
287 |
288 |
298 |
299 |
309 |
310 |
318 |
319 |
320 |
321 |
330 |
331 |
341 |
342 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
--------------------------------------------------------------------------------