android - GoogleSignInAccount 变量在 Fitness API 文档的示例中为空
问题描述
我正在尝试按照此文档在我的 android 手机上访问 Google Fit History API。
我已经完成了所需的步骤:
1. 生成调试密钥
2. 从 SHA1 创建客户端 ID
3. 在 SDK 工具中安装 Google Play 服务(找不到 Google 存储库)
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
只是默认对象,并且大多数字段都是空的。这意味着对 Fitness 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.
...
我尝试谷歌搜索,但我仍然不明白如何正确和轻松地进行身份验证。