GoogleApiClient setAccountName无法在Service

时间:2016-05-27 06:32:53

标签: android google-play-services google-fit googlesigninapi googlesigninaccount

我正在尝试使用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线程上运行。

任何帮助都会受到赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

我明白了。问题是我的包名未在Google API控制台上注册。非常常见的错误,调试并非易事。这个故事的主旨?非常 阅读文档和官方指南。