취소
다음에 대한 결과 표시 
다음에 대한 검색 
다음을 의미합니까? 

제목:

flutter로 삼성 헬스의 걸음수 가져오는 방법

(게시글 작성 시간: 06-24-2025 11:09 PM)
140 보기
hong5
Active Level 1
옵션
Samsung Health

flutter로 앱 개발중인 사람입니다.

권한 설정을 다 하고 걸음수를 가져오는데 계속 0걸음이 가져와집니다. 날짜 범위도 권한을 받은 후를 포함하도록 했는데에도 0걸음만 가져와집니다...

헬스 커넥트도 삼성헬스, 저의 앱 모두 걸음수 읽기/쓰기 허용 했습니다. 0걸음이 가져와진다는건 연결이 돼서 걸음수를 읽는다는 것 같은데 정확한 걸음수가 아닌 0걸음만 가져와지는 원인을 못찾겠어서 이렇게 문의드립니다.

혹시 몰라 제 코드를 남깁니다.

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:health/health.dart';
import 'package:permission_handler/permission_handler.dart';

class NewScreen extends StatefulWidget {
const NewScreen({super.key});

@override
State<NewScreen> createState() => _NewScreenState();
}

class _NewScreenState extends State<NewScreen> {
// 1. Health 인스턴스
final health = Health();
// 걸음수 저장 변수
String steps = '?';
// HealthDataType 리스트 (걸음수)
List<HealthDataType> types = [HealthDataType.STEPS];
// 권한 리스트 - types와 같은 순서로 설정(Android Health Connect에서 필요)
List<HealthDataAccess> permissions = [
HealthDataAccess.READ_WRITE,
]; // ios는 필요 없는데 Android에서 필요함
late DateTime startDate;
late DateTime endDate;
bool isInstalled = false; // google health connect 설치 여부

@override
void initState() {
// TODO: implement initState
fnInint();
super.initState();
}

Future<void> fnInint() async {
health.configure();
if (Platform.isAndroid) {
fnCheckHealthConnectSdkStatus(); // google health connect 설치 확인
await fnRequestAuthorization(); // 권한 요청 및 걸음수 데이터 가져오기
} else if (Platform.isIOS) {
await fnRequestAuthorization();
}
}

// 날짜 가져오기
Future<void> fnSetDate() async {
// 0.5초 정도 기다리기(데이터 가져오기)
await Future.delayed(const Duration(milliseconds: 500));
// 날짜 설정
DateTime start = DateTime(2025, 6, 12);
DateTime end = DateTime(2025, 6, 12, 23, 59, 59); // 같은 날의 마지막 시간으로 설정

startDate = start;
endDate = end;
}

// google health connect와 연결 (android)
Future<void> fnCheckHealthConnectSdkStatus() async {
// google health connect 설치 안됐을 때 설치
isInstalled = await health.isHealthConnectAvailable();
if (!isInstalled) {
await health.installHealthConnect();
return; // 설치 후 다시 초기화
}
// google health connect와 연결 확인
// var healthConnectSdkStatus = await health.getHealthConnectSdkStatus();
}

// 건강 데이터 권한 요청 및 걸음수 데이터 가져오기
Future<void> fnRequestAuthorization() async {
// 위험 보호 단계라서 권한 요청이 필요함(자동으로 안됨)
await Permission.activityRecognition.request();
// await Permission.location.request(); // 걸음수만 가져올거라 필요 X

if (isInstalled) {
bool? hasPermissions =
(Platform.isAndroid)
? await health.hasPermissions(types, permissions: permissions)
: await health.hasPermissions(types);

print("hasPermissions: $hasPermissions");
if (hasPermissions != true) {
hasPermissions = await health.requestAuthorization(types);
print('hihihihihi: $hasPermissions');
// historic data 읽기 허용 (Android Health Connect 에서 과거 데이터 접근 - 30일 전까지만 가능...)
var hihi = await health.requestHealthDataHistoryAuthorization();
print('hihi: $hihi');
setState(() {
fnFetchSteps(
DateTime(2025, 6, 24), // 예시로 2025년 6월 11일로 설정
DateTime(2025, 6, 24, 23, 59, 59), // 같은 날의 마지막 시간으로 설정
);
});
} else {
// historic data 읽기 허용 (Android Health Connect 에서 과거 데이터 접근 - 30일 전까지만 가능 ㅠㅠ)
// await health.isHealthDataHistoryAuthorized().then((isAuthorized) {
// if (!isAuthorized) {
// print('isAutorized: $isAuthorized');
// health.requestHealthDataHistoryAuthorization();
// // var hihi = health.requestHealthDataHistoryAuthorization();
// // print('hihi: $hihi');
// }
// });

var history = await health.requestHealthDataHistoryAuthorization();
print('history: $history');
print('##########################');
print(DateTime.utc(2025, 6, 24));
print(DateTime.utc(2025, 6, 24, 0, 0, 0));
print(DateTime.utc(2025, 6, 24, 23, 59, 59));
print('##########################');
print(DateTime(2025, 6, 24, 0, 0, 0));
setState(() {
fnFetchSteps(
// 예시로 2025년 6월 11일로 설정
DateTime(2025, 6, 24), // 예시로 2025년 6월 11일로 설정
DateTime(2025, 6, 24, 23, 59, 59), // 같은 날의 마지막 시간으로 설정
);
});
}
} else {
// iOS에서는 권한 요청만 하면 됨
setState(() {
fnFetchSteps(
DateTime(2025, 6, 24), // 예시로 2025년 6월 11일로 설정
DateTime(2025, 6, 24, 23, 59, 59), // 같은 날의 마지막 시간으로 설정
);
});
}
}

// 권한 요청
Future<void> authorize() async {
await Permission.activityRecognition.request();

// health.hasPermissions : 이미 권한이 있는지 확인만 함 (요청은 안 함)
bool? hasPermissions = await health.hasPermissions(
types,
permissions: permissions,
);

// hasPermissions = false; // 플러그인 제한으로 WRITE 여부 파악이 안 되므로 항상 false로 처리

bool authorized = false;

if (hasPermissions != null && !hasPermissions) {
try {
// health.requestAuthorization : 권한 요청(권한 없을 경우 사용자에게 요청 창 띄움)
authorized = await health.requestAuthorization(
types,
permissions: permissions,
);

// historic data 읽기 허용 (Android Health Connect 에서 과거 데이터 접근)
await health.requestHealthDataHistoryAuthorization();
} catch (e) {
debugPrint("Exception in authorize: $e");
}
}
}

// 걸음수 가져오기
Future<void> fnFetchSteps(startDate, endDate) async {
// 0.5초 정도 기다리기(데이터 가져오기)
await Future.delayed(const Duration(milliseconds: 500));

int? totalSteps = await health.getTotalStepsInInterval(
startDate,
endDate,
includeManualEntry: true, // 또는 false 확인
); // Future를 기다림
setState(() {
steps = totalSteps?.toString() ?? '??'; // null일 경우 '0'으로 처리
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('New Screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('걸음수'),
const SizedBox(height: 20),
Text(
steps,
style: TextStyle(fontSize: 16, color: Colors.grey[700]),
),
],
),
),
);
}
}
2 댓글
고전파
Expert Level 2
Samsung Health
개발자 포럼에 질문하셔야 할듯요
옵션
Samsung Health

안녕하세요. 삼성 헬스 서비스 운영 담당자입니다.

앱 개발과 관련하여 도움이 필요하실 경우, 아래의 사이트를 통하여 문의 부탁드립니다.

http://developer.samsung.com/health

감사합니다.