Переменная GoogleSignInAccount равна нулю в примере из документации по API для фитнеса - PullRequest
0 голосов
/ 10 ноября 2019

Я пытаюсь следовать этому документу для доступа к API Google Fit History на моем телефоне с Android.

Я прошел необходимые шаги:
1. Созданиеключ отладки
2. Создание идентификатора клиента из SHA1
3. Установка Google Play Services в инструментах SDK (не удалось найти Google Repository)
4. Использование примера кода из здесь

MainActivity.kt

import android.view.MenuItem

import kotlinx.android.synthetic.main.activity_main.*
import android.os.AsyncTask
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.fitness.Fitness
import com.google.android.gms.fitness.FitnessOptions
import com.google.android.gms.fitness.data.DataType
import com.google.android.gms.fitness.request.DataReadRequest
import com.google.android.gms.tasks.Tasks
import java.util.*
import java.util.concurrent.TimeUnit
import android.util.Log
import kotlin.system.exitProcess


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        val fitnessOptions = FitnessOptions.builder()
                .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
                .build()

        val googleSignInAccount = GoogleSignIn.getAccountForExtension(this, fitnessOptions)
        if(googleSignInAccount.idToken.isNullOrEmpty()){
            Log.e("GSA",googleSignInAccount.toString())
            exitProcess(1)
        }

        val cal = Calendar.getInstance()
        val now = Date()
        cal.time = now
        cal.add(Calendar.HOUR_OF_DAY, -1)
        val endTime = cal.timeInMillis

        cal.add(Calendar.HOUR_OF_DAY, -12)
        val startTime = cal.timeInMillis
        val response = Fitness.getHistoryClient(this, googleSignInAccount)
                .readData(DataReadRequest.Builder()
                        .read(DataType.TYPE_STEP_COUNT_DELTA)
                        .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                        .build())
        AsyncTask.execute(Runnable {
            run(){
                Log.d ("GSA",googleSignInAccount.account.toString())
                val readDataResult = Tasks.await(response)
                val dataSet = readDataResult.getDataSet(DataType.TYPE_STEP_COUNT_DELTA)
                println(dataSet.toString())
            }
        })
        ...
    }

Однако каждый раз, когда я запускаю это, я замечаю, что googleSignInAccount является просто объектом по умолчанию, и большинство полей являются нулевыми. Это означает, что вызов фитнес-API возвращает:

2019-11-09 14:15:49.933 31216-31263/site.arashout.fitpets E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: site.arashout.fitpets, PID: 31216
    java.lang.Error: java.util.concurrent.ExecutionException: com.google.android.gms.common.api.ApiException: 4: The user must be signed in to make this API call.
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1173)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.util.concurrent.ExecutionException: com.google.android.gms.common.api.ApiException: 4: The user must be signed in to make this API call.
...

Я пробовал поискать в Google, но до сих пор не понимаю, как правильно и легко пройти аутентификацию.

...