├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── colors.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ ├── ic_blue_round_bg.png
│ │ │ │ ├── ic_launcher_round.png
│ │ │ │ └── ic_small_blue_rectangular.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ ├── before_or_after_calendar_layout.xml
│ │ │ │ ├── records_calender_item_view.xml
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── fyspring
│ │ │ │ └── stepcounter
│ │ │ │ ├── base
│ │ │ │ ├── MainApp.kt
│ │ │ │ ├── BaseFragment.kt
│ │ │ │ └── BaseActivity.kt
│ │ │ │ ├── constant
│ │ │ │ └── ConstantData.kt
│ │ │ │ ├── bean
│ │ │ │ └── StepEntity.kt
│ │ │ │ ├── utils
│ │ │ │ ├── ScreenUtil.kt
│ │ │ │ ├── StepCountCheckUtil.kt
│ │ │ │ └── TimeUtil.kt
│ │ │ │ ├── dao
│ │ │ │ ├── DBOpenHelper.kt
│ │ │ │ └── StepDataDao.kt
│ │ │ │ ├── ui
│ │ │ │ ├── view
│ │ │ │ │ ├── RecordsCalenderItemView.kt
│ │ │ │ │ └── BeforeOrAfterCalendarView.kt
│ │ │ │ └── activities
│ │ │ │ │ └── MainActivity.kt
│ │ │ │ └── service
│ │ │ │ └── StepService.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── fyspring
│ │ │ └── stepcounter
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── fyspring
│ │ └── stepcounter
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── README.md
├── .idea
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── vcs.xml
├── misc.xml
├── runConfigurations.xml
└── gradle.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 | rootProject.name='SimpleStepCounter'
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 春雨计步器
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_blue_round_bg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xhdpi/ic_blue_round_bg.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_small_blue_rectangular.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fySpring/SimpleStepCounter/HEAD/app/src/main/res/mipmap-xhdpi/ic_small_blue_rectangular.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SimpleStepCounter
2 | android简易计步器,已适配只Android 10,基于android自带传感器,使用kotlin开发,可查看近7天历史记录,步数隔天清零,有问题欢迎交流~
3 | 博客地址:https://blog.csdn.net/u013700040/article/details/67633634
4 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 22 09:35:07 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/base/MainApp.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.base
2 |
3 | import android.app.Application
4 |
5 | /**
6 | * Created by fySpring
7 | * Date: 2020/4/22
8 | * To do:
9 | */
10 | class MainApp : Application() {
11 | override fun onCreate() {
12 | super.onCreate()
13 | }
14 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/constant/ConstantData.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.constant
2 |
3 | /**
4 | * Created by fySpring
5 | * Date: 2020/4/22
6 | * To do:
7 | */
8 | class ConstantData {
9 | companion object{
10 | const val MSG_FROM_CLIENT = 0
11 | const val MSG_FROM_SERVER = 1
12 | const val NOTIFY_ID = 110
13 |
14 | const val CHANNEL_ID = "120"
15 | const val CHANNEL_NAME = "StepService"
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/fyspring/stepcounter/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 | #FFFFFF
7 | #000000
8 | #44CDC5
9 | #333333
10 | #666666
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/before_or_after_calendar_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/bean/StepEntity.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.bean
2 |
3 | /**
4 | * Created by fySpring
5 | * Date: 2020/4/22
6 | * To do:
7 | */
8 | class StepEntity() {
9 | var curDate: String? = null //当天的日期
10 | var steps: String? = null //当天的步数
11 |
12 | constructor(curDate: String, steps: String) : this() {
13 | this.curDate = curDate
14 | this.steps = steps
15 | }
16 |
17 | override fun toString(): String {
18 | return "StepEntity{" +
19 | "curDate='" + curDate + '\'' +
20 | ", steps=" + steps +
21 | '}'
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/utils/ScreenUtil.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.utils
2 |
3 | import android.content.Context
4 |
5 |
6 | /**
7 | * Created by fySpring
8 | * Date: 2020/4/21
9 | * To do:
10 | */
11 | class ScreenUtil {
12 | companion object {
13 | fun getScreenWidth(mContext: Context): Int {
14 |
15 | val displayMetrics = mContext.resources.displayMetrics
16 | //获取屏幕宽高,单位是像素
17 | val widthPixels = displayMetrics.widthPixels
18 | val heightPixels = displayMetrics.heightPixels
19 | //获取屏幕密度倍数
20 | val density = displayMetrics.density
21 |
22 | return widthPixels
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/fyspring/stepcounter/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter
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.fyspring.stepcounter", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/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
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/base/BaseFragment.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.base
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.fragment.app.Fragment
8 |
9 | /**
10 | * Created by fySpring
11 | * Date: 2020/4/22
12 | * To do:
13 | */
14 | abstract class BaseFragment : Fragment() {
15 |
16 | override fun onCreateView(
17 | inflater: LayoutInflater,
18 | container: ViewGroup?,
19 | savedInstanceState: Bundle?
20 | ): View? {
21 | return inflater.inflate(getLayoutId(), null, false)
22 | }
23 |
24 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
25 | super.onViewCreated(view, savedInstanceState)
26 | initData()
27 | initListener()
28 | }
29 |
30 | abstract fun getLayoutId(): Int
31 | abstract fun initData()
32 | abstract fun initListener()
33 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/dao/DBOpenHelper.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.dao
2 |
3 | import android.content.Context
4 | import android.database.sqlite.SQLiteOpenHelper
5 | import android.database.sqlite.SQLiteDatabase
6 |
7 |
8 |
9 | /**
10 | * Created by fySpring
11 | * Date: 2020/4/21
12 | * To do:
13 | */
14 | class DBOpenHelper(mContext :Context) :SQLiteOpenHelper(mContext, "StepCounter.db", null,1) {
15 | private val DB_NAME = "StepCounter.db" //数据库名称
16 | private val DB_VERSION = 1//数据库版本,大于0
17 |
18 | //用于创建Banner表
19 | private val CREATE_BANNER = ("create table step ("
20 | + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
21 | + "curDate TEXT, "
22 | + "totalSteps TEXT)")
23 |
24 |
25 | override fun onCreate(db: SQLiteDatabase) {
26 | db.execSQL(CREATE_BANNER)//执行有更改的sql语句
27 | }
28 |
29 | override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
30 |
31 | }
32 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/base/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.base
2 |
3 | import android.os.Bundle
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import androidx.annotation.LayoutRes
7 | import androidx.appcompat.app.AppCompatActivity
8 |
9 | /**
10 | * Created by fySpring
11 | * Date: 2020/4/22
12 | * To do:
13 | */
14 | abstract class BaseActivity : AppCompatActivity() {
15 |
16 | override fun onCreate(savedInstanceState: Bundle?) {
17 | super.onCreate(savedInstanceState)
18 | setContentView(getLayoutId())
19 | }
20 |
21 | override fun setContentView(@LayoutRes layoutResID: Int) {
22 | super.setContentView(layoutResID)
23 | init()
24 | }
25 |
26 | override fun setContentView(view: View) {
27 | super.setContentView(view)
28 | init()
29 | }
30 |
31 | override fun setContentView(view: View, params: ViewGroup.LayoutParams) {
32 | super.setContentView(view, params)
33 | init()
34 | }
35 |
36 | private fun init() {
37 | initData()
38 | initListener()
39 | }
40 |
41 | abstract fun getLayoutId(): Int
42 | abstract fun initData()
43 | abstract fun initListener()
44 | }
--------------------------------------------------------------------------------
/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=-Xmx1536m
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
22 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | android {
8 | compileSdkVersion 29
9 | buildToolsVersion "29.0.2"
10 | defaultConfig {
11 | applicationId "com.fyspring.stepcounter"
12 | minSdkVersion 19
13 | targetSdkVersion 29
14 | versionCode 1
15 | versionName "1.0"
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
29 | implementation 'androidx.appcompat:appcompat:1.0.2'
30 | implementation 'androidx.core:core-ktx:1.0.2'
31 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
32 | testImplementation 'junit:junit:4.12'
33 | androidTestImplementation 'androidx.test.ext:junit:1.1.0'
34 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/utils/StepCountCheckUtil.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.utils
2 |
3 | import android.hardware.Sensor.TYPE_STEP_DETECTOR
4 | import android.hardware.Sensor.TYPE_STEP_COUNTER
5 | import android.content.Context.SENSOR_SERVICE
6 | import androidx.core.content.ContextCompat.getSystemService
7 | import android.hardware.SensorManager
8 | import android.os.Build
9 | import android.annotation.TargetApi
10 | import android.content.Context
11 | import android.content.pm.PackageManager
12 | import android.hardware.Sensor
13 |
14 |
15 | /**
16 | * Created by fySpring
17 | * Date: 2020/4/21
18 | * To do:
19 | */
20 | class StepCountCheckUtil(private val mContext: Context) {
21 |
22 | //是否有传感器
23 | private var hasSensor: Boolean = isSupportStepCountSensor()
24 |
25 |
26 | @TargetApi(Build.VERSION_CODES.KITKAT)
27 | fun isSupportStepCountSensor(): Boolean {
28 | return mContext.packageManager
29 | .hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER)
30 | }
31 |
32 |
33 | companion object{
34 | /**
35 | * 判断该设备是否支持计歩
36 | *
37 | * @param context
38 | * @return
39 | */
40 | fun isSupportStepCountSensor(context: Context): Boolean {
41 | // 获取传感器管理器的实例
42 | val sensorManager = context
43 | .getSystemService(SENSOR_SERVICE) as SensorManager
44 | val countSensor = sensorManager.getDefaultSensor(TYPE_STEP_COUNTER)
45 | val detectorSensor = sensorManager.getDefaultSensor(TYPE_STEP_DETECTOR)
46 | return countSensor != null || detectorSensor != null
47 | }
48 | }
49 |
50 |
51 |
52 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
18 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/records_calender_item_view.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
20 |
21 |
28 |
29 |
35 |
36 |
42 |
43 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/dao/StepDataDao.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.dao
2 |
3 | import android.content.ContentValues
4 | import android.content.Context
5 | import android.database.sqlite.SQLiteDatabase
6 | import com.fyspring.stepcounter.bean.StepEntity
7 |
8 |
9 | /**
10 | * Created by fySpring
11 | * Date: 2020/4/21
12 | * To do:
13 | */
14 | class StepDataDao(mContext: Context) {
15 | private var stepHelper: DBOpenHelper = DBOpenHelper(mContext)
16 | private var stepDb: SQLiteDatabase? = null
17 |
18 | /**
19 | * 添加一条新记录
20 | *
21 | * @param stepEntity
22 | */
23 | fun addNewData(stepEntity: StepEntity) {
24 | stepDb = stepHelper.readableDatabase
25 |
26 | val values = ContentValues()
27 | values.put("curDate", stepEntity.curDate)
28 | values.put("totalSteps", stepEntity.steps)
29 | stepDb!!.insert("step", null, values)
30 | stepDb!!.close()
31 | }
32 |
33 | /**
34 | * 根据日期查询记录
35 | *
36 | * @param curDate
37 | * @return
38 | */
39 | fun getCurDataByDate(curDate: String): StepEntity? {
40 | stepDb = stepHelper.readableDatabase
41 | var stepEntity: StepEntity? = null
42 | val cursor = stepDb!!.query("step", null, null, null, null, null, null)
43 | while (cursor.moveToNext()) {
44 | val date = cursor.getString(cursor.getColumnIndexOrThrow("curDate"))
45 | if (curDate == date) {
46 | val steps = cursor.getString(cursor.getColumnIndexOrThrow("totalSteps"))
47 | stepEntity = StepEntity(date, steps)
48 | //跳出循环
49 | break
50 | }
51 | }
52 | //关闭
53 | stepDb!!.close()
54 | cursor.close()
55 | return stepEntity
56 | }
57 |
58 | /**
59 | * 查询所有的记录
60 | *
61 | * @return
62 | */
63 | fun getAllDatas(): List {
64 | val dataList: MutableList = ArrayList()
65 | stepDb = stepHelper.readableDatabase
66 | val cursor = stepDb!!.rawQuery("select * from step", null)
67 |
68 | while (cursor.moveToNext()) {
69 | val curDate = cursor.getString(cursor.getColumnIndex("curDate"))
70 | val totalSteps = cursor.getString(cursor.getColumnIndex("totalSteps"))
71 | val entity = StepEntity(curDate, totalSteps)
72 | dataList.add(entity)
73 | }
74 |
75 | //关闭数据库
76 | stepDb!!.close()
77 | cursor.close()
78 | return dataList
79 | }
80 |
81 | /**
82 | * 更新数据
83 | * @param stepEntity
84 | */
85 | fun updateCurData(stepEntity: StepEntity) {
86 | stepDb = stepHelper.readableDatabase
87 |
88 | val values = ContentValues()
89 | values.put("curDate", stepEntity.curDate)
90 | values.put("totalSteps", stepEntity.steps)
91 | stepDb!!.update("step", values, "curDate=?", arrayOf(stepEntity.curDate))
92 |
93 | stepDb!!.close()
94 | }
95 |
96 |
97 | /**
98 | * 删除指定日期的记录
99 | *
100 | * @param curDate
101 | */
102 | fun deleteCurData(curDate: String) {
103 | stepDb = stepHelper.readableDatabase
104 |
105 | if (stepDb!!.isOpen)
106 | stepDb!!.delete("step", "curDate", arrayOf(curDate))
107 | stepDb!!.close()
108 | }
109 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/ui/view/RecordsCalenderItemView.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.ui.view
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.view.ViewGroup
6 | import android.widget.TextView
7 | import android.widget.RelativeLayout
8 | import android.widget.LinearLayout
9 | import android.view.LayoutInflater
10 | import android.view.View
11 | import com.fyspring.stepcounter.R
12 | import com.fyspring.stepcounter.utils.ScreenUtil
13 |
14 |
15 | /**
16 | * Created by fySpring
17 | * Date: 2020/4/21
18 | * To do:
19 | */
20 | class RecordsCalenderItemView(
21 | mContext: Context,//日期时间
22 | private val weekStr: String,
23 | private val dateStr: String, //返回当前项的id
24 | val position: Int, //当前item 的时间 ,如 2017年02月07日 , 用以判断当前item是否可以被点击
25 | private var curItemDate: String
26 | ) : RelativeLayout(mContext) {
27 |
28 | private var itemLl: LinearLayout? = null
29 | private var lineView: View? = null
30 | private var weekTv: TextView? = null
31 | private var dateRl: RelativeLayout? = null
32 | private var dateTv: TextView? = null
33 |
34 |
35 | private var itemClick: OnCalenderItemClick? = null
36 |
37 | interface OnCalenderItemClick {
38 | fun onCalenderItemClick()
39 | }
40 |
41 | fun setOnCalenderItemClick(itemClick: OnCalenderItemClick) {
42 | this.itemClick = itemClick
43 | }
44 |
45 | init {
46 | val inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
47 | val itemView = inflater.inflate(R.layout.records_calender_item_view, this)
48 | itemLl = itemView.findViewById(R.id.records_calender_item_ll)
49 | weekTv = itemView.findViewById(R.id.records_calender_item_week_tv)
50 | lineView = itemView.findViewById(R.id.calendar_item_line_view)
51 | dateRl = itemView.findViewById(R.id.records_calender_item_date_rl)
52 | dateTv = itemView.findViewById(R.id.records_calender_item_date_tv)
53 |
54 | //如果日期是今天的话设为选中 目前有BUG
55 |
56 | // if(curItemDate.equals(TimeUtil.getCurrentDate())){
57 | // dateTv.setBackgroundResource(R.drawable.ic_blue_round_border_bg);
58 | // dateTv.getBackground().setAlpha(255);
59 | // }else{
60 | // if(dateTv.getBackground() != null){
61 | // dateTv.getBackground().setAlpha(0);
62 | // }
63 | // }
64 |
65 |
66 | weekTv!!.textSize = 15f
67 | lineView!!.visibility = View.GONE
68 |
69 | weekTv!!.text = weekStr
70 | dateTv!!.text = dateStr
71 |
72 | itemView.layoutParams = LayoutParams(
73 | ScreenUtil.getScreenWidth(mContext) / 7,
74 | ViewGroup.LayoutParams.MATCH_PARENT
75 | )
76 |
77 | itemView.setOnClickListener { itemClick!!.onCalenderItemClick() }
78 |
79 | }
80 |
81 | fun setChecked(checkedFlag: Boolean) {
82 | if (checkedFlag) {
83 | //当前item被选中后样式
84 | weekTv!!.setTextColor(resources.getColor(R.color.main_text_color))
85 | dateTv!!.setTextColor(resources.getColor(R.color.white))
86 | dateRl!!.setBackgroundResource(R.mipmap.ic_blue_round_bg)
87 | } else {
88 | //当前item未被选中样式
89 | weekTv!!.setTextColor(resources.getColor(R.color.gray_default_dark))
90 | dateTv!!.setTextColor(resources.getColor(R.color.gray_default_dark))
91 | //设置背景透明
92 | dateRl!!.setBackgroundColor(Color.TRANSPARENT)
93 | }
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/ui/view/BeforeOrAfterCalendarView.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.ui.view
2 |
3 | import android.widget.RelativeLayout
4 |
5 | import android.content.Context
6 | import android.widget.LinearLayout
7 | import android.view.LayoutInflater
8 | import com.fyspring.stepcounter.R
9 | import com.fyspring.stepcounter.utils.TimeUtil
10 |
11 |
12 | /**
13 | * Created by fySpring
14 | * Date: 2020/4/21
15 | * To do:
16 | */
17 | class BeforeOrAfterCalendarView(mContext: Context) : RelativeLayout(mContext) {
18 | private var dayList: MutableList = ArrayList()
19 | private var dateList: MutableList = ArrayList()
20 | private var itemViewList: MutableList = ArrayList()
21 | private var calenderViewLl: LinearLayout? = null
22 | private var curPosition: Int = 0
23 |
24 | init {
25 | val view =
26 | LayoutInflater.from(mContext).inflate(R.layout.before_or_after_calendar_layout, this)
27 |
28 | calenderViewLl = view.findViewById(R.id.boa_calender_view_ll)
29 | setBeforeDateViews()
30 | initItemViews()
31 | }
32 |
33 |
34 | /**
35 | * 设置之前的日期显示
36 | */
37 | private fun setBeforeDateViews() {
38 | //获取日期列表
39 | dateList.addAll(TimeUtil.getBeforeDateListByNow())
40 | dayList.addAll(TimeUtil.dateListToDayList(dateList))
41 | }
42 |
43 | private fun initItemViews() {
44 | for (i in dateList.indices) {
45 | val day = dayList[i]
46 | val curItemDate = dateList[i]
47 | val itemView: RecordsCalenderItemView
48 | itemView = if (day == TimeUtil.getCurrentDay()) {
49 | RecordsCalenderItemView(context , "今天", day.toString(), i, curItemDate)
50 | } else {
51 | RecordsCalenderItemView(
52 | context,
53 | TimeUtil.getCurWeekDay(curItemDate),
54 | day.toString(),
55 | i,
56 | curItemDate
57 | )
58 | }
59 |
60 | itemViewList.add(itemView)
61 | calenderViewLl?.addView(itemView)
62 |
63 | itemView.setOnCalenderItemClick(object : RecordsCalenderItemView.OnCalenderItemClick {
64 | override fun onCalenderItemClick() {
65 | curPosition = itemView.position
66 | switchPositionView(curPosition)
67 |
68 | if (calenderClickListener != null) {
69 | calenderClickListener!!.onClickToRefresh(
70 | curPosition,
71 | dateList[curPosition]
72 | )
73 | }
74 | }
75 | })
76 | }
77 | switchPositionView(6)
78 | }
79 |
80 | private fun switchPositionView(position: Int) {
81 | for (i in itemViewList.indices) {
82 | if (position == i) {
83 | itemViewList[i].setChecked(true)
84 | } else {
85 | itemViewList[i].setChecked(false)
86 | }
87 | }
88 | }
89 |
90 | private var calenderClickListener: BoaCalenderClickListener? = null
91 |
92 | interface BoaCalenderClickListener {
93 | fun onClickToRefresh(position: Int, curDate: String)
94 | }
95 |
96 | fun setOnBoaCalenderClickListener(calenderClickListener: BoaCalenderClickListener) {
97 | this.calenderClickListener = calenderClickListener
98 | }
99 |
100 | }
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | xmlns:android
20 |
21 | ^$
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | xmlns:.*
31 |
32 | ^$
33 |
34 |
35 | BY_NAME
36 |
37 |
38 |
39 |
40 |
41 |
42 | .*:id
43 |
44 | http://schemas.android.com/apk/res/android
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | .*:name
54 |
55 | http://schemas.android.com/apk/res/android
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | name
65 |
66 | ^$
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | style
76 |
77 | ^$
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 | .*
87 |
88 | ^$
89 |
90 |
91 | BY_NAME
92 |
93 |
94 |
95 |
96 |
97 |
98 | .*
99 |
100 | http://schemas.android.com/apk/res/android
101 |
102 |
103 | ANDROID_ATTRIBUTE_ORDER
104 |
105 |
106 |
107 |
108 |
109 |
110 | .*
111 |
112 | .*
113 |
114 |
115 | BY_NAME
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/utils/TimeUtil.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.utils
2 |
3 | import java.text.ParseException
4 | import java.text.SimpleDateFormat
5 | import java.util.*
6 | import kotlin.collections.ArrayList
7 |
8 |
9 | /**
10 | * Created by fySpring
11 | * Date: 2020/4/21
12 | * To do:
13 | */
14 | class TimeUtil {
15 |
16 | companion object {
17 | private val dateFormat = SimpleDateFormat("yyyy年MM月dd日")
18 | private val mCalendar = Calendar.getInstance()
19 | private val weekStrings = arrayOf("日", "一", "二", "三", "四", "五", "六")
20 | private val rWeekStrings = arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六")
21 |
22 |
23 | /**
24 | * 改变日期格式
25 | * @param date 2017年02月09日
26 | * @return 2017-02-09
27 | */
28 | fun changeFormatDate(date: String): String? {
29 | val dFormat = SimpleDateFormat("yyyy-MM-dd")
30 | var curDate: String? = null
31 | try {
32 | val dt = dateFormat.parse(date)
33 | curDate = dFormat.format(dt)
34 | } catch (e: ParseException) {
35 | e.printStackTrace()
36 | }
37 |
38 | return curDate
39 | }
40 |
41 | /**
42 | * 判断日期是否与当前日期差7天
43 | * @param date 2020年04月22日
44 | * @return true
45 | */
46 | fun isDateOutDate(date: String): Boolean {
47 | try {
48 | if ((Date().time - dateFormat.parse(date).time) > 7 * 24 * 60 * 60 * 1000) return true
49 |
50 | } catch (e: ParseException) {
51 | e.printStackTrace()
52 | }
53 |
54 | return false
55 | }
56 |
57 | /**
58 | * 返回当前的时间
59 | * @return 今天 09:48
60 | */
61 | private fun getCurTime(): String {
62 | val dFormat = SimpleDateFormat("HH:mm")
63 | return "今天 " + dFormat.format(System.currentTimeMillis())
64 | }
65 |
66 | /**
67 | * 获取运动记录是周几,今天则返回具体时间,其他则返回具体周几
68 | * @param dateStr
69 | * @return
70 | */
71 | fun getWeekStr(dateStr: String): String {
72 |
73 | val todayStr = dateFormat.format(mCalendar.time)
74 |
75 | if (todayStr == dateStr) {
76 | return getCurTime()
77 | }
78 |
79 | val preCalendar = Calendar.getInstance()
80 | preCalendar.add(Calendar.DATE, -1)
81 | val yesterdayStr = dateFormat.format(preCalendar.time)
82 | if (yesterdayStr == dateStr) {
83 | return "昨天"
84 | }
85 |
86 | var w = 0
87 | try {
88 | val date = dateFormat.parse(dateStr)
89 | val calendar = Calendar.getInstance()
90 | calendar.time = date
91 | w = calendar.get(Calendar.DAY_OF_WEEK) - 1
92 | if (w < 0) {
93 | w = 0
94 | }
95 |
96 | } catch (e: ParseException) {
97 | e.printStackTrace()
98 | }
99 |
100 | return rWeekStrings[w]
101 | }
102 |
103 |
104 | /**
105 | * 获取是几号
106 | *
107 | * @return dd
108 | */
109 | public fun getCurrentDay(): Int {
110 | return mCalendar.get(Calendar.DATE)
111 | }
112 |
113 | /**
114 | * 获取当前的日期
115 | *
116 | * @return yyyy年MM月dd日
117 | */
118 | fun getCurrentDate(): String {
119 | return dateFormat.format(mCalendar.getTime())
120 | }
121 |
122 |
123 | /**
124 | * 根据date列表获取day列表
125 | *
126 | * @param dateList
127 | * @return
128 | */
129 | fun dateListToDayList(dateList: List): List {
130 | val calendar = Calendar.getInstance()
131 | val dayList: MutableList = ArrayList()
132 | for (date in dateList) {
133 | try {
134 | calendar.setTime(dateFormat.parse(date))
135 | val day = calendar.get(Calendar.DATE)
136 | dayList.add(day)
137 | } catch (e: ParseException) {
138 | e.printStackTrace()
139 | }
140 |
141 | }
142 | return dayList
143 | }
144 |
145 |
146 | /**
147 | * 根据当前日期获取以含当天的前一周日期
148 | * @return [2017年02月21日, 2017年02月22日, 2017年02月23日, 2017年02月24日, 2017年02月25日, 2017年02月26日, 2017年02月27日]
149 | */
150 | fun getBeforeDateListByNow(): List {
151 | val weekList: MutableList = ArrayList()
152 |
153 | for (i in -6..0) {
154 | //以周日为一周的第一天
155 | val calendar = Calendar.getInstance()
156 | calendar.add(Calendar.DATE, i)
157 | val date = dateFormat.format(calendar.time)
158 | weekList.add(date)
159 | }
160 | return weekList
161 | }
162 |
163 | /**
164 | * 判断当前日期是周几
165 | * @param curDate
166 | * @return
167 | */
168 | fun getCurWeekDay(curDate: String): String {
169 | var w = 0
170 | try {
171 | val date = dateFormat.parse(curDate)
172 | val calendar = Calendar.getInstance()
173 | calendar.time = date
174 | w = calendar.get(Calendar.DAY_OF_WEEK) - 1
175 | if (w < 0) {
176 | w = 0
177 | }
178 |
179 | } catch (e: ParseException) {
180 | e.printStackTrace()
181 | }
182 |
183 | return weekStrings[w]
184 | }
185 | }
186 |
187 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/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/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
18 |
19 |
25 |
26 |
34 |
35 |
39 |
40 |
47 |
48 |
55 |
56 |
61 |
62 |
70 |
71 |
77 |
78 |
79 |
80 |
85 |
86 |
95 |
96 |
97 |
98 |
99 |
100 |
105 |
106 |
113 |
114 |
121 |
122 |
127 |
128 |
136 |
137 |
143 |
144 |
145 |
146 |
151 |
152 |
161 |
162 |
163 |
164 |
165 |
166 |
174 |
175 |
176 |
177 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/ui/activities/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.ui.activities
2 |
3 | import android.Manifest
4 | import android.content.ComponentName
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.content.ServiceConnection
8 | import android.content.pm.PackageManager
9 | import android.os.*
10 | import android.view.View
11 | import android.widget.Toast
12 | import androidx.core.app.ActivityCompat
13 | import androidx.core.content.ContextCompat
14 | import com.fyspring.stepcounter.R
15 | import com.fyspring.stepcounter.base.BaseActivity
16 | import com.fyspring.stepcounter.bean.StepEntity
17 | import com.fyspring.stepcounter.constant.ConstantData
18 | import com.fyspring.stepcounter.service.StepService
19 | import com.fyspring.stepcounter.dao.StepDataDao
20 | import com.fyspring.stepcounter.ui.view.BeforeOrAfterCalendarView
21 | import com.fyspring.stepcounter.utils.StepCountCheckUtil
22 | import com.fyspring.stepcounter.utils.TimeUtil
23 | import kotlinx.android.synthetic.main.activity_main.*
24 | import java.text.DecimalFormat
25 | import java.util.*
26 | import kotlin.collections.ArrayList
27 |
28 | class MainActivity : BaseActivity(), Handler.Callback {
29 | private var calenderView: BeforeOrAfterCalendarView? = null
30 | private var curSelDate: String = ""
31 | private val df = DecimalFormat("#.##")
32 | private val stepEntityList: MutableList = ArrayList()
33 | private var stepDataDao: StepDataDao? = null
34 | private var isBind = false
35 | private val mGetReplyMessenger = Messenger(Handler(this))
36 | private var messenger: Messenger? = null
37 |
38 | /**
39 | * 定时任务
40 | */
41 | private var timerTask: TimerTask? = null
42 | private var timer: Timer? = null
43 |
44 | override fun getLayoutId(): Int {
45 | return R.layout.activity_main
46 | }
47 |
48 | override fun initData() {
49 | curSelDate = TimeUtil.getCurrentDate()
50 | calenderView = BeforeOrAfterCalendarView(this)
51 | movement_records_calender_ll!!.addView(calenderView)
52 | requestPermission()
53 | }
54 |
55 | override fun initListener() {
56 | calenderView!!.setOnBoaCalenderClickListener(object :
57 | BeforeOrAfterCalendarView.BoaCalenderClickListener {
58 | override fun onClickToRefresh(position: Int, curDate: String) {
59 | //获取当前选中的时间
60 | curSelDate = curDate
61 | //根据日期去取数据
62 | setDatas()
63 | }
64 | })
65 | }
66 |
67 | private fun requestPermission() {
68 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
69 | if (ContextCompat.checkSelfPermission(
70 | this,
71 | Manifest.permission.ACTIVITY_RECOGNITION
72 | ) != PackageManager.PERMISSION_GRANTED
73 | ) {
74 | ActivityCompat.requestPermissions(
75 | this,
76 | arrayOf(Manifest.permission.ACTIVITY_RECOGNITION),
77 | 1
78 | )
79 | if (ActivityCompat.shouldShowRequestPermissionRationale(
80 | this,
81 | Manifest.permission.ACTIVITY_RECOGNITION
82 | )
83 | ) {
84 | //此处需要弹窗通知用户去设置权限
85 | Toast.makeText(this, "请允许获取健身运动信息,不然不能为你计步哦~", Toast.LENGTH_SHORT).show()
86 | }
87 | } else {
88 | startStepService()
89 | }
90 | } else {
91 | startStepService()
92 | }
93 | }
94 |
95 |
96 | private fun startStepService() {
97 | /**
98 | * 这里判断当前设备是否支持计步
99 | */
100 | if (StepCountCheckUtil.isSupportStepCountSensor(this)) {
101 | getRecordList()
102 | is_support_tv.visibility = View.GONE
103 | setDatas()
104 | setupService()
105 | } else {
106 | movement_total_steps_tv.text = "0"
107 | is_support_tv!!.visibility = View.VISIBLE
108 | }
109 | }
110 |
111 | override fun onRequestPermissionsResult(
112 | requestCode: Int,
113 | permissions: Array,
114 | grantResults: IntArray
115 | ) {
116 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
117 | if (requestCode == 1) {
118 | for (i in permissions.indices) {
119 | if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
120 | startStepService()
121 | } else {
122 | Toast.makeText(this, "请允许获取健身运动信息,不然不能为你计步哦~", Toast.LENGTH_SHORT).show()
123 | }
124 | }
125 | }
126 | }
127 |
128 | /**
129 | * 开启计步服务
130 | */
131 | private fun setupService() {
132 | val intent = Intent(this, StepService::class.java)
133 | isBind = bindService(intent, conn, Context.BIND_AUTO_CREATE)
134 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) startForegroundService(intent)
135 | else startService(intent)
136 | }
137 |
138 | /**
139 | * 用于查询应用服务(application Service)的状态的一种interface,
140 | * 更详细的信息可以参考Service 和 context.bindService()中的描述,
141 | * 和许多来自系统的回调方式一样,ServiceConnection的方法都是进程的主线程中调用的。
142 | */
143 | private val conn = object : ServiceConnection {
144 | /**
145 | * 在建立起于Service的连接时会调用该方法,目前Android是通过IBind机制实现与服务的连接。
146 | * @param name 实际所连接到的Service组件名称
147 | * @param service 服务的通信信道的IBind,可以通过Service访问对应服务
148 | */
149 | override fun onServiceConnected(name: ComponentName, service: IBinder) {
150 | timerTask = object : TimerTask() {
151 | override fun run() {
152 | try {
153 | messenger = Messenger(service)
154 | val msg = Message.obtain(null, ConstantData.MSG_FROM_CLIENT)
155 | msg.replyTo = mGetReplyMessenger
156 | messenger!!.send(msg)
157 | } catch (e: RemoteException) {
158 | e.printStackTrace()
159 | }
160 | }
161 | }
162 | timer = Timer()
163 | timer!!.schedule(timerTask, 0, 500)
164 | }
165 |
166 | /**
167 | * 当与Service之间的连接丢失的时候会调用该方法,
168 | * 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用,
169 | * 此方法不会移除与Service的连接,当服务重新启动的时候仍然会调用 onServiceConnected()。
170 | * @param name 丢失连接的组件名称
171 | */
172 | override fun onServiceDisconnected(name: ComponentName) {
173 |
174 | }
175 | }
176 |
177 | /**
178 | * 设置记录数据
179 | */
180 | private fun setDatas() {
181 | val stepEntity = stepDataDao!!.getCurDataByDate(curSelDate)
182 |
183 | if (stepEntity != null) {
184 | val steps = stepEntity.steps?.let { Integer.parseInt(it) }
185 | //获取全局的步数
186 | movement_total_steps_tv.text = steps.toString()
187 | //计算总公里数
188 | movement_total_km_tv.text = steps?.let { countTotalKM(it) }
189 | } else {
190 | //获取全局的步数
191 | movement_total_steps_tv.text = "0"
192 | //计算总公里数
193 | movement_total_km_tv.text = "0"
194 | }
195 |
196 | //设置时间
197 | val time = TimeUtil.getWeekStr(curSelDate)
198 | movement_total_km_time_tv.text = time
199 | movement_total_steps_time_tv.text = time
200 | }
201 |
202 | /**
203 | * 简易计算公里数,假设一步大约有0.7米
204 | *
205 | * @param steps 用户当前步数
206 | * @return
207 | */
208 | private fun countTotalKM(steps: Int): String {
209 | val totalMeters = steps * 0.7
210 | //保留两位有效数字
211 | return df.format(totalMeters / 1000)
212 | }
213 |
214 | /**
215 | * 获取全部运动历史纪录
216 | */
217 | private fun getRecordList() {
218 | //获取数据库
219 | stepDataDao = StepDataDao(this)
220 | stepEntityList.clear()
221 | stepEntityList.addAll(stepDataDao!!.getAllDatas())
222 | if (stepEntityList.size > 7) {
223 | //在这里获取历史记录条数,当条数达到7条以上时,就开始删除第七天之前的数据
224 | for (entity in stepEntityList) {
225 | if (TimeUtil.isDateOutDate(entity.curDate!!)) {
226 | stepDataDao?.deleteCurData(entity.curDate!!)
227 | }
228 | }
229 | }
230 | }
231 |
232 | override fun handleMessage(msg: Message): Boolean {
233 | when (msg.what) {
234 | //这里用来获取到Service发来的数据
235 | ConstantData.MSG_FROM_SERVER ->
236 | //如果是今天则更新数据
237 | if (curSelDate == TimeUtil.getCurrentDate()) {
238 | //记录运动步数
239 | val steps = msg.data.getInt("steps")
240 | //设置的步数
241 | movement_total_steps_tv.text = steps.toString()
242 | //计算总公里数
243 | movement_total_km_tv.text = countTotalKM(steps)
244 | }
245 | }
246 | return false
247 | }
248 |
249 | override fun onDestroy() {
250 | super.onDestroy()
251 | //记得解绑Service,不然多次绑定Service会异常
252 | if (isBind) this.unbindService(conn)
253 | }
254 | }
255 |
--------------------------------------------------------------------------------
/app/src/main/java/com/fyspring/stepcounter/service/StepService.kt:
--------------------------------------------------------------------------------
1 | package com.fyspring.stepcounter.service
2 |
3 | import android.app.*
4 | import android.content.BroadcastReceiver
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.content.IntentFilter
8 | import android.graphics.BitmapFactory
9 | import android.hardware.Sensor
10 | import android.hardware.SensorEvent
11 | import android.hardware.SensorEventListener
12 | import android.hardware.SensorManager
13 | import android.os.*
14 | import androidx.annotation.Nullable
15 | import com.fyspring.stepcounter.R
16 | import com.fyspring.stepcounter.bean.StepEntity
17 | import com.fyspring.stepcounter.constant.ConstantData
18 | import com.fyspring.stepcounter.ui.activities.MainActivity
19 | import com.fyspring.stepcounter.dao.StepDataDao
20 | import com.fyspring.stepcounter.utils.TimeUtil
21 | import java.text.SimpleDateFormat
22 | import java.util.*
23 |
24 | /**
25 | * Created by fySpring
26 | * Date: 2020/4/22
27 | * To do:
28 | */
29 | class StepService : Service(), SensorEventListener {
30 | //当前日期
31 | private var currentDate: String? = null
32 | //当前步数
33 | private var currentStep: Int = 0
34 | //传感器
35 | private var sensorManager: SensorManager? = null
36 | //数据库
37 | private var stepDataDao: StepDataDao? = null
38 | //计步传感器类型 0-counter 1-detector
39 | private var stepSensor = -1
40 | //广播接收
41 | private var mInfoReceiver: BroadcastReceiver? = null
42 | //发送消息,用来和Service之间传递步数
43 | private val messenger = Messenger(MessengerHandler())
44 | //是否有当天的记录
45 | private var hasRecord: Boolean = false
46 | //未记录之前的步数
47 | private var hasStepCount: Int = 0
48 | //下次记录之前的步数
49 | private var previousStepCount: Int = 0
50 | private var builder: Notification.Builder? = null
51 |
52 | private var notificationManager: NotificationManager? = null
53 | private var nfIntent: Intent? = null
54 |
55 |
56 | override fun onCreate() {
57 | super.onCreate()
58 | initBroadcastReceiver()
59 | Thread(Runnable { getStepDetector() }).start()
60 | initTodayData()
61 | }
62 |
63 | @Nullable
64 | override fun onBind(intent: Intent): IBinder? {
65 | return messenger.binder
66 | }
67 |
68 |
69 | override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
70 | /**
71 | * 此处设将Service为前台,不然当APP结束以后很容易被GC给干掉,
72 | * 这也就是大多数音乐播放器会在状态栏设置一个原理大都是相通的
73 | */
74 | notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
75 |
76 |
77 | //---------------- 针对8.0 新增代码 --------------------------------------
78 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
79 | builder = Notification.Builder(this.applicationContext, ConstantData.CHANNEL_ID)
80 | val notificationChannel =
81 | NotificationChannel(
82 | ConstantData.CHANNEL_ID,
83 | ConstantData.CHANNEL_NAME,
84 | NotificationManager.IMPORTANCE_MIN
85 | )
86 | notificationChannel.enableLights(false)//如果使用中的设备支持通知灯,则说明此通知通道是否应显示灯
87 | notificationChannel.setShowBadge(false)//是否显示角标
88 | notificationChannel.lockscreenVisibility = Notification.VISIBILITY_SECRET
89 | notificationManager?.createNotificationChannel(notificationChannel)
90 | builder?.setChannelId(ConstantData.CHANNEL_ID)
91 | } else {
92 | builder = Notification.Builder(this.applicationContext)
93 | }
94 |
95 | /**
96 | * 设置点击通知栏打开的界面,此处需要注意了,
97 | * 如果你的计步界面不在主界面,则需要判断app是否已经启动,
98 | * 再来确定跳转页面,这里面太多坑
99 | */
100 | nfIntent = Intent(this, MainActivity::class.java)
101 | setStepBuilder()
102 | // 参数一:唯一的通知标识;参数二:通知消息。
103 | startForeground(ConstantData.NOTIFY_ID, builder?.build())// 开始前台服务
104 | return START_STICKY
105 | }
106 |
107 | /**
108 | * 自定义handler
109 | */
110 | private inner class MessengerHandler : Handler() {
111 | override fun handleMessage(msg: Message) = when (msg.what) {
112 | ConstantData.MSG_FROM_CLIENT -> try {
113 | //这里负责将当前的步数发送出去,可以在界面或者其他地方获取,我这里是在MainActivity中获取来更新界面
114 | val messenger = msg.replyTo
115 | val replyMsg = Message.obtain(null, ConstantData.MSG_FROM_SERVER)
116 | val bundle = Bundle()
117 | bundle.putInt("steps", currentStep)
118 | replyMsg.data = bundle
119 | messenger.send(replyMsg)
120 | } catch (e: RemoteException) {
121 | e.printStackTrace()
122 | }
123 | else -> super.handleMessage(msg)
124 | }
125 | }
126 |
127 | /**
128 | * 初始化广播
129 | */
130 | private fun initBroadcastReceiver() {
131 | val filter = IntentFilter()
132 | // 屏幕灭屏广播
133 | filter.addAction(Intent.ACTION_SCREEN_OFF)
134 | //关机广播
135 | filter.addAction(Intent.ACTION_SHUTDOWN)
136 | // 屏幕解锁广播
137 | filter.addAction(Intent.ACTION_USER_PRESENT)
138 | // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
139 | // example:有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者“关机”对话框之上,
140 | // 所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
141 | filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
142 | //监听日期变化
143 | filter.addAction(Intent.ACTION_DATE_CHANGED)
144 | filter.addAction(Intent.ACTION_TIME_CHANGED)
145 | filter.addAction(Intent.ACTION_TIME_TICK)
146 |
147 | mInfoReceiver = object : BroadcastReceiver() {
148 | override fun onReceive(context: Context, intent: Intent) {
149 | when (intent.action) {
150 | // 屏幕灭屏广播
151 | Intent.ACTION_SCREEN_OFF -> saveStepData()
152 | //关机广播,保存好当前数据
153 | Intent.ACTION_SHUTDOWN -> saveStepData()
154 | // 屏幕解锁广播
155 | Intent.ACTION_USER_PRESENT -> saveStepData()
156 | // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
157 | // example:有时候会用到系统对话框,权限可能很高,会覆盖在锁屏界面或者“关机”对话框之上,
158 | // 所以监听这个广播,当收到时就隐藏自己的对话,如点击pad右下角部分弹出的对话框
159 | Intent.ACTION_CLOSE_SYSTEM_DIALOGS -> saveStepData()
160 | //监听日期变化
161 | Intent.ACTION_DATE_CHANGED, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIME_TICK -> {
162 | saveStepData()
163 | isNewDay()
164 | }
165 | }
166 | }
167 | }
168 | //注册广播
169 | registerReceiver(mInfoReceiver, filter)
170 | }
171 |
172 | /**
173 | * 初始化当天数据
174 | */
175 | private fun initTodayData() {
176 | //获取当前时间
177 | currentDate = TimeUtil.getCurrentDate()
178 | //获取数据库
179 | stepDataDao = StepDataDao(applicationContext)
180 | //获取当天的数据,用于展示
181 | val entity = stepDataDao!!.getCurDataByDate(currentDate!!)
182 | //为空则说明还没有该天的数据,有则说明已经开始当天的计步了
183 | currentStep = if (entity == null) 0 else Integer.parseInt(entity.steps!!)
184 | }
185 |
186 | /**
187 | * 监听晚上0点变化初始化数据
188 | */
189 | private fun isNewDay() {
190 | val time = "00:00"
191 | if (time == SimpleDateFormat("HH:mm").format(Date()) || currentDate != TimeUtil.getCurrentDate()) {
192 | initTodayData()
193 | }
194 | }
195 |
196 | /**
197 | * 获取传感器实例
198 | */
199 | private fun getStepDetector() {
200 | if (sensorManager != null) {
201 | sensorManager = null
202 | }
203 | // 获取传感器管理器的实例
204 | sensorManager = this
205 | .getSystemService(Context.SENSOR_SERVICE) as SensorManager
206 | //android4.4以后可以使用计步传感器
207 | if (Build.VERSION.SDK_INT >= 19) {
208 | addCountStepListener()
209 | }
210 | }
211 |
212 | /**
213 | * 添加传感器监听
214 | */
215 | private fun addCountStepListener() {
216 | val countSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
217 | val detectorSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
218 | if (countSensor != null) {
219 | stepSensor = 0
220 | sensorManager!!.registerListener(
221 | this@StepService,
222 | countSensor,
223 | SensorManager.SENSOR_DELAY_NORMAL
224 | )
225 | } else if (detectorSensor != null) {
226 | stepSensor = 1
227 | sensorManager!!.registerListener(
228 | this@StepService,
229 | detectorSensor,
230 | SensorManager.SENSOR_DELAY_NORMAL
231 | )
232 | }
233 | }
234 |
235 | /**
236 | * 由传感器记录当前用户运动步数,注意:该传感器只在4.4及以后才有,并且该传感器记录的数据是从设备开机以后不断累加,
237 | * 只有当用户关机以后,该数据才会清空,所以需要做数据保护
238 | */
239 | override fun onSensorChanged(event: SensorEvent) {
240 | if (stepSensor == 0) {
241 | val tempStep = event.values[0].toInt()
242 | if (!hasRecord) {
243 | hasRecord = true
244 | hasStepCount = tempStep
245 | } else {
246 | val thisStepCount = tempStep - hasStepCount
247 | currentStep += thisStepCount - previousStepCount
248 | previousStepCount = thisStepCount
249 | }
250 | saveStepData()
251 | } else if (stepSensor == 1) {
252 | if (event.values[0].toDouble() == 1.0) {
253 | currentStep++
254 | saveStepData()
255 | }
256 | }
257 | }
258 |
259 | override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
260 |
261 | }
262 |
263 |
264 | /**
265 | * 保存当天的数据到数据库中,并去刷新通知栏
266 | */
267 | private fun saveStepData() {
268 | //查询数据库中的数据
269 | var entity = stepDataDao?.getCurDataByDate(currentDate!!)
270 | //为空则说明还没有该天的数据,有则说明已经开始当天的计步了
271 | if (entity == null) {
272 | //没有则新建一条数据
273 | entity = StepEntity()
274 | entity.curDate = currentDate
275 | entity.steps = currentStep.toString()
276 |
277 | stepDataDao?.addNewData(entity)
278 | } else {
279 | //有则更新当前的数据
280 | entity.steps = currentStep.toString()
281 |
282 | stepDataDao?.updateCurData(entity)
283 | }
284 | setStepBuilder()
285 | }
286 |
287 | private fun setStepBuilder() {
288 | builder?.setContentIntent(
289 | PendingIntent.getActivity(
290 | this,
291 | 0,
292 | nfIntent,
293 | 0
294 | )
295 | ) // 设置PendingIntent
296 | ?.setLargeIcon(
297 | BitmapFactory.decodeResource(
298 | this.resources,
299 | R.mipmap.ic_launcher
300 | )
301 | )
302 | ?.setContentTitle("今日步数" + currentStep + "步")
303 | ?.setSmallIcon(R.mipmap.ic_launcher)
304 | ?.setContentText("加油,要记得勤加运动哦")
305 | // 获取构建好的Notification
306 | val stepNotification = builder?.build()
307 | //调用更新
308 | notificationManager?.notify(ConstantData.NOTIFY_ID, stepNotification)
309 | }
310 |
311 | override fun onDestroy() {
312 | super.onDestroy()
313 | //主界面中需要手动调用stop方法service才会结束
314 | stopForeground(true)
315 | unregisterReceiver(mInfoReceiver)
316 | }
317 |
318 | override fun onUnbind(intent: Intent): Boolean {
319 | return super.onUnbind(intent)
320 | }
321 | }
--------------------------------------------------------------------------------