废话不多说,直接上步骤

首先新建一个类HealthKitManage,采用单利模式

HealthKitManage.h中导入

#import

#import

1.定义

#define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]

#define CustomHealthErrorDomain @"com.sdqt.healthError"

2.定义几个方法

+(id)shareInstance; //单例

- (void)authorizeHealthKit:(void(^)(BOOL success, NSError *error))compltion;

- (void)getStepCount:(void(^)(double value, NSError *error))completion; //获取步数

- (void)getDistance:(void(^)(double value, NSError *error))completion; //获取距离

HealthKitManage.m中

1.单例

+(id)shareInstance{ //单例

static id manager ;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

manager = [[[self class] alloc] init];

});

return manager;

}

2.实现其他方法

/*

* @brief 检查是否支持获取健康数据

*/

- (void)authorizeHealthKit:(void(^)(BOOL success, NSError *error))compltion{

if(HKVersion >= 8.0){

if (![HKHealthStore isHealthDataAvailable]) {

NSError *error = [NSError errorWithDomain: @"com.raywenderlich.tutorials.healthkit" code: 2 userInfo: [NSDictionary dictionaryWithObject:@"HealthKit is not available in th is Device" forKey:NSLocalizedDescriptionKey]];

if (compltion != nil) {

compltion(false, error);

}

return;

}

if ([HKHealthStore isHealthDataAvailable]) {

if(self.healthStore == nil)

self.healthStore = [[HKHealthStore alloc] init];

/*

组装需要读写的数据类型

*/

NSSet *writeDataTypes = [self dataTypesToWrite];

NSSet *readDataTypes = [self dataTypesRead];

/*

注册需要读写的数据类型,也可以在“健康”APP中重新修改

*/

[self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {

if (compltion != nil) {

NSLog(@"error->%@", error.localizedDescription);

compltion (success, error);

}

}];

}

}

else {

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"iOS 系统低于8.0" forKey:NSLocalizedDescriptionKey];

NSError *aError = [NSError errorWithDomain:CustomHealthErrorDomain code:0 userInfo:userInfo];

compltion(0,aError);

}

}

/*!

* @brief 写权限

* @return 集合

*/

- (NSSet *)dataTypesToWrite{

HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];

HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];

HKQuantityType *temperatureType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];

HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];

return [NSSet setWithObjects:heightType, temperatureType, weightType,activeEnergyType,nil];

}

/*!

* @brief 读权限

* @return 集合

*/

- (NSSet *)dataTypesRead{

HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];

HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];

HKQuantityType *temperatureType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];

HKCharacteristicType *birthdayType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth];

HKCharacteristicType *sexType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];

HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

HKQuantityType *distance = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];

HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];

return [NSSet setWithObjects:heightType, temperatureType,birthdayType,sexType,weightType,stepCountType, distance, activeEnergyType,nil];

}

//获取步数

- (void)getStepCount:(void(^)(double value, NSError *error))completion{

HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];

// Since we are interested in retrieving the user's latest sample, we sort the samples in descending order, and set the limit to 1. We are not filtering the data, and so the predicate is set to nil.

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:stepType predicate:[HealthKitManage predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {

if(error){

completion(0,error);

}

else{

NSInteger totleSteps = 0;

for(HKQuantitySample *quantitySample in results){

HKQuantity *quantity = quantitySample.quantity;

HKUnit *heightUnit = [HKUnit countUnit];

double usersHeight = [quantity doubleValueForUnit:heightUnit];

totleSteps += usersHeight;

}

NSLog(@"当天行走步数 = %ld",(long)totleSteps);

completion(totleSteps,error);

}

}];

[self.healthStore executeQuery:query];

}

//获取公里数

- (void)getDistance:(void(^)(double value, NSError *error))completion{

HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];

NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:distanceType predicate:[HealthKitManage predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof hksample> * _Nullable results, NSError * _Nullable error) {

if(error){

completion(0,error);

}

else{

double totleSteps = 0;

for(HKQuantitySample *quantitySample in results){

HKQuantity *quantity = quantitySample.quantity;

HKUnit *distanceUnit = [HKUnit meterUnitWithMetricPrefix:HKMetricPrefixKilo];

double usersHeight = [quantity doubleValueForUnit:distanceUnit];

totleSteps += usersHeight;

}

NSLog(@"当天行走距离 = %.2f",totleSteps);

completion(totleSteps,error);

}

}];

[self.healthStore executeQuery:query];

}

/*!

* @brief 当天时间段

*

* @return 时间段

*/

+ (NSPredicate *)predicateForSamplesToday {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *now = [NSDate date];

NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];

[components setHour:0];

[components setMinute:0];

[components setSecond: 0];

NSDate *startDate = [calendar dateFromComponents:components];

NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];

NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];

return predicate;

}

调用,比如我们想在ViewConreoller中使用步数和距离

1.ViewConreoller.m 中先导入

#import "HealthKitManage.h"

2.获取步数,value即为步数

HealthKitManage *manage = [HealthKitManage shareInstance];

[manage authorizeHealthKit:^(BOOL success, NSError *error) {

if (success) {

NSLog(@"success");

[manage getStepCount:^(double value, NSError *error) {

NSLog(@"1count-->%.0f", value);

NSLog(@"1error-->%@", error.localizedDescription);

});

}];

}

else {

NSLog(@"fail");

}

}];

2.获取距离,value即为距离

