0

我正在尝试使用 Google Fit API,并且我成功使用了 Google 的示例应用程序。当我运行它时,它弹出了一个登录窗口,我选择了我的帐户,然后按预期使用了 API。

在我的应用程序中,我必须保持对 API 的持续访问,因此我在服务中启动我的 google 客户端并尝试从服务中向 Google Fit 数据发出请求。初始化如下所示:

         public class MyService extends Service  {
....
....
....
protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient
                    = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
    // automanage can not be used in Service, so it is disabled.
    //                .enableAutoManage(
    //
    //                /* FragmentActivity */
    //                                  new FragmentActivity(),
    //                        this /* OnConnectionFailedListener */)
                    .addApi(ActivityRecognition.API)
                    .addApi(Fitness.RECORDING_API)
                    .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
                    .addApi(Fitness.HISTORY_API)
                    .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                    .setAccountName("myemail@gmail.com")
                    .build();
        }
.....
.....
}

当我这样做时,我收到以下错误:

 I/fitapi: Google Play services connection failed. Cause: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{1887aff: android.os.BinderProxy@1cd040cc}, message=null}

显然 .setAccountName(String) 没有像错误消息所暗示的那样工作。

我的问题如下:如果 .setAccountName 不起作用,我如何从服务登录?

从主要活动执行 .enableAutoManage() 有效,但它不允许后台进程继续收集健身数据。显然 .enableAutoManage() 不会在服务中工作,因为服务不在 UI 线程上运行。

任何帮助将不胜感激。谢谢。

4

1 回答 1

0

我想到了。问题在于我的包名未在 Google API 控制台上注册。非常常见的错误,调试起来并不简单。这个故事的主旨?仔细阅读文档和官方指南。

于 2018-04-06T16:06:35.190 回答