Oturumlarla çalışma

Oturumlar, kullanıcıların fitness etkinliği gerçekleştirdiği bir zaman aralığını temsil eder. Sessions API, uygulamanızın fitness mağazasında oturumlar oluşturmasına olanak tanır.

Kullanıcının bir fitness aktivitesini başlatıp tamamladığında uygulamanızı bilgilendirdiği devam eden fitness aktiviteleri için, gerçek zamanlı olarak oturumlar oluşturabilirsiniz.

Ayrıca, bir fitness aktivitesi bittikten sonra veya Google Fit dışından veri ve oturumlar içe aktardığınızda da fitness mağazasına oturum ekleyebilirsiniz.

Oturumları gerçek zamanlı olarak oluşturun

Devam eden fitness aktivitelerine yönelik seanslar oluşturmak için aşağıdaki adımları tamamlayın:

  1. RecordingClient.subscribe yöntemini kullanarak fitness verilerine abone olun.

  2. Kullanıcı fitness aktivitesini başlattığında SessionsClient.startSession yöntemini kullanarak bir oturum başlatın.

  3. Kullanıcı fitness aktivitesini sonlandırdığında SessionsClient.stopSession yöntemini kullanarak oturumu durdurun.

  4. RecordingClient.unsubscribe yöntemini kullanarak artık ilgilenmediğiniz fitness verileri e-posta listesinden çıkabilirsiniz.

Oturum başlatma

Uygulamanızda oturum başlatmak için SessionsClient.startSession yöntemini kullanın:

Kotlin

// 1. Subscribe to fitness data
// 2. Create a session object
// (provide a name, identifier, description, activity and start time)
val session = Session.Builder()
    .setName(sessionName)
    .setIdentifier("UniqueIdentifierHere")
    .setDescription("Morning run")
    .setActivity(FitnessActivities.RUNNING)
    .setStartTime(startTime, TimeUnit.MILLISECONDS)
    .build()

// 3. Use the Sessions client to start a session:
Fitness.getSessionsClient(this, googleSigninAccount)
    .startSession(session)
    .addOnSuccessListener {
        Log.i(TAG, "Session started successfully!")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was an error starting the session", e)
    }

Java

// 1. Subscribe to fitness data
// 2. Create a session object
// (provide a name, identifier, description, activity and start time)
Session session = new Session.Builder()
        .setName(sessionName)
        .setIdentifier("UniqueIdentifierHere")
        .setDescription("Morning run")
        .setActivity(FitnessActivities.RUNNING)
        .setStartTime(startTime, TimeUnit.MILLISECONDS)
        .build();

// 3. Use the Sessions client to start a session:
Fitness.getSessionsClient(this, googleSigninAccount)
        .startSession(session)
        .addOnSuccessListener(unused ->
                Log.i(TAG, "Session started successfully!"))
        .addOnFailureListener(e ->
                Log.w(TAG, "There was an error starting the session", e));

Oturumu durdurma

Uygulamanızda bir oturumu durdurmak için SessionsClient.stopSession yöntemini kullanın:

Kotlin

// Invoke the SessionsClient with the session identifier
Fitness.getSessionsClient(this, googleSigninAccount)
    .stopSession(session.getIdentifier())
    .addOnSuccessListener {
        Log.i(TAG, "Session stopped successfully!")

        // Now unsubscribe from the fitness data (see
        // Recording Fitness data)
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was an error stopping the session", e)
    }

Java

// Invoke the SessionsClient with the session identifier
Fitness.getSessionsClient(this, googleSigninAccount)
        .stopSession(session.getIdentifier())
        .addOnSuccessListener (unused -> {
            Log.i(TAG, "Session stopped successfully!");
            // Now unsubscribe from the fitness data (see
            // Recording Fitness data)
        })
        .addOnFailureListener(e ->
                Log.w(TAG, "There was an error stopping the session", e));

Sonuçta elde edilen oturum aşağıdaki parametrelere sahiptir:

  • Başlangıç zamanı: Uygulamanızın SessionsClient.startSession yöntemini çağırdığı zaman.

  • Bitiş zamanı: Uygulamanızın SessionsClient.stopSession yöntemini çağırdığı zaman.

  • Ad: SessionsClient.startSession öğesine ilettiğiniz Session nesnesindeki ad.

Fitness mağazasında seans ekle

Daha önce topladığınız verilerle oturumlar eklemek için aşağıdakileri yapın:

  1. Zaman aralığını ve diğer gerekli bilgileri belirten bir Session nesnesi oluşturun.

  2. Oturumla bir SessionInsertRequest oluşturun.

  3. Dilerseniz veri kümeleri ekleyebilir ve veri noktalarını toplayabilirsiniz.

  4. SessionsClient.insertSession yöntemini kullanarak oturumu ekleyin.