HealthKitManage *manage = [HealthKitManage shareInstance];

[manage authorizeHealthKit:^(BOOL success, NSError *error) {

if (success) {

NSLog(@"success");

[manage getDistance:^(double value, NSError *error) {

NSLog(@"2count-->%.2f", value);

NSLog(@"2error-->%@", error.localizedDescription);

});

}];

}

else {

NSLog(@"fail");

}

}];

本文这样的方法,不能实时记录步数,它是一种每天截止到你获取数据时间的统计。

实时计步可以采用陀螺仪和传感器的方法,但是这种方法需要很麻烦的算法,否则手里拿着手机晃也会增加步数,本人才疏学浅,还不会。

文章仅供自己学习,复习和新手实现基本功能使用,觉得写的不好的,请移驾别处,好走不送~

获取android手机步数,获取手机健康应用中的步数和距离相关推荐

  1. 获取android的SDK或者手机目录路径

    获取android的SDK或者手机目录路径 Google为我们提供了API来获取SDK或者手机目录路径: 1.获取SD卡目录 File file1 = Environment.getExternalS ...

  2. Unity 获取Android版本号和其他手机信息

    获取版本号需要使用Gradle打包调用Java C# int systemMemory = SystemInfo.systemMemorySize; int processorCount = Syst ...

  3. iOS利用HealthKit框架从健康app中获取步数信息

    微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食. 统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为 ...

  4. HealthKit 从健康app中获取步数信息

    原文:http://blog.csdn.net/dynastyting/article/details/51858595 微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的 ...

  5. 获取Android手机的分辨率通过ADB命令

    获取Android手机的分辨率通过ADB命令 adb shell dumpsys window displays//此命令即可获取 WINDOW MANAGER DISPLAY CONTENTS (d ...

  6. 获取android系统手机的铃声和音量

    获取android系统手机的铃声和音量 通过程序 获取android系统手机的铃声和音量.设置音量的方法也很简单,AudioManager提供了方法: publicvoidsetStreamVolum ...

  7. android 短信位置,浅析Android手机卫士之手机实现短信指令获取位置

    推荐阅读: 获取位置 新建一个service的包 新建一个GPSService类继承系统的Service类 清单文件中注册一下 重写onCreate()方法,服务创建的时候回调 重写onDestroy ...

  8. 获取android型号代码,Android应用开发之Android获取手机品牌、手机型号、手机唯一序列号的代码教程...

    本文将带你了解Android应用开发Android获取手机品牌.手机型号.手机唯一序列号的代码教程,希望本文对大家学Android有所帮助. Android获取手机品牌.手机型号.手机唯一序列号的代码 ...

  9. 获取android手机基本信息

    http://zdpeng.iteye.com/blog/1676979 /*** 获取android当前可用内存大小 */private String getAvailMemory() {// 获取 ...

  10. Android 在Android手机上获取其他应用的包名及版本号

    获取Android手机上其他应用的包名及版本号方法有很多,可以通过AAPT从APK包中直接获取,也可以通过代码在手机上获取.显然,对于产品或者用户来说要获取这些信息,在手机上获取更为简便. 下面我们来 ...

最新文章

  1. 两道面试题,带你解析Java类加载机制
  2. Elasticsearch学习笔记-05浏览数据
  3. 【鸿蒙 HarmonyOS】界面跳转 ( Page Ability 的 action 标识 | Page Ability 之间的界面跳转及传递数据 | 鸿蒙工程下创建 Module | 代码示例 )
  4. python 不执行函数_解决python调用自己文件函数/执行函数找不到包问题
  5. struts+hibernate+oracle+easyui实现lazyout组件的简单案例——DeptDao层代码
  6. ubuntu wps缺少字体_WPS各版本
  7. windows中使用scrapyd遇到的问题
  8. Typora导出PDF时一直处于正在导出的状态
  9. java——ArrayList中contains()方法中的疑问
  10. matlab导出prn文件怎么打开,prn文件怎么打开?prn是什么意思?
  11. 微信朋友圈马赛克图片 —— 抓包破解
  12. Android NDK SO库隐藏内部符号表
  13. java点歌系统代码_基于jsp的KTV点歌系统-JavaEE实现KTV点歌系统 - java项目源码
  14. led同步回显到计算机屏幕,手把手教您如何将笔记本电脑的画面投屏到LED大屏幕上显示,音视频同步传输...
  15. win10开启快速启动,关机时电源键一直亮着无法正常关机。。。
  16. 云电脑是否可以玩挂机网游
  17. 速写人物的脸型怎么画?如何画好人物脸型?
  18. 计算机毕业设计(附源码)python校园疫情防控管理软件
  19. 张赐荣 | PHP 获取喜马拉雅音频直链地址
  20. PWM、SPWM、SVPWM的个人理解

热门文章

  1. Elastic-Job介绍
  2. linux下的rpm命令详解,RPM包命令详解
  3. 左程云算法菜手班整理(一)
  4. Echarts柱状图属性设置大全
  5. 测试员一份工作坚持多久跳槽,才能完美提升薪资?
  6. Java io流使用相对路径读取文件
  7. 2020中国数据智能产业图谱1.0版发布丨数据猿产业全景图
  8. linux netfilter路由表,Netfilter策略路由和uRPF
  9. 在css表格怎么居中对齐,css居中和对齐方法集锦
  10. 哈工大2020春形式语言与自动机期末试题