├── .DS_Store ├── LICENSE ├── PRIVACY POLICY FOR MOBILE APPLICATION.pdf ├── README.md ├── app ├── .DS_Store ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── release │ ├── .DS_Store │ └── app-release.aab └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── immortalweeds │ │ └── pedometer │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── immortalweeds │ │ │ └── pedometer │ │ │ ├── CountStep.kt │ │ │ ├── GgMapTest.kt │ │ │ ├── GpsMap.kt │ │ │ ├── UserSetup.kt │ │ │ ├── builders │ │ │ └── WeekChartBuilder.kt │ │ │ ├── database │ │ │ └── DatabasePreference.kt │ │ │ ├── model │ │ │ ├── countstep │ │ │ │ └── Week.kt │ │ │ └── gps │ │ │ │ ├── Admin.kt │ │ │ │ ├── Geometry.kt │ │ │ │ ├── Leg.kt │ │ │ │ ├── Route.kt │ │ │ │ ├── Routes.kt │ │ │ │ └── Waypoint.kt │ │ │ └── network │ │ │ └── ApiInterface.kt │ ├── logo-playstore.png │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ ├── fringe.xml │ │ ├── ic_baseline_directions_run_24.xml │ │ ├── ic_baseline_local_fire_department_24.xml │ │ ├── ic_baseline_map_24.xml │ │ ├── ic_launcher_background.xml │ │ └── logo_background.xml │ │ ├── layout │ │ ├── abs_layout.xml │ │ ├── activity_count_step.xml │ │ ├── activity_gps_map.xml │ │ ├── activity_user_setup.xml │ │ └── fragment_gg_map_test.xml │ │ ├── menu │ │ ├── bottom_navigation.xml │ │ └── current_place_menu.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ ├── ic_launcher_round.xml │ │ ├── logo.xml │ │ └── logo_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_round.webp │ │ ├── logo.png │ │ ├── logo_foreground.png │ │ └── logo_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_round.webp │ │ ├── logo.png │ │ ├── logo_foreground.png │ │ └── logo_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_round.webp │ │ ├── logo.png │ │ ├── logo_foreground.png │ │ └── logo_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_round.webp │ │ ├── logo.png │ │ ├── logo_foreground.png │ │ └── logo_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_round.webp │ │ ├── logo.png │ │ ├── logo_foreground.png │ │ └── logo_round.png │ │ ├── values-night │ │ └── themes.xml │ │ ├── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── themes.xml │ │ └── xml │ │ ├── backup_rules.xml │ │ └── data_extraction_rules.xml │ └── test │ └── java │ └── com │ └── immortalweeds │ └── pedometer │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── local.properties └── settings.gradle /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Weedlly/Pedometer/411c6fcf45a7a9aa34214148264297b345211ed7/.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PRIVACY POLICY FOR MOBILE APPLICATION.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Weedlly/Pedometer/411c6fcf45a7a9aa34214148264297b345211ed7/PRIVACY POLICY FOR MOBILE APPLICATION.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pedometer 2 | How far can we go per day? Let me help you counting it ^^ 3 | 4 | - Setting your target step per day 5 | 6 | ![Goal](https://user-images.githubusercontent.com/80594990/190896900-cd1e7d51-d0dd-4459-9d2a-8e87f8621f65.png) 7 | 8 | 9 | - Counting your step 10 | 11 | ![Counter](https://user-images.githubusercontent.com/80594990/190896916-49384115-f337-42a0-9745-9afc5f4302b3.png) 12 | 13 | 14 | - Gps Training: practice in real time with Gps system 15 | 16 | ![GPSTraining](https://user-images.githubusercontent.com/80594990/190896921-ae8db8cc-bcd5-4cd7-8ce1-7346dc2aef78.png) 17 | 18 | # LICENCE 19 | 20 | The third library and license I used to this app 21 | 22 | 1) MPAndroid Chart 23 | 24 | https://github.com/PhilJay/MPAndroidChart 25 | 26 | http://www.apache.org/licenses/LICENSE-2.0 27 | 28 | 2) Circular Progress Bar 29 | 30 | https://github.com/lopspower/CircularProgressBar 31 | 32 | Apache License 2.0. 33 | 34 | 3) Smart Location 35 | 36 | https://github.com/mrmans0n/smart-location-lib 37 | 38 | The MIT License (MIT) 39 | -------------------------------------------------------------------------------- /app/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Weedlly/Pedometer/411c6fcf45a7a9aa34214148264297b345211ed7/app/.DS_Store -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'org.jetbrains.kotlin.android' 4 | id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' 5 | } 6 | 7 | android { 8 | compileSdk 33 9 | 10 | defaultConfig { 11 | applicationId "com.immortalweeds.pedometer" 12 | minSdk 21 13 | targetSdk 33 14 | versionCode 6 15 | versionName "1.6" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | buildTypes { 20 | release { 21 | minifyEnabled true 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | kotlinOptions { 30 | jvmTarget = '1.8' 31 | } 32 | viewBinding{ 33 | enabled = true 34 | } 35 | buildFeatures{ 36 | viewBinding = true 37 | } 38 | } 39 | 40 | dependencies { 41 | 42 | implementation 'androidx.core:core-ktx:1.8.0' 43 | implementation 'androidx.appcompat:appcompat:1.5.1' 44 | implementation 'com.google.android.material:material:1.6.1' 45 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 46 | implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.5.1' 47 | implementation 'androidx.navigation:navigation-fragment-ktx:2.5.2' 48 | implementation 'androidx.navigation:navigation-ui-ktx:2.5.2' 49 | 50 | 51 | 52 | testImplementation 'junit:junit:4.13.2' 53 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 54 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 55 | 56 | // Google map service 57 | implementation 'com.google.android.gms:play-services-maps:18.1.0' 58 | implementation 'com.google.maps.android:android-maps-utils:2.2.0' 59 | implementation 'com.google.android.libraries.places:places:2.6.0' 60 | 61 | // Call APi convert json to object 62 | implementation 'com.squareup.retrofit2:retrofit:2.9.0' 63 | implementation 'com.squareup.retrofit2:converter-gson:2.9.0' 64 | implementation 'com.google.code.gson:gson:2.9.1' 65 | 66 | 67 | // For app interface 68 | implementation 'com.mikhaellopez:circularprogressbar:3.1.0' 69 | implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' 70 | 71 | // Handle error 400 72 | implementation 'com.android.volley:volley:1.2.1' 73 | 74 | // Continuous update location 75 | implementation 'io.nlopez.smartlocation:library:3.3.3' 76 | 77 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1" 78 | } -------------------------------------------------------------------------------- /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/release/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Weedlly/Pedometer/411c6fcf45a7a9aa34214148264297b345211ed7/app/release/.DS_Store -------------------------------------------------------------------------------- /app/release/app-release.aab: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Weedlly/Pedometer/411c6fcf45a7a9aa34214148264297b345211ed7/app/release/app-release.aab -------------------------------------------------------------------------------- /app/src/androidTest/java/com/immortalweeds/pedometer/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.example.pedometer", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 23 | 24 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 36 | 39 | 40 | 43 | 46 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/CountStep.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer 2 | 3 | import android.content.Context 4 | import android.content.Intent 5 | import android.content.pm.PackageManager 6 | import android.hardware.Sensor 7 | import android.hardware.SensorEvent 8 | import android.hardware.SensorEventListener 9 | import android.hardware.SensorManager 10 | import android.os.Build 11 | import android.os.Bundle 12 | import android.util.Log 13 | import android.widget.Toast 14 | import androidx.appcompat.app.ActionBar 15 | import androidx.appcompat.app.AppCompatActivity 16 | import androidx.core.app.ActivityCompat 17 | import androidx.core.content.ContextCompat 18 | import androidx.core.view.get 19 | import com.github.mikephil.charting.charts.BarChart 20 | import com.google.android.material.bottomnavigation.BottomNavigationView 21 | import com.immortalweeds.pedometer.builders.WeekChart 22 | import com.immortalweeds.pedometer.database.DatabasePreference 23 | import com.immortalweeds.pedometer.databinding.AbsLayoutBinding 24 | import com.immortalweeds.pedometer.databinding.ActivityCountStepBinding 25 | import com.immortalweeds.pedometer.model.countstep.Week 26 | import java.text.DateFormatSymbols 27 | import java.util.* 28 | import kotlin.math.roundToInt 29 | 30 | const val FOOT_TO_METER = 0.7867 31 | const val FOOT_TO_CALORIE = 0.0667 32 | class CountStep : AppCompatActivity(), SensorEventListener { 33 | //Sensor and CountStep 34 | private var sensorManager: SensorManager? = null 35 | private var running = false 36 | private var totalStep: Float = 0f 37 | private var maxStep: Float? = null 38 | 39 | // Static data 40 | companion object { 41 | private const val PERMISSIONS_REQUEST_ACCESS_ACTIVITY_RECOGNITION = 2 42 | private const val TAG = "CountStep" 43 | private val X_TITLE: Array = 44 | arrayOf("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT") 45 | } 46 | private var todayNumber : Int? = null 47 | private var barChart: BarChart? = null 48 | private var databasePreference: DatabasePreference? = null 49 | 50 | private var myWeek: Week? = Week() 51 | 52 | private var binding: ActivityCountStepBinding? = null 53 | private var absBinding: AbsLayoutBinding? = null 54 | 55 | private var activityRecognitionGranted = false 56 | 57 | @Suppress("DEPRECATION") 58 | override fun onCreate(savedInstanceState: Bundle?) { 59 | super.onCreate(savedInstanceState) 60 | binding = ActivityCountStepBinding.inflate(layoutInflater) 61 | setContentView(binding!!.root) 62 | 63 | //Setup Activity Custom action bar 64 | supportActionBar!!.setDisplayHomeAsUpEnabled(true) 65 | 66 | supportActionBar!!.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM 67 | absBinding = AbsLayoutBinding.inflate(layoutInflater) 68 | 69 | supportActionBar!!.customView = absBinding!!.root 70 | absBinding!!.activityTitleTv.text = baseContext.resources.getString(R.string.count_step_activity_title) 71 | //Bottom navigation 72 | bottomNavigationHandle() 73 | 74 | loadWeekData() 75 | maxStep = myWeek!!.stepPerDay!!.toFloat() 76 | binding!!.progressCircular.progressMax = maxStep!! 77 | 78 | // Init database 79 | databasePreference = DatabasePreference(baseContext) 80 | myWeek = databasePreference!!.initData(0) 81 | todayNumber = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) 82 | loadWeekData() 83 | maxStep = myWeek!!.stepPerDay!!.toFloat() 84 | binding!!.progressCircular.progressMax = maxStep!! 85 | 86 | binding!!.totalMaxStepTv.text =baseContext.resources.getString(R.string.aim_step,maxStep!!.toInt()) 87 | Log.v(TAG, "Max step : $maxStep") 88 | 89 | //Counter monitor 90 | loadTime() 91 | loadData() 92 | resetStep() 93 | 94 | //Chart visualise 95 | barChart = binding!!.weeklyBarChartBc 96 | 97 | //Construct bar chart 98 | constructBarChar() 99 | // //init data to test 100 | initData() 101 | 102 | sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager 103 | 104 | } 105 | private fun loadWeekData() : Boolean { 106 | val sharedPreferences = getSharedPreferences("myPrefs",Context.MODE_PRIVATE) 107 | 108 | myWeek!!.deviceId = sharedPreferences.getString("deviceId","") 109 | myWeek!!.stepPerDay = sharedPreferences.getInt("stepPerDay",0) 110 | myWeek!!.mon = sharedPreferences.getInt("monStep",0) 111 | myWeek!!.tue = sharedPreferences.getInt("tueStep",0) 112 | myWeek!!.wed = sharedPreferences.getInt("wedStep",0) 113 | myWeek!!.thu = sharedPreferences.getInt("thuStep",0) 114 | myWeek!!.fri = sharedPreferences.getInt("friStep",0) 115 | myWeek!!.sat = sharedPreferences.getInt("satStep",0) 116 | myWeek!!.sun = sharedPreferences.getInt("sunStep",0) 117 | return true 118 | } 119 | private fun constructBarChar() { 120 | barChart = WeekChart.WeekChartBuilder( 121 | barChart!!, 122 | baseContext, 123 | X_TITLE 124 | ) 125 | .setMaxStep(maxStep!!) 126 | .setWeek(myWeek!!).build() 127 | 128 | } 129 | 130 | private fun bottomNavigationHandle() { 131 | val bottomNavigationView: BottomNavigationView = binding!!.bottomNavigation 132 | 133 | binding!!.bottomNavigation.menu[1].isChecked = true 134 | bottomNavigationView.setOnItemSelectedListener { 135 | when (it.itemId) { 136 | R.id.gps_training -> { 137 | startActivity(Intent(this, GpsMap::class.java)) 138 | } 139 | R.id.target -> { 140 | val intentUserSetup = Intent(this, UserSetup::class.java) 141 | intentUserSetup.putExtra("isRegister", false) 142 | startActivity(intentUserSetup) 143 | } 144 | } 145 | true 146 | } 147 | } 148 | 149 | 150 | private fun initData() { 151 | 152 | binding!!.stepsTakenTv.text = ("${totalStep.toInt()}") 153 | 154 | var percent = (totalStep * 100 / maxStep!!) 155 | if (percent.isNaN()) percent = 0f 156 | binding!!.percentTv.text = 157 | baseContext.resources.getString(R.string.percent_aim, percent.roundToInt()) 158 | 159 | 160 | binding!!.progressCircular.apply { 161 | setProgressWithAnimation(totalStep) 162 | } 163 | 164 | binding!!.distanceContentTv.text = baseContext.resources.getString( 165 | R.string.distances, 166 | FOOT_TO_METER * totalStep 167 | ) 168 | binding!!.caloriesContentTv.text = baseContext.resources.getString( 169 | R.string.calories, 170 | FOOT_TO_CALORIE * totalStep 171 | ) 172 | } 173 | 174 | 175 | private fun activityRecognitionPermission(){ 176 | Log.v(TAG, "version sdk : ${Build.VERSION.SDK_INT} and version code : ${Build.VERSION_CODES.Q}") 177 | 178 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { 179 | if (ContextCompat.checkSelfPermission(this, 180 | android.Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED) { 181 | 182 | ActivityCompat.requestPermissions(this, 183 | arrayOf(android.Manifest.permission.ACTIVITY_RECOGNITION), 184 | PERMISSIONS_REQUEST_ACCESS_ACTIVITY_RECOGNITION 185 | ) 186 | } 187 | else{ 188 | activityRecognitionGranted = true 189 | } 190 | } 191 | else{ 192 | Log.v(TAG,"seftpermis ${ContextCompat.checkSelfPermission(this, 193 | "com.google.android.gms.permission.ACTIVITY_RECOGNITION")}") 194 | if (ContextCompat.checkSelfPermission(this, 195 | "com.google.android.gms.permission.ACTIVITY_RECOGNITION") == PackageManager.PERMISSION_DENIED){ 196 | 197 | ActivityCompat.requestPermissions(this, 198 | arrayOf("com.google.android.gms.permission.ACTIVITY_RECOGNITION"), 199 | PERMISSIONS_REQUEST_ACCESS_ACTIVITY_RECOGNITION) 200 | } 201 | else{ 202 | activityRecognitionGranted = true 203 | } 204 | } 205 | } 206 | override fun onRequestPermissionsResult( 207 | requestCode: Int, 208 | permissions: Array, 209 | grantResults: IntArray 210 | ) { 211 | activityRecognitionGranted = false 212 | when(requestCode){ 213 | PERMISSIONS_REQUEST_ACCESS_ACTIVITY_RECOGNITION -> { 214 | if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 215 | activityRecognitionGranted = true 216 | startSensor() 217 | } 218 | else{ 219 | Toast.makeText(this,"This activity need permission to use",Toast.LENGTH_SHORT).show() 220 | val intentUserSetup = Intent(this, UserSetup::class.java) 221 | intentUserSetup.putExtra("isRegister", false) 222 | startActivity(intentUserSetup) 223 | } 224 | } 225 | else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) 226 | } 227 | } 228 | override fun onResume() { 229 | super.onResume() 230 | running = true 231 | activityRecognitionPermission() 232 | Log.v(TAG,"permission : $activityRecognitionGranted") 233 | 234 | startSensor() 235 | } 236 | private fun startSensor(){ 237 | if (activityRecognitionGranted) { 238 | val stepSensor: Sensor? = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR) 239 | if (stepSensor == null) { 240 | Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show() 241 | } else { 242 | sensorManager?.registerListener( 243 | this, 244 | stepSensor, 245 | SensorManager.SENSOR_DELAY_FASTEST 246 | ) 247 | Toast.makeText(this, "Set up monitor!!!", Toast.LENGTH_SHORT).show() 248 | } 249 | } 250 | } 251 | 252 | override fun onPause() { 253 | super.onPause() 254 | running = false 255 | myWeek = databasePreference!!.updateSpecifyDay( 256 | myWeek!!, 257 | todayNumber!!, 258 | totalStep.toInt() 259 | ) 260 | saveData() 261 | saveWeekData() 262 | Toast.makeText(this, "Pause!!!", Toast.LENGTH_SHORT).show() 263 | Log.v(TAG, "Activity on pause, data updating!!!") 264 | } 265 | 266 | override fun onSensorChanged(p0: SensorEvent?) { 267 | Toast.makeText(this, "Counting!!!", Toast.LENGTH_SHORT).show() 268 | if (p0!!.sensor.type == Sensor.TYPE_STEP_DETECTOR) { 269 | if (running) { 270 | totalStep += p0.values[0] 271 | myWeek = databasePreference!!.updateSpecifyDay(myWeek!!,todayNumber!!,totalStep.toInt()) 272 | Log.v(TAG,"Sensor value: $totalStep") 273 | 274 | binding!!.stepsTakenTv.text = ("${totalStep.toInt()}") 275 | var percent = (totalStep * 100 / maxStep!!) 276 | if (percent.isNaN()) percent = 0f 277 | binding!!.percentTv.text = 278 | baseContext.resources.getString(R.string.percent_aim, percent.roundToInt()) 279 | 280 | binding!!.progressCircular.apply { 281 | setProgressWithAnimation(totalStep) 282 | } 283 | Toast.makeText(this, "Counting!!!", Toast.LENGTH_SHORT).show() 284 | binding!!.distanceContentTv.text = baseContext.resources.getString( 285 | R.string.distances, 286 | FOOT_TO_METER * totalStep 287 | ) 288 | binding!!.caloriesContentTv.text = baseContext.resources.getString( 289 | R.string.calories, 290 | FOOT_TO_CALORIE * totalStep 291 | ) 292 | } 293 | } 294 | } 295 | 296 | override fun onAccuracyChanged(p0: Sensor?, p1: Int) { 297 | 298 | } 299 | 300 | private fun resetStep() { 301 | binding!!.stepsTakenTv.setOnClickListener { 302 | Toast.makeText(this, "Long tap to reset steps", Toast.LENGTH_SHORT).show() 303 | } 304 | binding!!.stepsTakenTv.setOnLongClickListener { 305 | totalStep = 0f 306 | binding!!.stepsTakenTv.text = "0" 307 | binding!!.percentTv.text = baseContext.resources.getString(R.string.percent_aim, 0) 308 | saveData() 309 | saveWeekData() 310 | true 311 | } 312 | } 313 | 314 | private fun saveData() { 315 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 316 | // Save step 317 | val editor = sharedPreferences.edit() 318 | editor.putFloat("previousTotalSteps", totalStep) 319 | editor.apply() 320 | } 321 | 322 | private fun saveWeekData() { 323 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 324 | 325 | val editor = sharedPreferences.edit() 326 | 327 | Log.v(TAG,"Week save is : $myWeek") 328 | editor.putString("deviceId", myWeek!!.deviceId) 329 | editor.putInt("stepPerDay",myWeek!!.stepPerDay!!) 330 | editor.putInt("monStep",myWeek!!.mon!!) 331 | editor.putInt("tueStep",myWeek!!.tue!!) 332 | editor.putInt("wedStep",myWeek!!.wed!!) 333 | editor.putInt("thuStep",myWeek!!.thu!!) 334 | editor.putInt("friStep",myWeek!!.fri!!) 335 | editor.putInt("satStep",myWeek!!.sat!!) 336 | editor.putInt("sunStep",myWeek!!.sun!!) 337 | 338 | editor.apply() 339 | } 340 | 341 | 342 | private fun loadData() { 343 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 344 | val saveNumber = sharedPreferences.getFloat("previousTotalSteps", 0f) 345 | Log.v(TAG, "$saveNumber") 346 | totalStep = saveNumber 347 | 348 | } 349 | 350 | private fun loadTime() { 351 | val calendarInstance = Calendar.getInstance() 352 | val day = calendarInstance.get(Calendar.DAY_OF_MONTH) 353 | val month = calendarInstance.get(Calendar.MONTH) 354 | val weekday = calendarInstance.get(Calendar.DAY_OF_WEEK) 355 | binding!!.weekdaysTv.text = getWeekday(weekday) 356 | 357 | binding!!.monthAndDayTv.text = baseContext.resources.getString( 358 | R.string.month_and_day, 359 | getMonth(month), 360 | day.toString() 361 | ) 362 | } 363 | } 364 | 365 | fun getMonth(month: Int): String? { 366 | return DateFormatSymbols().months[month - 1] 367 | } 368 | fun getWeekday(weekday: Int): String? { 369 | return DateFormatSymbols().weekdays[weekday] 370 | } 371 | -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/GgMapTest.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.immortalweeds.pedometer 4 | 5 | import android.Manifest 6 | import android.annotation.SuppressLint 7 | import android.content.pm.PackageManager 8 | import android.hardware.SensorManager 9 | import android.location.Location 10 | import android.os.Build 11 | import android.os.Bundle 12 | import android.telephony.CarrierConfigManager 13 | import android.util.Log 14 | import androidx.appcompat.app.AppCompatActivity 15 | import androidx.core.app.ActivityCompat 16 | import androidx.core.content.ContextCompat 17 | import com.google.android.gms.location.FusedLocationProviderClient 18 | import com.google.android.gms.location.LocationServices 19 | import com.google.android.gms.maps.CameraUpdateFactory 20 | import com.google.android.gms.maps.GoogleMap 21 | import com.google.android.gms.maps.OnMapReadyCallback 22 | import com.google.android.gms.maps.SupportMapFragment 23 | import com.google.android.gms.maps.model.CameraPosition 24 | import com.google.android.gms.maps.model.LatLng 25 | import com.google.android.libraries.places.api.Places 26 | import com.google.android.libraries.places.api.net.PlacesClient 27 | import com.immortalweeds.pedometer.BuildConfig.MAPS_API_KEY 28 | import com.immortalweeds.pedometer.GpsMapTest.Companion.PERMISSIONS_REQUEST_ACCESS_ACTIVITY_RECOGNITION 29 | import com.immortalweeds.pedometer.database.DatabasePreference 30 | import com.immortalweeds.pedometer.databinding.AbsLayoutBinding 31 | import com.immortalweeds.pedometer.databinding.FragmentGgMapTestBinding 32 | import com.immortalweeds.pedometer.model.countstep.Week 33 | 34 | private const val baseUrl = "https://api.mapbox.com" 35 | 36 | 37 | class GpsMapTest : AppCompatActivity(), OnMapReadyCallback { 38 | 39 | private lateinit var binding: FragmentGgMapTestBinding 40 | 41 | private var absBinding : AbsLayoutBinding? = null 42 | 43 | private var markerPoints = ArrayList() 44 | private var totalStep : Float = 0f 45 | 46 | private var mGoogleMap: GoogleMap? = null 47 | private var cameraPosition: CameraPosition? = null 48 | 49 | // The entry point to the Places API. 50 | private lateinit var placesClient: PlacesClient 51 | 52 | // The entry point to the Fused Location Provider. 53 | private lateinit var fusedLocationProviderClient: FusedLocationProviderClient 54 | 55 | private var locationPermissionGranted = false 56 | private var activityRecognitionGranted = false 57 | 58 | // The geographical location where the device is currently located. That is, the last-known 59 | // location retrieved by the Fused Location Provider. 60 | 61 | private var lastKnownLocation: Location? = null 62 | private var desti: LatLng? = null 63 | 64 | private var isEnoughTwoPoint = false 65 | 66 | private var isUpdateLocation = false 67 | 68 | // Counter step 69 | private var sensorManager : SensorManager? = null 70 | 71 | // Data 72 | private var databasePreference : DatabasePreference? = null 73 | private var myWeek : Week? = null 74 | private var today : Int? = null 75 | 76 | override fun onMapReady(googleMap: GoogleMap) { 77 | this.mGoogleMap = googleMap 78 | Log.v("permiss","1") 79 | getLocationPermission() 80 | } 81 | 82 | @SuppressLint("MissingPermission") 83 | private fun getDeviceLocation() { 84 | Log.v("permiss","getDeviceLocation") 85 | try { 86 | val locationResult = fusedLocationProviderClient.lastLocation 87 | locationResult.addOnCompleteListener(this){ 88 | task -> 89 | if(task.isSuccessful) { 90 | // Set the map's camera position to the current location of the device. 91 | lastKnownLocation = task.result 92 | if (lastKnownLocation != null) { 93 | 94 | mGoogleMap?.moveCamera( 95 | (CameraUpdateFactory.newLatLngZoom( 96 | LatLng( 97 | lastKnownLocation!!.latitude, 98 | lastKnownLocation!!.longitude 99 | ), DEFAULT_ZOOM.toFloat() 100 | )) 101 | ) 102 | } 103 | } 104 | } 105 | } 106 | catch (e : SecurityException){ 107 | Log.e("Exception %e",e.message,e) 108 | } 109 | } 110 | 111 | private fun getLocationPermission(){ 112 | Log.v("permiss","2") 113 | if (ContextCompat.checkSelfPermission(this.applicationContext 114 | , Manifest.permission.ACCESS_FINE_LOCATION) 115 | == PackageManager.PERMISSION_GRANTED){ 116 | Log.v("permiss","PERMISSION_GRANTED") 117 | locationPermissionGranted = true 118 | }else{ 119 | 120 | Log.v("permiss","PERMISSION_DENNIE") 121 | ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 122 | GpsMapTest.PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION 123 | ) 124 | } 125 | 126 | } 127 | override fun onRequestPermissionsResult( 128 | requestCode: Int, 129 | permissions: Array, 130 | grantResults: IntArray 131 | ) { 132 | 133 | when(requestCode){ 134 | PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION -> { 135 | Log.v("permiss","code PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION") 136 | // If request is cancelled, the result arrays are empty. 137 | locationPermissionGranted = false 138 | if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){ 139 | Log.v("permiss","accpect") 140 | 141 | locationPermissionGranted = true 142 | // getDeviceLocation() 143 | } 144 | else{ 145 | Log.v("permiss","not accpect") 146 | onPause() 147 | } 148 | 149 | } 150 | 151 | else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) 152 | } 153 | // updateLocationUI() 154 | } 155 | // @SuppressLint("MissingPermission") 156 | // private fun updateLocationUI(){ 157 | // Log.v("permiss","updateLocationUI") 158 | // if (mGoogleMap == null){ 159 | // return 160 | // } 161 | // try{ 162 | // if (locationPermissionGranted){ 163 | // mGoogleMap?.isMyLocationEnabled = true 164 | // mGoogleMap?.uiSettings?.isMyLocationButtonEnabled = true 165 | // }else{ 166 | // mGoogleMap?.isMyLocationEnabled = false 167 | // mGoogleMap?.uiSettings?.isMyLocationButtonEnabled = true 168 | // lastKnownLocation = null 169 | // getLocationPermission() 170 | // } 171 | // } 172 | // catch (e :SecurityException){ 173 | // Log.e("Exception: %s",e.message,e) 174 | // } 175 | // } 176 | @Suppress("DEPRECATION") 177 | override fun onCreate(savedInstanceState: Bundle?) { 178 | super.onCreate(savedInstanceState) 179 | Log.v("permiss","0") 180 | binding = FragmentGgMapTestBinding.inflate(layoutInflater) 181 | setContentView(binding.root) 182 | 183 | 184 | val mapFragment = supportFragmentManager 185 | .findFragmentById(R.id.maptest) as? SupportMapFragment 186 | mapFragment?.getMapAsync (this) 187 | // Construct a PlacesClient 188 | Places.initialize(applicationContext,MAPS_API_KEY) 189 | placesClient = Places.createClient(this) 190 | 191 | // Construct a FusedLocationProviderClient. 192 | fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) 193 | 194 | } 195 | 196 | 197 | companion object { 198 | private val TAG = GpsMap::class.java.simpleName 199 | private const val DEFAULT_ZOOM = 15 200 | private const val PERMISSIONS_REQUEST_ACCESS_ACTIVITY_RECOGNITION = 2 201 | private const val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1 202 | 203 | // Keys for storing activity state. 204 | // [START maps_current_place_state_keys] 205 | private const val KEY_CAMERA_POSITION = "camera_position" 206 | private const val KEY_LOCATION = "location" 207 | 208 | } 209 | } -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/GpsMap.kt: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.immortalweeds.pedometer 4 | 5 | import android.Manifest 6 | import android.annotation.SuppressLint 7 | import android.content.Context 8 | import android.content.Intent 9 | import android.content.pm.PackageManager 10 | import android.hardware.Sensor 11 | import android.hardware.SensorEvent 12 | import android.hardware.SensorEventListener 13 | import android.hardware.SensorManager 14 | import android.location.Location 15 | import android.os.Build 16 | import android.os.Bundle 17 | import android.util.Log 18 | import android.widget.Toast 19 | import androidx.appcompat.app.ActionBar 20 | import androidx.appcompat.app.AppCompatActivity 21 | import androidx.core.app.ActivityCompat 22 | import androidx.core.content.ContextCompat 23 | import androidx.core.view.get 24 | import androidx.core.view.isVisible 25 | import com.google.android.gms.maps.CameraUpdateFactory 26 | import com.google.android.gms.maps.GoogleMap 27 | import com.google.android.gms.maps.OnMapReadyCallback 28 | import com.google.android.gms.maps.SupportMapFragment 29 | import com.google.android.gms.maps.model.* 30 | import com.google.android.libraries.places.api.Places 31 | import com.google.android.libraries.places.api.net.PlacesClient 32 | import com.google.android.material.bottomnavigation.BottomNavigationView 33 | import com.immortalweeds.pedometer.BuildConfig.MAPS_API_KEY 34 | import com.immortalweeds.pedometer.database.DatabasePreference 35 | import com.immortalweeds.pedometer.databinding.AbsLayoutBinding 36 | import com.immortalweeds.pedometer.databinding.ActivityGpsMapBinding 37 | import com.immortalweeds.pedometer.model.countstep.Week 38 | import com.immortalweeds.pedometer.model.gps.Route 39 | import com.immortalweeds.pedometer.network.ApiInterface 40 | import io.nlopez.smartlocation.SmartLocation 41 | import kotlinx.coroutines.* 42 | import retrofit2.Retrofit 43 | import retrofit2.converter.gson.GsonConverterFactory 44 | import java.util.* 45 | 46 | private const val baseUrl = "https://api.mapbox.com" 47 | 48 | const val KILOMETER_TO_CALORIE = 84 49 | class GpsMap : AppCompatActivity(), SensorEventListener, OnMapReadyCallback { 50 | 51 | private lateinit var binding: ActivityGpsMapBinding 52 | 53 | private var absBinding : AbsLayoutBinding? = null 54 | 55 | private var markerPoints = ArrayList() 56 | private var totalStep : Float = 0f 57 | 58 | private var mGoogleMap: GoogleMap? = null 59 | private var cameraPosition: CameraPosition? = null 60 | 61 | // The entry point to the Places API. 62 | private lateinit var placesClient: PlacesClient 63 | 64 | //Permission 65 | private var locationPermissionGranted = false 66 | 67 | // The geographical location where the device is currently located. That is, the last-known 68 | // location retrieved by the Fused Location Provider. 69 | 70 | private var lastKnownLocation: Location? = null 71 | private var desti: LatLng? = null 72 | 73 | private var isEnoughTwoPoint = false 74 | 75 | private var isUpdateLocation = false 76 | 77 | // Counter step 78 | private var sensorManager : SensorManager? = null 79 | 80 | // Data 81 | private var databasePreference : DatabasePreference? = null 82 | private var myWeek : Week? = Week() 83 | private var today : Int? = null 84 | 85 | @Suppress("DEPRECATION") 86 | override fun onCreate(savedInstanceState: Bundle?) { 87 | super.onCreate(savedInstanceState) 88 | binding = ActivityGpsMapBinding.inflate(layoutInflater) 89 | setContentView(binding.root) 90 | 91 | //Setup Activity Custom action bar 92 | supportActionBar!!.setDisplayHomeAsUpEnabled(true) 93 | 94 | supportActionBar!!.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM 95 | absBinding = AbsLayoutBinding.inflate(layoutInflater) 96 | supportActionBar!!.customView = absBinding!!.root 97 | absBinding!!.activityTitleTv.text = 98 | baseContext.resources.getString(R.string.title_activity_gps_map) 99 | 100 | //Bottom navigation 101 | bottomNavigationHandle() 102 | 103 | //Set up title and init value 104 | setupTitle() 105 | updateJourneyInformation(0.0, 0.0) 106 | 107 | // Init database 108 | today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) 109 | databasePreference = DatabasePreference(baseContext) 110 | myWeek = databasePreference!!.initData(0) 111 | loadWeekData() 112 | Log.v(TAG, "GPS take week : $myWeek") 113 | 114 | // button Start, Stop, Pause 115 | buttonControlListener() 116 | 117 | // savedInstanceState 118 | if (savedInstanceState != null) { 119 | Log.v(TAG,"saveInstance :$savedInstanceState") 120 | lastKnownLocation = if (Build.VERSION.SDK_INT >= 33) 121 | savedInstanceState.getParcelable(KEY_LOCATION, Location::class.java) 122 | else 123 | savedInstanceState.getParcelable(KEY_LOCATION) 124 | 125 | cameraPosition = if (Build.VERSION.SDK_INT >= 33) 126 | savedInstanceState.getParcelable( 127 | KEY_CAMERA_POSITION, 128 | CameraPosition::class.java 129 | ) 130 | else 131 | savedInstanceState.getParcelable(KEY_CAMERA_POSITION) 132 | } 133 | 134 | // Setup map 135 | val mapFragment = supportFragmentManager 136 | .findFragmentById(R.id.map) as? SupportMapFragment 137 | mapFragment?.getMapAsync(this) 138 | // Construct a PlacesClient 139 | Places.initialize(applicationContext, MAPS_API_KEY) 140 | placesClient = Places.createClient(this) 141 | 142 | // Set up sensor manager 143 | sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager 144 | 145 | } 146 | 147 | override fun onMapReady(googleMap: GoogleMap) { 148 | this.mGoogleMap = googleMap 149 | // Prompt the user for permission. 150 | getLocationPermission() 151 | 152 | Log.v(TAG,"don't waiting") 153 | locationPermissionAccepted() 154 | } 155 | private fun locationPermissionAccepted(){ 156 | if (locationPermissionGranted) { 157 | 158 | updateCurrentLocation() 159 | 160 | mGoogleMap?.setOnMyLocationButtonClickListener { 161 | handleMyLocation() 162 | } 163 | 164 | mGoogleMap!!.setOnMapClickListener { 165 | setupTrainingRoute(it) 166 | } 167 | } 168 | } 169 | 170 | override fun onSensorChanged(p0: SensorEvent?) { 171 | if (p0!!.sensor.type == Sensor.TYPE_STEP_DETECTOR){ 172 | if (isUpdateLocation) 173 | { 174 | totalStep += p0.values[0] 175 | } 176 | } 177 | } 178 | 179 | override fun onAccuracyChanged(p0: Sensor?, p1: Int) { 180 | } 181 | 182 | override fun onResume() { 183 | super.onResume() 184 | 185 | val stepSensor : Sensor? = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR) 186 | if (stepSensor == null) { 187 | Toast.makeText(this, "No sensor detected on this device", Toast.LENGTH_SHORT).show() 188 | } else { 189 | sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_FASTEST) 190 | Log.v(TAG, "Start") 191 | } 192 | } 193 | 194 | private fun getLocationPermission(){ 195 | 196 | if (ContextCompat.checkSelfPermission(this.applicationContext 197 | ,Manifest.permission.ACCESS_FINE_LOCATION) 198 | == PackageManager.PERMISSION_GRANTED){ 199 | locationPermissionGranted = true 200 | }else{ 201 | ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 202 | PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) 203 | } 204 | } 205 | 206 | override fun onRequestPermissionsResult( 207 | requestCode: Int, 208 | permissions: Array, 209 | grantResults: IntArray 210 | ) { 211 | locationPermissionGranted = false 212 | when(requestCode){ 213 | PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION -> { 214 | // If request is cancelled, the result arrays are empty. 215 | if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){ 216 | locationPermissionGranted = true 217 | locationPermissionAccepted() 218 | } 219 | else{ 220 | Toast.makeText(this,"This activity need GPS permission to use",Toast.LENGTH_SHORT).show() 221 | val intentUserSetup = Intent(this,UserSetup::class.java) 222 | intentUserSetup.putExtra("isRegister",false) 223 | startActivity(intentUserSetup) 224 | } 225 | } 226 | else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) 227 | } 228 | } 229 | 230 | 231 | @SuppressLint("MissingPermission") 232 | private fun updateCurrentLocation(){ 233 | // Start continuous location 234 | mGoogleMap!!.isMyLocationEnabled = true 235 | SmartLocation.with(baseContext).location().start{ 236 | lastKnownLocation = it 237 | Log.v(TAG, "lastKnownLocation: $lastKnownLocation") 238 | focusCurrentLocation() 239 | } 240 | // Update continuous location 241 | CoroutineScope(Dispatchers.IO).launch{ 242 | while (true) { 243 | // Get current location each 5 second 244 | delay(3000) 245 | Log.v(TAG, "isUpdateLocation $isUpdateLocation") 246 | // if (isUpdateLocation) { 247 | // CoroutineScope(Dispatchers.Main).launch { 248 | // lastKnownLocation = SmartLocation.with(baseContext).location().get().lastLocation 249 | // lastKnownLocation!!.latitude = desti!!.latitude 250 | // lastKnownLocation!!.longitude = desti!!.longitude 251 | // updateTrainingRoute( 252 | // LatLng( 253 | // lastKnownLocation!!.latitude, 254 | // lastKnownLocation!!.longitude 255 | // ) 256 | // ) 257 | // Log.v(TAG, "Update location: $lastKnownLocation") 258 | // } 259 | // } 260 | 261 | if ( isUpdateLocation) { 262 | CoroutineScope(Dispatchers.Main).launch { 263 | //get new current location 264 | lastKnownLocation = SmartLocation.with(baseContext).location().get().lastLocation 265 | updateTrainingRoute( 266 | LatLng( 267 | lastKnownLocation!!.latitude, 268 | lastKnownLocation!!.longitude 269 | ) 270 | ) 271 | Log.v(TAG, "Update location: $lastKnownLocation") 272 | } 273 | } 274 | } 275 | } 276 | } 277 | 278 | // Mark origin and dest point ,then draw line between them 279 | private fun setupTrainingRoute(it: LatLng){ 280 | if (markerPoints.size > 1){ 281 | markerPoints.clear() 282 | mGoogleMap!!.clear() 283 | isEnoughTwoPoint = false 284 | } 285 | 286 | // Adding new item to the ArrayList 287 | markerPoints.add(it) 288 | // Creating MarkerOptions 289 | val markerOptions = MarkerOptions() 290 | // Setting the position of the marker 291 | markerOptions.position(it) 292 | 293 | if (!it.equals(lastKnownLocation)){ 294 | // Only Des in Lat Array 295 | if (markerPoints.size == 1) { 296 | handleMyLocation() 297 | // Adding new item to the ArrayList 298 | markerPoints.add(it) 299 | 300 | markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) 301 | Log.v(TAG,"Array point size : ${markerPoints.size}") 302 | } 303 | // Enough 2 point in Lat Array 304 | else if (markerPoints.size == 2){ 305 | markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) 306 | } 307 | } 308 | 309 | // Add new marker to the Google Map Android API V2 310 | mGoogleMap!!.addMarker(markerOptions) 311 | // Checks, whether start and end locations are captured 312 | if (markerPoints.size >= 2){ 313 | isEnoughTwoPoint = true 314 | val origin = markerPoints[0] 315 | val dest = markerPoints[1] 316 | desti = dest 317 | val polylineOptions = PolylineOptions() 318 | 319 | // Print URL to the Google Directions API 320 | Log.v(TAG,"Direction API Url : https://api.mapbox.com/directions/v5/mapbox/walking/" + 321 | "${origin.longitude}%2C" + 322 | "${origin.latitude}%3B" + 323 | "${dest.longitude}%2C" + 324 | "${dest.latitude}?alternatives=false&geometries=geojson&overview=simplified&steps=false&access_token=pk.eyJ1Ijoid2VlZGx5IiwiYSI6ImNsN2VpMW56bjAwa2gzbnBnaHd2MjJmZGYifQ.It2pYYoWNWQ-9Ogs49OUMg" 325 | ) 326 | val route = getDirection(origin,dest) 327 | val coordinates = route.geometry.coordinates 328 | 329 | var nextStep = origin 330 | for (step in coordinates){ 331 | val lng = LatLng(step[1],step[0]) 332 | polylineOptions.add(nextStep,lng) 333 | nextStep = lng 334 | } 335 | 336 | polylineOptions.add(nextStep,dest) 337 | mGoogleMap!!.addPolyline(polylineOptions) 338 | 339 | updateJourneyInformation(route.distance,route.duration) 340 | } 341 | } 342 | 343 | // Update current location by mark and draw again 344 | private fun updateTrainingRoute(it: LatLng){ 345 | var dest : LatLng = it 346 | if (markerPoints.size > 1){ 347 | dest = markerPoints[1] 348 | markerPoints.clear() 349 | mGoogleMap!!.clear() 350 | isEnoughTwoPoint = true 351 | } 352 | // Adding new item to the ArrayList 353 | markerPoints.add(it) 354 | markerPoints.add(dest) 355 | // Creating MarkerOptions 356 | val markerOptionsDest = MarkerOptions() 357 | val markerOptionsCurrent = MarkerOptions() 358 | // Setting the position of the marker 359 | markerOptionsCurrent.position(it).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) 360 | markerOptionsDest.position(dest).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) 361 | 362 | Log.v(TAG,"Array point size : ${markerPoints.size}") 363 | 364 | // Add new marker to the Google Map Android API V2 365 | mGoogleMap!!.addMarker(markerOptionsCurrent) 366 | 367 | mGoogleMap!!.addMarker(markerOptionsDest) 368 | // Checks, whether start and end locations are captured 369 | if (markerPoints.size >= 2){ 370 | isEnoughTwoPoint = true 371 | val origin = markerPoints[0] 372 | dest = markerPoints[1] 373 | 374 | val polylineOptions = PolylineOptions() 375 | 376 | // Print URL to the Google Directions API 377 | Log.v(TAG,"Direction API Url : https://api.mapbox.com/directions/v5/mapbox/walking/" + 378 | "${origin.longitude}%2C" + 379 | "${origin.latitude}%3B" + 380 | "${dest.longitude}%2C" + 381 | "${dest.latitude}?alternatives=false&geometries=geojson&overview=simplified&steps=false&access_token=pk.eyJ1Ijoid2VlZGx5IiwiYSI6ImNsN2VpMW56bjAwa2gzbnBnaHd2MjJmZGYifQ.It2pYYoWNWQ-9Ogs49OUMg" 382 | ) 383 | val route = getDirection(origin,dest) 384 | 385 | val currentDistance = route.distance.toFloat() 386 | 387 | journeyFinishingListener(currentDistance) 388 | 389 | val coordinates = route.geometry.coordinates 390 | 391 | var nextStep = origin 392 | for (step in coordinates){ 393 | val lng = LatLng(step[1],step[0]) 394 | polylineOptions.add(nextStep,lng) 395 | nextStep = lng 396 | } 397 | 398 | polylineOptions.add(nextStep,dest) 399 | mGoogleMap!!.addPolyline(polylineOptions) 400 | 401 | updateJourneyInformation(route.distance,route.duration) 402 | } 403 | } 404 | private fun journeyFinishingListener(currentDistance : Float){ 405 | if (currentDistance <= 10f){ 406 | // Notify to user they finish journey 407 | Toast.makeText(this, "Congratulating you finished journey ", Toast.LENGTH_SHORT) 408 | .show() 409 | 410 | // Focus my location 411 | handleMyLocation() 412 | isUpdateLocation = false 413 | binding.stopBt.isVisible = false 414 | binding.pauseBt.isVisible = false 415 | binding.startBt.isVisible = true 416 | setupTitle() 417 | 418 | updateData() 419 | } 420 | } 421 | 422 | private fun getDirection(origin: LatLng ,dest: LatLng) : Route { 423 | val retrofit = Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create()).build() 424 | val service: ApiInterface by lazy { retrofit.create(ApiInterface::class.java)} 425 | var route : Route? 426 | 427 | route = runBlocking { 428 | withContext(Dispatchers.Default) { 429 | val routes = service.getPlaces( 430 | origin.longitude, 431 | origin.latitude, 432 | dest.longitude, 433 | dest.latitude 434 | ) 435 | route = routes.routes[0] 436 | } 437 | route 438 | } 439 | return route!! 440 | } 441 | 442 | // Handle my location action 443 | private fun handleMyLocation() : Boolean{ 444 | Log.v(TAG,"Current location: $lastKnownLocation") 445 | val latLng = LatLng(lastKnownLocation!!.latitude,lastKnownLocation!!.longitude) 446 | 447 | mGoogleMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15f)) 448 | val markerOptions = MarkerOptions() 449 | if (markerPoints.isEmpty()) { 450 | markerPoints.add(latLng) 451 | } 452 | else { 453 | markerPoints.clear() 454 | mGoogleMap!!.clear() 455 | markerPoints.add(latLng) 456 | } 457 | markerOptions.position(latLng) 458 | markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) 459 | mGoogleMap!!.addMarker(markerOptions.title("You are here")) 460 | 461 | isEnoughTwoPoint = false 462 | return true 463 | } 464 | 465 | private fun focusCurrentLocation(){ 466 | if (lastKnownLocation != null) { 467 | Log.v(TAG,"lastKnownLocation :$lastKnownLocation") 468 | mGoogleMap?.moveCamera( 469 | (CameraUpdateFactory.newLatLngZoom( 470 | LatLng( 471 | lastKnownLocation!!.latitude, 472 | lastKnownLocation!!.longitude 473 | ), DEFAULT_ZOOM.toFloat() 474 | )) 475 | ) 476 | } 477 | } 478 | 479 | private fun bottomNavigationHandle(){ 480 | val bottomNavigationView : BottomNavigationView = binding.bottomNavigation 481 | 482 | binding.bottomNavigation.menu[0].isChecked = true 483 | bottomNavigationView.setOnItemSelectedListener { 484 | when(it.itemId){ 485 | R.id.home-> { 486 | val countStepIntent = Intent(this, CountStep::class.java) 487 | countStepIntent.putExtra("myWeek", myWeek) 488 | startActivity(countStepIntent) 489 | } 490 | R.id.target-> { 491 | val intentUserSetup = Intent(this,UserSetup::class.java) 492 | intentUserSetup.putExtra("isRegister",false) 493 | startActivity(intentUserSetup) 494 | } 495 | } 496 | true 497 | } 498 | } 499 | 500 | private fun buttonControlListener(){ 501 | // Press Start Button to show Stop and Pause Button, also active GPS Training 502 | binding.startBt.setOnClickListener { 503 | 504 | if (isEnoughTwoPoint) { 505 | isUpdateLocation = true 506 | binding.startBt.isVisible = false 507 | binding.stopBt.isVisible = true 508 | binding.pauseBt.isVisible = true 509 | } 510 | else { 511 | // Requiring choose destination point to start 512 | Toast.makeText(this, "Choosing location you want to moving ", Toast.LENGTH_SHORT) 513 | .show() 514 | // Focus my location 515 | handleMyLocation() 516 | } 517 | } 518 | 519 | // Stopping Gps training then show Start button 520 | binding.stopBt.setOnClickListener { 521 | handleMyLocation() 522 | isUpdateLocation = false 523 | binding.stopBt.isVisible = false 524 | binding.pauseBt.isVisible = false 525 | binding.startBt.isVisible = true 526 | setupTitle() 527 | } 528 | 529 | binding.pauseBt.setOnClickListener { 530 | if (binding.pauseBt.text == "PAUSE") { 531 | isUpdateLocation = false 532 | binding.pauseBt.text = getString(R.string.continue_button) 533 | } 534 | // binding.pauseBt.text = CONTINUE 535 | else{ 536 | isUpdateLocation = true 537 | updateTrainingRoute(LatLng(lastKnownLocation!!.latitude,lastKnownLocation!!.longitude)) 538 | binding.pauseBt.text = getString(R.string.pause_button) 539 | } 540 | } 541 | } 542 | 543 | private fun saveData() { 544 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 545 | // Save step 546 | val editor = sharedPreferences.edit() 547 | editor.putFloat("previousTotalSteps", totalStep) 548 | editor.apply() 549 | } 550 | private fun loadWeekData() : Boolean { 551 | val sharedPreferences = getSharedPreferences("myPrefs",Context.MODE_PRIVATE) 552 | 553 | myWeek!!.deviceId = sharedPreferences.getString("deviceId","") 554 | myWeek!!.stepPerDay = sharedPreferences.getInt("stepPerDay",0) 555 | myWeek!!.mon = sharedPreferences.getInt("monStep",0) 556 | myWeek!!.tue = sharedPreferences.getInt("tueStep",0) 557 | myWeek!!.wed = sharedPreferences.getInt("wedStep",0) 558 | myWeek!!.thu = sharedPreferences.getInt("thuStep",0) 559 | myWeek!!.fri = sharedPreferences.getInt("friStep",0) 560 | myWeek!!.sat = sharedPreferences.getInt("satStep",0) 561 | myWeek!!.sun = sharedPreferences.getInt("sunStep",0) 562 | return true 563 | } 564 | 565 | // Set up title for some showing information 566 | private fun setupTitle(){ 567 | 568 | binding.distanceTitleTv.text = getString(R.string.distance_title) 569 | binding.distanceContentTv.text = "0" 570 | binding.durationTitleTv.text = getString(R.string.duration_title) 571 | binding.durationContentTv.text = "0" 572 | binding.caloriesTitleTv.text = getString(R.string.calorie_title) 573 | binding.caloriesContentTv.text = "0" 574 | } 575 | 576 | // Update textview which show journey information 577 | private fun updateJourneyInformation(distance : Double, duration : Double){ 578 | val kilometer = distance / 1000 579 | val hours = (duration / 3600).toInt() 580 | val minus = ((duration - hours * 3600) / 60).toInt() 581 | val second = (duration - hours * 3600 - minus * 60).toInt() 582 | binding.distanceContentTv.text = baseContext.resources.getString(R.string.distances,kilometer) 583 | binding.caloriesContentTv.text = baseContext.resources.getString(R.string.calories,kilometer * KILOMETER_TO_CALORIE) 584 | binding.durationContentTv.text = baseContext.resources.getString(R.string.duration, 585 | hours, 586 | minus, 587 | second) 588 | } 589 | 590 | private fun updateData(){ 591 | myWeek = databasePreference!!.plusStepSpecificDay( 592 | myWeek!!, 593 | today!!, 594 | totalStep.toInt()) 595 | 596 | totalStep = databasePreference!!.getStepSpecifyDay(myWeek!!, today!!).toFloat() 597 | saveData() 598 | saveWeekData() 599 | totalStep = 0f 600 | } 601 | override fun onPause() { 602 | updateData() 603 | Log.v(TAG, "Activity on pause, data updating!!!") 604 | super.onPause() 605 | } 606 | private fun saveWeekData() { 607 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 608 | // Save step 609 | val editor = sharedPreferences.edit() 610 | Log.v(TAG,"Week save is : $myWeek") 611 | editor.putString("deviceId", myWeek!!.deviceId) 612 | editor.putInt("stepPerDay",myWeek!!.stepPerDay!!) 613 | editor.putInt("monStep",myWeek!!.mon!!) 614 | editor.putInt("tueStep",myWeek!!.tue!!) 615 | editor.putInt("wedStep",myWeek!!.wed!!) 616 | editor.putInt("thuStep",myWeek!!.thu!!) 617 | editor.putInt("friStep",myWeek!!.fri!!) 618 | editor.putInt("satStep",myWeek!!.sat!!) 619 | editor.putInt("sunStep",myWeek!!.sun!!) 620 | 621 | editor.apply() 622 | } 623 | 624 | override fun onSaveInstanceState(outState: Bundle) { 625 | Log.v(TAG,"saveInstance :$outState") 626 | mGoogleMap?.let { map -> 627 | outState.putParcelable(KEY_CAMERA_POSITION, map.cameraPosition) 628 | outState.putParcelable(KEY_LOCATION, lastKnownLocation) 629 | } 630 | super.onSaveInstanceState(outState) 631 | } 632 | 633 | override fun onStop() { 634 | SmartLocation.with(baseContext).location().stop() 635 | super.onStop() 636 | } 637 | companion object { 638 | private val TAG = GpsMap::class.java.simpleName 639 | private const val DEFAULT_ZOOM = 15 640 | private const val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1 641 | 642 | // Keys for storing activity state. 643 | // [START maps_current_place_state_keys] 644 | private const val KEY_CAMERA_POSITION = "camera_position" 645 | private const val KEY_LOCATION = "location" 646 | 647 | } 648 | } -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/UserSetup.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer 2 | 3 | import android.content.Context 4 | import android.content.Intent 5 | import android.os.Bundle 6 | import android.util.Log 7 | import android.widget.Toast 8 | import androidx.appcompat.app.ActionBar 9 | import androidx.appcompat.app.AppCompatActivity 10 | import androidx.core.view.get 11 | import com.immortalweeds.pedometer.database.DatabasePreference 12 | import com.immortalweeds.pedometer.databinding.AbsLayoutBinding 13 | import com.immortalweeds.pedometer.databinding.ActivityUserSetupBinding 14 | import com.immortalweeds.pedometer.model.countstep.Week 15 | import com.google.android.material.bottomnavigation.BottomNavigationView 16 | import java.util.* 17 | 18 | class UserSetup : AppCompatActivity() { 19 | private var databasePreference : DatabasePreference? = null 20 | private var binding : ActivityUserSetupBinding? = null 21 | private var absBinding : AbsLayoutBinding? = null 22 | 23 | private var maxSteps: Float? = 0f 24 | private var calories: Float? = 0f 25 | private var isRegister : Boolean = false 26 | private var myWeek : Week? = Week() 27 | 28 | private var isInitAccount : Boolean? = null 29 | companion object{ 30 | private const val TAG = "UserSetup" 31 | } 32 | override fun onCreate(savedInstanceState: Bundle?) { 33 | super.onCreate(savedInstanceState) 34 | binding = ActivityUserSetupBinding.inflate(layoutInflater) 35 | setContentView(binding!!.root) 36 | 37 | //Setup Activity Custom action bar 38 | supportActionBar!!.setDisplayHomeAsUpEnabled(true) 39 | 40 | supportActionBar!!.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM 41 | 42 | absBinding = AbsLayoutBinding.inflate(layoutInflater) 43 | supportActionBar!!.customView = absBinding!!.root 44 | absBinding!!.activityTitleTv.text = baseContext.resources.getString(R.string.user_setup_activity_title) 45 | 46 | // Because delay when connect to Firestore so need to prevent user moving to another screen 47 | bottomNavigationVisible(false) 48 | 49 | //Bottom navigation 50 | bottomNavigationHandle() 51 | 52 | //Setup database 53 | 54 | databasePreference = DatabasePreference(baseContext) 55 | Log.v(TAG,"Get key success: ${databasePreference!!.deviceId}") 56 | 57 | isRegister = intent.getBooleanExtra("isRegister",false) 58 | 59 | isTargetFill() 60 | eventHandle() 61 | } 62 | private fun eventHandle(){ 63 | binding!!.goBt.setOnClickListener{ 64 | if (!binding!!.totalMaxStepEv.text.isNullOrBlank() && !binding!!.totalCaloriesEv.text.isNullOrBlank()){ 65 | myWeek!!.stepPerDay = maxSteps!!.toInt() 66 | 67 | val countStepIntent = Intent(this,CountStep::class.java) 68 | countStepIntent.putExtra("myWeek",myWeek) 69 | startActivity(countStepIntent) 70 | } 71 | else{ 72 | Toast.makeText(this,"You need to fill Step or Calories target to starting",Toast.LENGTH_SHORT).show() 73 | } 74 | } 75 | 76 | binding!!.totalMaxStepEv.setOnClickListener { 77 | if (!binding!!.totalMaxStepEv.text.isNullOrBlank()) { 78 | maxSteps = binding!!.totalMaxStepEv.text.toString().toFloat() 79 | calories = (maxSteps!!.toFloat() * FOOT_TO_CALORIE).toFloat() 80 | binding!!.totalCaloriesEv.setText(calories!!.toInt().toString()) 81 | } 82 | } 83 | binding!!.totalCaloriesEv.setOnClickListener { 84 | if (!binding!!.totalCaloriesEv.text.isNullOrBlank()) { 85 | calories = binding!!.totalCaloriesEv.text.toString().toFloat() 86 | maxSteps = (calories!!.toFloat() / FOOT_TO_CALORIE).toFloat() 87 | binding!!.totalMaxStepEv.setText(maxSteps!!.toInt().toString()) 88 | } 89 | } 90 | } 91 | 92 | override fun onPause() { 93 | super.onPause() 94 | // Save 95 | myWeek!!.stepPerDay = maxSteps!!.toInt() 96 | saveData() 97 | 98 | // Toast.makeText(this, "Pause!!!", Toast.LENGTH_SHORT).show() 99 | // 100 | myWeek!!.stepPerDay = maxSteps!!.toInt() 101 | Log.v(TAG, "Activity on pause, data updating!!!") 102 | } 103 | private fun isTargetFill(){ 104 | if (!loadWeekData()){ 105 | Log.v(TAG,"User data is init") 106 | bottomNavigationVisible(false) 107 | isInitAccount = true 108 | } 109 | else{ 110 | Log.v(TAG,"User data is exist") 111 | if (myWeek!!.stepPerDay == 0){ 112 | bottomNavigationVisible(false) 113 | } 114 | else { 115 | maxSteps = myWeek!!.stepPerDay!!.toFloat() 116 | calories = (maxSteps!!.toFloat() * FOOT_TO_CALORIE).toFloat() 117 | binding!!.totalCaloriesEv.setText(calories!!.toInt().toString()) 118 | binding!!.totalMaxStepEv.setText(maxSteps!!.toInt().toString()) 119 | bottomNavigationVisible(true) 120 | } 121 | if(isRegister) { 122 | val countStepIntent = Intent(this, CountStep::class.java) 123 | countStepIntent.putExtra("myWeek", myWeek) 124 | startActivity(countStepIntent) 125 | } 126 | isInitAccount = false 127 | } 128 | checkNewDay() 129 | } 130 | 131 | private fun bottomNavigationVisible(flag : Boolean){ 132 | binding!!.bottomNavigation.menu[0].isVisible = flag 133 | binding!!.bottomNavigation.menu[1].isVisible = flag 134 | } 135 | private fun bottomNavigationHandle(){ 136 | val bottomNavigationView : BottomNavigationView = binding!!.bottomNavigation 137 | 138 | binding!!.bottomNavigation.menu[2].isChecked = true 139 | bottomNavigationView.setOnItemSelectedListener { 140 | when(it.itemId){ 141 | R.id.gps_training-> { 142 | startActivity(Intent(this, GpsMap::class.java)) 143 | } 144 | R.id.home-> { 145 | startActivity(Intent(this, CountStep::class.java)) 146 | } 147 | } 148 | true 149 | } 150 | } 151 | private fun loadWeekData() : Boolean { 152 | val sharedPreferences = getSharedPreferences("myPrefs",Context.MODE_PRIVATE) 153 | 154 | myWeek = databasePreference!!.initData(0) 155 | 156 | val deviceId = sharedPreferences.getString("deviceId","") 157 | if (deviceId == ""){ 158 | return false 159 | } 160 | myWeek!!.deviceId = deviceId 161 | myWeek!!.stepPerDay = sharedPreferences.getInt("stepPerDay",0) 162 | myWeek!!.mon = sharedPreferences.getInt("monStep",0) 163 | myWeek!!.tue = sharedPreferences.getInt("tueStep",0) 164 | myWeek!!.wed = sharedPreferences.getInt("wedStep",0) 165 | myWeek!!.thu = sharedPreferences.getInt("thuStep",0) 166 | myWeek!!.fri = sharedPreferences.getInt("friStep",0) 167 | myWeek!!.sat = sharedPreferences.getInt("satStep",0) 168 | myWeek!!.sun = sharedPreferences.getInt("sunStep",0) 169 | return true 170 | } 171 | private fun saveData() { 172 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 173 | 174 | val editor = sharedPreferences.edit() 175 | // Save day 176 | val today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) 177 | editor.putInt("today", today) 178 | Log.v(TAG, "Today save is: $today") 179 | 180 | Log.v(TAG,"Week save is : $myWeek") 181 | editor.putString("deviceId", myWeek!!.deviceId) 182 | editor.putInt("stepPerDay",myWeek!!.stepPerDay!!) 183 | editor.putInt("monStep",myWeek!!.mon!!) 184 | editor.putInt("tueStep",myWeek!!.tue!!) 185 | editor.putInt("wedStep",myWeek!!.wed!!) 186 | editor.putInt("thuStep",myWeek!!.thu!!) 187 | editor.putInt("friStep",myWeek!!.fri!!) 188 | editor.putInt("satStep",myWeek!!.sat!!) 189 | editor.putInt("sunStep",myWeek!!.sun!!) 190 | 191 | editor.apply() 192 | } 193 | private fun resetData() { 194 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 195 | 196 | val editor = sharedPreferences.edit() 197 | editor.putFloat("previousTotalSteps",0f) 198 | editor.apply() 199 | 200 | } 201 | private fun checkNewDay() { 202 | val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) 203 | val oldDay = sharedPreferences.getInt("today",0) 204 | Log.v(TAG, "Old day: $oldDay") 205 | val today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) 206 | if (oldDay == today && !isInitAccount!!) { 207 | Log.v(TAG, "Still in today: $today") 208 | } else { 209 | // Reset data 210 | Log.v(TAG, "Change to new day is: $today") 211 | resetData() 212 | myWeek = databasePreference!!.updateSpecifyDay(myWeek!!, today,0) 213 | } 214 | } 215 | } -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/builders/WeekChartBuilder.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.builders 2 | 3 | import android.content.Context 4 | import androidx.core.content.ContextCompat 5 | import com.immortalweeds.pedometer.R 6 | import com.immortalweeds.pedometer.model.countstep.Week 7 | import com.github.mikephil.charting.charts.BarChart 8 | import com.github.mikephil.charting.components.XAxis 9 | import com.github.mikephil.charting.components.YAxis 10 | import com.github.mikephil.charting.data.BarData 11 | import com.github.mikephil.charting.data.BarDataSet 12 | import com.github.mikephil.charting.data.BarEntry 13 | import com.github.mikephil.charting.formatter.ValueFormatter 14 | import com.github.mikephil.charting.interfaces.datasets.IBarDataSet 15 | 16 | class WeekChart private constructor( 17 | private var barChart: BarChart 18 | ) { 19 | data class WeekChartBuilder( 20 | var barChart : BarChart, 21 | var baseContext : Context, 22 | var X_TITLE : Array, 23 | private var maxStep: Float = 0f, 24 | private var myWeek: Week = Week("",0,0,0,0,0,0,0,0) 25 | ){ 26 | fun setMaxStep(maxStep: Float) = apply { 27 | this.maxStep = maxStep 28 | 29 | barChart.description.isEnabled = false 30 | barChart.setDrawValueAboveBar(false) 31 | barChart.setDrawGridBackground(true) 32 | 33 | barChart.setBackgroundColor(ContextCompat.getColor(baseContext, R.color.blue_gray)) 34 | barChart.setGridBackgroundColor( 35 | ContextCompat.getColor( 36 | baseContext, 37 | R.color.blue_gray 38 | ) 39 | ) 40 | 41 | barChart.xAxis.isEnabled = true 42 | barChart.axisLeft.isEnabled = false 43 | barChart.axisRight.isEnabled = false 44 | barChart.xAxis.position = XAxis.XAxisPosition.BOTTOM 45 | barChart.xAxis.textColor = ContextCompat.getColor(baseContext, R.color.silver) 46 | barChart.xAxis.textSize = 18f 47 | barChart.setDrawValueAboveBar(true) 48 | 49 | val xAxis: XAxis = barChart.xAxis 50 | 51 | xAxis.valueFormatter = object : ValueFormatter() { 52 | override fun getFormattedValue(value: Float): String { 53 | return X_TITLE[value.toInt()] 54 | } 55 | } 56 | 57 | val axisLeft: YAxis = barChart.axisLeft 58 | axisLeft.granularity = 10f 59 | axisLeft.axisMinimum = 0f 60 | axisLeft.axisMaximum = maxStep 61 | 62 | val axisRight: YAxis = barChart.axisRight 63 | axisRight.granularity = 10f 64 | axisRight.axisMinimum = 0f 65 | 66 | } 67 | 68 | fun setWeek(week: Week) = apply { 69 | this.myWeek = week 70 | 71 | val values = arrayListOf() 72 | var i = 0f 73 | 74 | values.add(BarEntry(i++, myWeek.sun!!.toFloat())) 75 | values.add(BarEntry(i++, myWeek.mon!!.toFloat())) 76 | values.add(BarEntry(i++, myWeek.tue!!.toFloat())) 77 | values.add(BarEntry(i++, myWeek.wed!!.toFloat())) 78 | values.add(BarEntry(i++, myWeek.thu!!.toFloat())) 79 | values.add(BarEntry(i++, myWeek.fri!!.toFloat())) 80 | values.add(BarEntry(i, myWeek.sat!!.toFloat())) 81 | 82 | 83 | val barDataSet = BarDataSet(values, null) 84 | barDataSet.color = ContextCompat.getColor(baseContext, R.color.yellow) 85 | barDataSet.valueTextColor = ContextCompat.getColor(baseContext, R.color.white) 86 | 87 | val dataSets = arrayListOf() 88 | dataSets.add(barDataSet) 89 | 90 | val barData = BarData(dataSets) 91 | barData.setValueTextSize(15f) 92 | barChart.data = barData 93 | barChart.invalidate() 94 | 95 | } 96 | 97 | fun build() = WeekChart( 98 | barChart 99 | ).barChart 100 | 101 | override fun equals(other: Any?): Boolean { 102 | if (this === other) return true 103 | if (javaClass != other?.javaClass) return false 104 | 105 | other as WeekChartBuilder 106 | 107 | if (!X_TITLE.contentEquals(other.X_TITLE)) return false 108 | 109 | return true 110 | } 111 | 112 | override fun hashCode(): Int { 113 | return X_TITLE.contentHashCode() 114 | } 115 | } 116 | } -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/database/DatabasePreference.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.database 2 | 3 | import android.annotation.SuppressLint 4 | import android.content.Context 5 | import android.provider.Settings 6 | import com.immortalweeds.pedometer.model.countstep.Week 7 | 8 | class DatabasePreference (context: Context){ 9 | @SuppressLint("HardwareIds") 10 | var deviceId: String = Settings.Secure.getString( 11 | context.contentResolver, 12 | Settings.Secure.ANDROID_ID) 13 | 14 | fun initData(targetStep: Int) : Week { 15 | return Week( 16 | deviceId, 17 | 0, 18 | 0, 19 | 0, 20 | 0, 21 | 0, 22 | 0, 23 | 0, 24 | targetStep 25 | ) 26 | } 27 | // // Update the specify day 28 | // fun updateWeekToFireStore(newWeek: Week){ 29 | // 30 | // db.collection("Week").whereEqualTo("deviceId", deviceId) 31 | // .get().addOnSuccessListener { 32 | // if (it.documents.isNotEmpty()) { 33 | // 34 | // docId = it.documents[0].id 35 | // Log.v(TAG, "DocId: ${it.documents[0].id}") 36 | // 37 | // db.collection("Week").document(docId!!).delete() 38 | // 39 | // db.collection("Week").add(newWeek) 40 | // .addOnSuccessListener { 41 | // Log.v(TAG, "Update data successful") 42 | // } 43 | // }else{ 44 | // Log.v(TAG, "Update failed : Data not exist") 45 | // } 46 | // } 47 | // } 48 | 49 | 50 | fun getStepSpecifyDay(myWeek :Week, dayNumber: Int) : Int{ 51 | return when (dayNumber){ 52 | 1 ->{ 53 | myWeek.sun!! 54 | } 55 | 2 ->{ 56 | myWeek.mon!! 57 | } 58 | 3 ->{ 59 | myWeek.tue!! 60 | } 61 | 4 ->{ 62 | myWeek.wed!! 63 | } 64 | 5 ->{ 65 | myWeek.thu!! 66 | } 67 | 6 ->{ 68 | myWeek.fri!! 69 | } 70 | 7->{ 71 | myWeek.sat!! 72 | } 73 | else -> 0 74 | } 75 | } 76 | fun updateSpecifyDay(myWeek: Week,dayNumber: Int, step :Int) : Week { 77 | return when (dayNumber){ 78 | 1 ->{ 79 | myWeek.sun = step 80 | myWeek 81 | } 82 | 2 -> { 83 | myWeek.mon = step 84 | myWeek 85 | } 86 | 3 -> { 87 | myWeek.tue = step 88 | myWeek 89 | } 90 | 4 -> { 91 | myWeek.wed = step 92 | myWeek 93 | } 94 | 5 -> { 95 | myWeek.thu = step 96 | myWeek 97 | } 98 | 6 -> { 99 | myWeek.fri = step 100 | myWeek 101 | } 102 | 7 -> { 103 | myWeek.sat = step 104 | myWeek 105 | } 106 | else -> myWeek 107 | } 108 | } 109 | fun plusStepSpecificDay(myWeek: Week, dayNumber: Int, step :Int) : Week { 110 | return when (dayNumber){ 111 | 1 -> { 112 | myWeek.sun = myWeek.sun!!.plus(step) 113 | myWeek 114 | } 115 | 2 -> { 116 | myWeek.mon = myWeek.mon!!.plus(step) 117 | myWeek 118 | } 119 | 3 -> { 120 | myWeek.tue = myWeek.tue!!.plus(step) 121 | myWeek 122 | } 123 | 4 -> { 124 | myWeek.wed = myWeek.wed!!.plus(step) 125 | myWeek 126 | } 127 | 5 -> { 128 | myWeek.thu = myWeek.thu!!.plus(step) 129 | myWeek 130 | } 131 | 6 -> { 132 | myWeek.fri = myWeek.fri!!.plus(step) 133 | myWeek 134 | } 135 | 7-> { 136 | myWeek.sat = myWeek.sat!!.plus(step) 137 | myWeek 138 | } 139 | else -> myWeek 140 | } 141 | } 142 | } -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/countstep/Week.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.countstep 2 | 3 | import java.io.Serializable 4 | 5 | data class Week ( 6 | var deviceId: String? = "", 7 | var stepPerDay: Int? = 0, 8 | var mon: Int? = 0, 9 | var tue: Int? = 0, 10 | var wed: Int? = 0, 11 | var thu: Int? = 0, 12 | var fri: Int? = 0, 13 | var sat: Int? = 0, 14 | var sun: Int? = 0, 15 | ) : Serializable -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/gps/Admin.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.gps 2 | 3 | data class Admin( 4 | val iso_3166_1: String, 5 | val iso_3166_1_alpha3: String 6 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/gps/Geometry.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.gps 2 | 3 | import com.google.gson.annotations.SerializedName 4 | 5 | data class Geometry( 6 | @SerializedName("coordinates") 7 | val coordinates: List>, 8 | @SerializedName("type") 9 | val type: String 10 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/gps/Leg.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.gps 2 | 3 | data class Leg( 4 | val admins: List, 5 | val distance: Double, 6 | val duration: Double, 7 | val steps: List, 8 | val summary: String, 9 | val via_waypoints: List, 10 | val weight: Double 11 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/gps/Route.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.gps 2 | 3 | data class Route( 4 | val country_crossed: Boolean, 5 | val distance: Double, 6 | val duration: Double, 7 | val geometry: Geometry, 8 | val legs: List, 9 | val weight: Double, 10 | val weight_name: String 11 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/gps/Routes.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.gps 2 | 3 | data class Routes( 4 | val code: String, 5 | val routes: List, 6 | val uuid: String, 7 | val waypoints: List 8 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/model/gps/Waypoint.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.model.gps 2 | 3 | data class Waypoint( 4 | val distance: Double, 5 | val location: List, 6 | val name: String 7 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/immortalweeds/pedometer/network/ApiInterface.kt: -------------------------------------------------------------------------------- 1 | package com.immortalweeds.pedometer.network 2 | 3 | import com.immortalweeds.pedometer.BuildConfig 4 | import com.immortalweeds.pedometer.model.gps.Routes 5 | import retrofit2.http.GET 6 | import retrofit2.http.Path 7 | import retrofit2.http.Streaming 8 | 9 | 10 | // https://api.mapbox.com 11 | // /directions/v5/mapbox/walking/ 12 | // -73.98986028294692 13 | // %2C40.73354241917485 14 | // %3B-73.99008109133703 15 | // %2C40.7336442648961 16 | // ?alternatives=false 17 | // &geometries=geojson 18 | // &overview=simplified 19 | // &steps=false 20 | // &access_token=access_token 21 | 22 | interface ApiInterface { 23 | @Streaming 24 | @GET("/directions/v5/mapbox/walking/" + 25 | "{lonOrigin}%2C" + 26 | "{latOrigin}%3B" + 27 | "{lonDes}%2C" + 28 | "{latDes}?alternatives=false&geometries=geojson&overview=simplified&steps=false&" + 29 | "access_token=${BuildConfig.ACCESS_TOKEN}") 30 | // @GET("/{photos}" ) 31 | suspend fun getPlaces( 32 | // @Path("photos") name : String 33 | @Path("lonOrigin") lonOrigin : Double, 34 | @Path("latOrigin") latOrigin : Double, 35 | @Path("lonDes") lonDes : Double, 36 | @Path("latDes") latDes : Double, 37 | ): Routes 38 | } -------------------------------------------------------------------------------- /app/src/main/logo-playstore.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Weedlly/Pedometer/411c6fcf45a7a9aa34214148264297b345211ed7/app/src/main/logo-playstore.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/fringe.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_directions_run_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_local_fire_department_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_map_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/logo_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /app/src/main/res/layout/abs_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 13 | 16 | 24 | 25 | 35 | 36 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_count_step.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 23 | 24 | 41 | 42 | 50 | 51 | 59 | 60 | 72 | 73 | 81 | 82 | 90 | 91 | 92 | 101 | 108 | 118 | 119 | 130 | 140 | 141 | 152 | 153 | 154 | 163 | 164 | 171 | 172 | 183 | 184 | 185 | 186 | 187 | 188 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_gps_map.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 26 | 27 | 35 | 45 | 51 | 52 | 61 | 62 | 71 | 72 | 78 | 79 | 88 | 98 | 99 | 105 | 106 | 115 | 125 | 126 | 127 | 134 |