Oturum ekleme

Kullanıcının fitness geçmişine oturum meta verilerini içeren fitness verileri eklemek için önce bir SessionInsertRequest örneği oluşturun:

Kotlin

// Create a session with metadata about the activity.
val session = Session.Builder()
    .setName(SAMPLE_SESSION_NAME)
    .setIdentifier("UniqueIdentifierHere")
    .setDescription("Long run around Shoreline Park")

    .setActivity(FitnessActivities.RUNNING)
    .setStartTime(startTime, TimeUnit.MILLISECONDS)
    .setEndTime(endTime, TimeUnit.MILLISECONDS)
    .build()

// Build a session insert request
val insertRequest = SessionInsertRequest.Builder()
    .setSession(session)
    // Optionally add DataSets for this session.
    .addDataSet(dataset)
    .build()

Java

// Create a session with metadata about the activity.
Session session = new Session.Builder()
        .setName(SAMPLE_SESSION_NAME)
        .setIdentifier("UniqueIdentifierHere")
        .setDescription("Long run around Shoreline Park")

        .setActivity(FitnessActivities.RUNNING)
        .setStartTime(startTime, TimeUnit.MILLISECONDS)
        .setEndTime(endTime, TimeUnit.MILLISECONDS)
        .build();

// Build a session insert request
SessionInsertRequest insertRequest = new SessionInsertRequest.Builder()
        .setSession(session)
        // Optionally add DataSets for this session.
        .addDataSet(dataset)
        .build();

SessionInsertRequest sınıfı, fitness geçmişine veri eklemek ve aynı SessionsClient.insertSession çağrısında oturum oluşturmak için kullanışlı yöntemler sunar. Veri kümeleri, önce HistoryClient.insertData yöntemini çağırmışsınız gibi eklenir ve ardından oturum oluşturulur.

Kotlin

Fitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .insertSession(insertRequest)
    .addOnSuccessListener {
        Log.i(TAG, "Session insert was successful!")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "There was a problem inserting the session: ", e)
    }

Java

Fitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .insertSession(insertRequest)
        .addOnSuccessListener (unused ->
                Log.i(TAG, "Session insert was successful!"))
        .addOnFailureListener(e ->
        Log.w(TAG, "There was a problem inserting the session: ", e));

Aktivite segmentleri ekle

Google Fit'teki aktivite segmenti verileri, kullanıcıların belirli bir zaman aralığında hangi fitness aktivitesini gerçekleştirdiklerini gösterir. Aktivite segmenti verileri com.google.activity.segment (TYPE_ACTIVITY_SEGMENT) türündedir ve özellikle antrenmanlar sırasında duraklatmaların desteklenmesi için yararlıdır.

Örneğin, Session.Builder.setActivity() yöntemiyle 30 dakikalık bir koşu oturumu oluşturursanız ancak kullanıcı arada 10 dakika ara verirse uygulamanız, kullanıcının 30 dakika boyunca koşu yaptığını hatalı bir şekilde gösterir. Uygulamanız, kullanıcının yürüyor mu yoksa koşuyor mu olduğunu algılayabiliyorsa aktivite segmenti verileri, uygulamanızın kullanıcının 10 dakika koştuğunu, 10 dakika yürüdüğünü ve ardından 10 dakika daha koştuğunu gösterebilmesini sağlar. Diğer uygulamalar da eklediğiniz etkinlik segmenti verilerine bakarak etkinliği doğru bir şekilde bildirebilir.

Bir oturuma etkinlik segmenti verileri eklemek için com.google.activity.segment türünde noktaları içeren bir veri kümesi oluşturun. Bu noktaların her biri, kullanıcının tek bir etkinlik türünü gerçekleştirdiği sürekli bir zaman aralığını temsil eder.

Önceki koşu ve yürüyüş örneğinde üç aktivite segmenti noktası gerekecekti: biri ilk 10 dakika koşu için, biri sonraki 10 dakika boyunca yürümek için, diğeri son 10 dakika koşusu için.

Kotlin

// Create a DataSet of ActivitySegments to indicate the runner walked for
// 10 minutes in the middle of a run.
val activitySegmentDataSource = DataSource.Builder()
    .setAppPackageName(this.packageName)
    .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
    .setStreamName(SAMPLE_SESSION_NAME + "-activity segments")
    .setType(DataSource.TYPE_RAW)
    .build()

val firstRunningDp = DataPoint.builder(activitySegmentDataSource)
    .setActivityField(Field.FIELD_ACTIVITY, FitnessActivities.RUNNING)
    .setTimeInterval(startTime, startWalkTime, TimeUnit.MILLISECONDS)
    .build()

