您好,欢迎访问一九零五行业门户网

GoogleServices之GooglePlayService Accessing Google APIS(访

googleservices之googleplayservice accessing google apis( 访问 谷歌apis) 官方 文档 翻译 accessinggoogle apis( 访问 谷歌 apis) 当你想要连接到一个googleplayservice库中提供的api,(比如:google,games,或者drive),你需要创建一个 googleapiclient 的
 googleservices之googleplayservice  accessing google apis(访问谷歌apis)官方文档翻译
    accessinggoogle apis(访问谷歌apis)         当你想要连接到一个googleplayservice库中提供的api,(比如:google+,games,或者drive),你需要创建一个googleapiclient的实例。google api client提供了一个公共的入口点给所有的谷歌服务以及在用户设备和每个谷歌服务之间管理网络连接。
       这个指南示例你如何使用google api client:
1, 连接到一个或者多个googleplayservice是异步的和失败处理。
2,  执行同步和异步api调用很多google apiclient
注意:如果你已经有先有的应用使用子类googleplayservicesclient连接到googleplayservice,你应当尽可能迁移到googleapiclient。
图1.一个插图显示了google aps客户端是如何给连接和调用许多有效的google play services 提供接口,像 games和driveconnecting torest apis如果你想使用googleapi,但不包括google play services,你可以适当的restapi连接,但是你必须获取一个 oauth 2.0的令牌。获取更多信息,请阅读:authorizing with google for rest apis.
开始前,你必须先安装googleplay services库(版本号为15或者更高)为你的安卓sdk。如果你还没有准备好,请按照以下说明去做:set up google play services sdk.
start a connection 开始连接一旦你的项目引用google play services 库,你就可以使用googleapiclient.builder apis在你的activity的oncreate方法里创建googleapiclient实例。 googleapiclient.builder这个类提供的方法允许你指定你想使用的google apis和你想得到的oauth 2.0作用域。例如:这里是一个googleapiclient 使用google drive service连接的实例。
googleapiclient mgoogleapiclient=newgoogleapiclient.builder(this)
    .addapi(drive.api)
    .addscope(drive.scope_file)
    .build();
你可以通过追加addapi() 和 addscope().添加多个apis和多个scopes给相同的 googleapiclient。
重点:为了避免客户端在没有安装android wear app的设备上连接错误,请使用一个单独的 googleapiclient实例仅仅访问 wearable api。获取更多的信息,请看:access the wearable api
在开始连接之前你要调用googleapiclient的connect() 方法,你必须为回调接口 connectioncallbacks and onconnectionfailedlistener指定一个实现。当连接google play services成功,失败或者暂停时这些接口会接受异步方法connect()的回调。
例如:这里是一个实现了回调接口并且将他们添加到googleapi客户端的activity
import gms.common.api.*;
import gms.drive.*;
import android.support.v4.app.fragmentactivity;
public classmyactivityextendsfragmentactivity
        implements connectioncallbacks, onconnectionfailedlistener {
    private googleapiclient mgoogleapiclient;
@override
    protected void oncreate(bundle savedinstancestate){
        super.oncreate(savedinstancestate);
// create a googleapiclient instance
        mgoogleapiclient = new googleapiclient.builder(this)
                .addapi(drive.api)
                .addscope(drive.scope_file)
                .addconnectioncallbacks(this)
                .addonconnectionfailedlistener(this)
                .build();
        ...
    }
@override
    public void onconnected(bundle connectionhint){
        // connected to google play services!
        // the good stuff goes here.
    }
@override
    public void onconnectionsuspended(int cause){
        // the connection has been interrupted.
        // disable any ui components that depend on google apis
        // until onconnected() is called.
    }
@override
    public void onconnectionfailed(connectionresult result){
        // this callback is important for handling errors that
        // may occur while attempting to connect with google.
        //
        // more about this in the next div.
        ...
    }
}
定义了回调接口,你将准备调用connect(). 为了优雅的管理连接的生命周期,你应该调用connect(). 在activity的onstart()方法(除非你想晚一点连接)然后调用disconnect()在onstop()方法中。例如:
@override
    protected void onstart(){
        super.onstart();
        if (!mresolvingerror){  // more about this later
            mgoogleapiclient.connect();
        }
    }
@override
    protected void onstop(){
        mgoogleapiclient.disconnect();
        super.onstop();
    }
但是,如果您运行这段代码时,很有可能会失败,应用程序将接收调用onconnectionfailed()并发生sign_in_required错误,因为没有指定的用户帐户,下一节将展示如何处理这个错误等等。
handleconnection failures(处理连接失败)当你接收回调调用onconnectionfailed(),你应该调用connectionresult 对象提供的 hasresolution()方法。如果返回true,你可以请求用户立即采取行动通过调用connectionresult对象的startresolutionforresult()方法处理错误。这个 startresolutionforresult()方法的行为跟startactivityforresult() 比较相似,并启动适当的activity为用户解决错误(比如像一个选择账户的acticity)
       如果hasresolution()返回false,你应该通过错误代码调用 googleplayservicesutil.geterrordialog(),它会通过googleplayservices适当的错误给你返回一个dialog.         这个对话框                                                                                                                                                                                                                  提供了一个简单的错误解释信息,但他也有肯呢过提供一个action去启动一个activity去解决错误(比如当用户需要安装新版本的googleplayservice)
比如,你应该像这样调用 onconnectionfailed()
public class myactivity extends fragmentactivity
        implements connectioncallbacks, onconnectionfailedlistener {
// requestcode to use when launching the resolution activity
    private staticfinalint request_resolve_error=1001;
    // uniquetag for the error dialog fragment
    private staticfinalstring dialog_error=dialog_error;
    // bool totrack whether the app is already resolving an error
    private boolean mresolvingerror=false;
...
@override
    public void onconnectionfailed(connectionresult result){
        if (mresolvingerror){
            // already attempting to resolve an error.
               //如果正在解决这个错误,什么也不做
            return;
        } elseif(result.hasresolution()){
            try {
                mresolvingerror = true;
                result.startresolutionforresult(this, request_resolve_error);
            } catch(sendintentexception e){
                // there was an error with theresolution intent. try again.
                mgoogleapiclient.connect();
            }
        } else{
            // show dialog usinggoogleplayservicesutil.geterrordialog()
            showerrordialog(result.geterrorcode());
            mresolvingerror = true;
        }
    }
// the restof this code is all about building the error dialog
/* creates adialog for an error message */
    private void showerrordialog(int errorcode){
        // create a fragment for the error dialog
        errordialogfragment dialogfragment = new errordialogfragment();
        // pass the error that should be displayed
        bundle args = new bundle();
        args.putint(dialog_error, errorcode);
        dialogfragment.setarguments(args);
        dialogfragment.show(getsupportfragmentmanager(),errordialog);
    }
/* calledfrom errordialogfragment when the dialog is dismissed. */
    public void ondialogdismissed(){
        mresolvingerror = false;
    }
/* afragment to display an error dialog */
    public staticclasserrordialogfragmentextendsdialogfragment{
        public errordialogfragment(){}
@override
        public dialog oncreatedialog(bundle savedinstancestate){
            // get the error code and retrieve theappropriate dialog
            int errorcode = this.getarguments().getint(dialog_error);
            return googleplayservicesutil.geterrordialog(errorcode,
                    this.getactivity(), request_resolve_error);
        }
@override
        public void ondismiss(dialoginterface dialog){
            ((mainactivity)getactivity()).ondialogdismissed();
        }
    }
}
一旦用户通过提供的 startresolutionforresult() orgoogleplayservicesutil.geterrordialog()完成解决,你的activity会在onactivityresult()方法里接受处理结果码result_ok 。你可以继续调用connect() 比如:
@override
protected void onactivityresult(int requestcode,int resultcode,intent data){
    if (requestcode== request_resolve_error){
        mresolvingerror = false;
        if (resultcode== result_ok){
            // make sure the app is not alreadyconnected or attempting to connect
            if (!mgoogleapiclient.isconnecting()&&
                    !mgoogleapiclient.isconnected()){
                mgoogleapiclient.connect();
            }
        }
    }
}
在上面的代码中,你可能注意到布尔变量mresolvingerror。他追踪应用状态当用户正在解决错误时避免重复尝试解决相同的问题。例如,当选择用户的对话框正在展现解决sign_in_required这个错误,用户有可能旋转屏幕。就会再次调用onstart()重新展现你的activity,这个时候再次调用 connect()。就会有一次调用startresolutionforresult()返回相同的结果并创建有一个账户选择对话框展现在已存在的对话框前面。
这个布尔值会有效的在activity切换时被保存起来,下一节将做进一步解释。
maintainstate while resolving an error解决错误并维护状态
为了避免之前尝试解决错误时又执行 onconnectionfailed()中的代码,你需要保留一个布尔变量来跟踪你的应用当前是否在解决这个问题。
上面的代码示例,你应该在每次调用 startresolutionforresult()或者从googleplayservicesutil.geterrordialog()得到一个显示的对话框都要设置一个布尔值为true.知道你在onactivityresult()方法中接收到处理结果为 result_ok 时再次将布尔值设置为false.
为保持布尔值在acticity重启时不会变化,应该将布尔值保存在onsaveinstancestate():中
private static final string state_resolving_error = resolving_error;
@override
protected void onsaveinstancestate(bundle outstate){
    super.onsaveinstancestate(outstate);
    outstate.putboolean(state_resolving_error, mresolvingerror);
}
然后在oncreat()中恢复保存的状态:
@override
protected void oncreate(bundle savedinstancestate){
    super.oncreate(savedinstancestate);
...
    mresolvingerror = savedinstancestate != null
            && savedinstancestate.getboolean(state_resolving_error,false);
}
现在你可以安全的运行你的应用并连接到googleplayservice.如何使用 googleapiclient去执行读取和写入请求 google play services,下一节讨论:
accessthe wearable api(方位穿戴api)在没有安装android wear app的设备上,连接请求包含 wearable api 会发生错误,错误码为api_unavailable。如果你的应用除了访问其他的google apis 还要访问wearable api ,使用一个单独的googleapiclient实例去访问wearable api。这个方法使您在不用搭配穿戴设备上能够访问其他的google apis。
当你使用单独的googleapiclient 实例仅仅去访问wearable api,你要确定android wear app在设备上是否已经安装。
// connection failed listener method for a client thatonly
// requestsaccess to the wearable api
@override
public void onconnectionfailed(connectionresult result){
    if (result.geterrorcode()==connectionresult.api_unavailable){
        // the android wear app is not installed
    }
    ...
}
communicate with google services与谷歌服务通信
一旦连接,你的客户端就能使用特定的服务apis为你的应用授权读写调用。按照特定的api和范围你添加你的 googleapiclient实例。
注意:之前调用特定的谷歌服务,你可能首先需要在谷歌开发者控制台注册你的app.特定的说明请参考适合你所用的api入门指南。诸如:google drive or google+
当你使用google api client,执行读写请求的时候,他立即作为一个pendingresult 对象返回。这是一个表示请求的对象,他还没有交付给谷歌服务。
例如:这是一个从 google drive请求读取文件提供的pendingresult 对象,
query query = new query.builder()
        .addfilter(filters.eq(searchablefield.title, filename));
pendingresult result = drive.driveapi.query(mgoogleapiclient, query);
一旦你有了这个 pendingresult,你可以继续使用同步或者异步请求。
usingasynchronous calls 使用异步调用为了使用异步请求,pendingresult需要调用 setresultcallback()并提供一个实现resultcallback接口的实现类。例如,这是执行异步请求:
private void loadfile(string filename){
    // create aquery for a specific filename in drive.
    query query =newquery.builder()
            .addfilter(filters.eq(searchablefield.title, filename))
            .build();
    // invokethe query asynchronously with a callback method
    drive.driveapi.query(mgoogleapiclient, query)
            .setresultcallback(newresultcallbackdriveapi.metadatabufferresult>(){
        @override
        public void onresult(driveapi.metadatabufferresult result) {
            // success! handle the query result.
            ...
        }
    });
}
当你的应用在 onresult()方法中收到一个result对象时,他将按照你使用的api交付相应子类的实例,比如:driveapi.metadatabufferresult.
usingsynchronous calls 使用同步调用如果你想要你的代码按照你严格定义的顺序运行,或许因为一个调用的结果是另一个需要的参数,你可以使用 pendingresult.的 await()方法进行同步请求。这个阻塞线程会交付一个你使用api的子类实例直到请求完成后返回结果。如:metadatabufferresult
因为调用await()会阻塞线程知道结果返回,重点是你永远不要在你的ui线程中调用执行。所以你想执行同步请求googleplayservices,你应该创建一个新的线程,比如使用asynctask执行这个请求。例如:这里是如何使用同步请求googlepalyservice访问相同的文件。
private void loadfile(string filename){
    new getfiletask().execute(filename);
}
private classgetfiletaskextendsasynctaskstring,void,void>{
    protected void doinbackground(string filename){
        query query = new query.builder()
                .addfilter(filters.eq(searchablefield.title, filename))
                .build();
        // invoke the query synchronously
        driveapi.metadatabufferresult result=
                drive.driveapi.query(mgoogleapiclient, query).await();
// continue doing other stuff synchronously
        ...
    }
}
小提示:你也可以队列阅读请求而不用连接 google play services.。例如:不管google api client是否连接,执行一个方法从google drive读取文件,然后一旦确立了连接,就会执行读取请求并接收结果。然而,当你的google api client 没有连接的时候如果你调用他们进行写入请求将会发生错误。
其它类似信息

推荐信息