val walkingDp = DataPoint.builder(activitySegmentDataSource)
    .setActivityField(Field.FIELD_ACTIVITY, FitnessActivities.WALKING)
    .setTimeInterval(startWalkTime, endWalkTime, TimeUnit.MILLISECONDS)
    .build()

val secondRunningDp = DataPoint.builder(activitySegmentDataSource)
    .setActivityField(Field.FIELD_ACTIVITY, FitnessActivities.RUNNING)
    .setTimeInterval(endWalkTime, endTime, TimeUnit.MILLISECONDS)
    .build()

val activitySegments = DataSet.builder(activitySegmentDataSource)
    .addAll(listOf(firstRunningDp, walkingDp, secondRunningDp))
    .build()

// Create a session with metadata about the activity.
val session = Session.Builder()
    .setName(SAMPLE_SESSION_NAME)
    .setDescription("Long run around Shoreline Park")
    .setIdentifier("UniqueIdentifierHere")
    .setActivity(FitnessActivities.RUNNING)
    .setStartTime(startTime, TimeUnit.MILLISECONDS)
    .setEndTime(endTime, TimeUnit.MILLISECONDS)
    .build()

// Build a session insert request
val insertRequest = SessionInsertRequest.Builder()
    .setSession(session)
    .addDataSet(activitySegments)
    .build()

Java

// Create a DataSet of ActivitySegments to indicate the runner walked for
// 10 minutes in the middle of a run.
DataSource activitySegmentDataSource = new DataSource.Builder()
        .setAppPackageName(getPackageName())
        .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
        .setStreamName(SAMPLE_SESSION_NAME + "-activity segments")
        .setType(DataSource.TYPE_RAW)
        .build();

DataPoint firstRunningDp = DataPoint.builder(activitySegmentDataSource)
        .setActivityField(Field.FIELD_ACTIVITY, FitnessActivities.RUNNING)
        .setTimeInterval(startTime, startWalkTime, TimeUnit.MILLISECONDS)
        .build();

DataPoint walkingDp = DataPoint.builder(activitySegmentDataSource)
        .setActivityField(Field.FIELD_ACTIVITY, FitnessActivities.WALKING)
        .setTimeInterval(startWalkTime, endWalkTime, TimeUnit.MILLISECONDS)
        .build();

DataPoint secondRunningDp = DataPoint.builder(activitySegmentDataSource)
        .setActivityField(Field.FIELD_ACTIVITY, FitnessActivities.RUNNING)
        .setTimeInterval(endWalkTime, endTime, TimeUnit.MILLISECONDS)
        .build();

DataSet activitySegments = DataSet.builder(activitySegmentDataSource)
        .addAll(Arrays.asList(firstRunningDp, walkingDp, secondRunningDp))
        .build();

// Create a session with metadata about the activity.
Session session = new Session.Builder()
        .setName(SAMPLE_SESSION_NAME)
        .setDescription("Long run around Shoreline Park")
        .setIdentifier("UniqueIdentifierHere")
        .setActivity(FitnessActivities.RUNNING)
        .setStartTime(startTime, TimeUnit.MILLISECONDS)
        .setEndTime(endTime, TimeUnit.MILLISECONDS)
        .build();

// Build a session insert request
SessionInsertRequest insertRequest = new SessionInsertRequest.Builder()
        .setSession(session)
        .addDataSet(activitySegments)
        .build();

Seansları kullanarak fitness verilerini okuma

Sessions API, fitness mağazasından bazı ölçütlerle eşleşen oturumların listesini almanıza olanak tanır. Örneğin, bir zaman aralığında yer alan tüm oturumları veya ad ya da kimliğe göre belirli bir oturumu alabilirsiniz. Ayrıca, uygulamanız tarafından mı yoksa herhangi bir uygulama tarafından oluşturulan oturumlarla ilgilendiğinizi de belirtebilirsiniz.

Bazı ölçütlerle eşleşen oturumların listesini elde etmek için önce bir SessionReadRequest örneği oluşturun:

Kotlin

// Use a start time of 1 week ago and an end time of now.
val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault())
val startTime = endTime.minusWeeks(1)

// Build a session read request
val readRequest = SessionReadRequest.Builder()
    .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
    .read(DataType.TYPE_SPEED)
    .setSessionName(SAMPLE_SESSION_NAME)
    .build()

Java

// Use a start time of 1 week ago and an end time of now.
ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault())
ZonedDateTime startTime = endTime.minusWeeks(1)

// Build a session read request
SessionReadRequest readRequest = new SessionReadRequest.Builder()
        .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)
        .read(DataType.TYPE_SPEED)
        .setSessionName(SAMPLE_SESSION_NAME)
        .build();

Daha sonra SessionsClient.readSession yöntemini kullanın:

Kotlin

Fitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
    .readSession(readRequest)
    .addOnSuccessListener { response ->
        // Get a list of the sessions that match the criteria to check the result.
        val sessions = response.sessions
        Log.i(TAG, "Number of returned sessions is: ${sessions.size}")
        for (session in sessions) {
            // Process the session
            dumpSession(session)

            // Process the data sets for this session
            val dataSets = response.getDataSet(session)
            for (dataSet in dataSets) {
                // ...
            }
        }
    }
    .addOnFailureListener { e ->
        Log.w(TAG,"Failed to read session", e)
    }

Java

Fitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
        .readSession(readRequest)
        .addOnSuccessListener(response -> {
            // Get a list of the sessions that match the criteria to check the
            // result.
            List<Session> sessions = response.getSessions();
            Log.i(TAG, "Number of returned sessions is: ${sessions.size}");
            for (Session session : sessions) {
                // Process the session
                dumpSession(session);

                // Process the data sets for this session
                List<DataSet> dataSets = response.getDataSet(session);
                for (DataSet dataSet : dataSets) {
                    // ...
                }
            }
        })
        .addOnFailureListener(e ->
                Log.w(TAG,"Failed to read session", e));

Seansları kullanarak uyku verilerini okuma

Uyku oturumları diğer etkinlik oturumlarından ayrı olarak ele alınır. Varsayılan olarak, okunan yanıtlar uyku oturumlarını değil, yalnızca etkinlik oturumlarını içerir.

Uyku oturumlarını dahil etmek için SessionReadRequest cihazınızı oluştururken includeSleepSessions yöntemini kullanın. Hem etkinlikleri hem de oturumları dahil etmek için hem includeSleepSessions hem de includeActivitySessions kullanın.

Oturumları diğer uygulamalarda göster

Uygulamanız, kullanıcılara farklı bir uygulamadaki belirli bir oturumun daha ayrıntılı bir görünümünü göstermek için oturum bilgilerini içeren bir niyet çağırabilir. Oturumu oluşturan uygulama gibi belirli bir uygulamayı belirtebilirsiniz. Veya oturumu oluşturan uygulama cihazda yüklü değilse, fitness aktivitesini gösterebilen tüm uygulamaların amaca yanıt vermesine izin verebilirsiniz.

Oturum verilerini farklı bir uygulamada göstermek amacıyla niyet oluşturmak için SessionsApi.ViewIntentBuilder sınıfını kullanın:

Kotlin

// Pass your activity object to the constructor
val intent = SessionsApi.ViewIntentBuilder(this)
    .setPreferredApplication("com.example.someapp") // optional
    .setSession(session)
    .build()

// Invoke the intent
startActivity(intent)

Java

// Pass your activity object to the constructor
Intent intent = new SessionsApi.ViewIntentBuilder(this)
        .setPreferredApplication("com.example.someapp") // optional
        .setSession(session)
        .build();

// Invoke the intent
startActivity(intent);

Diğer uygulamalardan intent alma

Uygulamanızı diğer sağlık ve sağlıklı yaşam uygulamalarından amaçlar almak üzere kaydetmek için manifest dosyanızda aşağıdakine benzer bir intent filtresi tanımlayın:

<intent-filter>
    <action android:name="vnd.google.fitness.VIEW"/>
    <data android:mimeType="vnd.google.fitness.session/running"/>
</intent-filter>

Uygulamanızın Google Fit'ten aldığı her amaç yalnızca bir etkinliktir, ancak tek bir intent filtresinde birden fazla MIME türünü filtreleyebilirsiniz. Uygulamanızın intent filtresi, uygulamanızın desteklediği tüm etkinlikleri içermelidir.

Fitness amaçları şu ekstraları içerir:

  • vnd.google.gms.fitness.start_time
  • vnd.google.gms.fitness.end_time
  • vnd.google.gms.fitness.session

Bu ekstralardan aşağıdaki şekilde veri elde edebilirsiniz:

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ...
    val supportedType = Session.getMimeType(FitnessActivities.RUNNING)

    if (Intent.ACTION_VIEW == intent.action && supportedType == intent.type) {
        // Get the intent extras
        val startTime = Fitness.getStartTime(intent, TimeUnit.MILLISECONDS);
        val endTime = Fitness.getEndTime(intent, TimeUnit.MILLISECONDS)
        val session = Session.extract(intent)
    }
}

Java

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    String supportedType = Session.getMimeType(FitnessActivities.RUNNING);

    if (Intent.ACTION_VIEW.equals(getIntent().getAction()) && supportedType.equals(getIntent().getType())) {
        // Get the intent extras
        long startTime = Fitness.getStartTime(getIntent(), TimeUnit.MILLISECONDS);
        long endTime = Fitness.getEndTime(getIntent(), TimeUnit.MILLISECONDS);
        Session session = Session.extract(getIntent());
    }
}