【发布时间】:2017-01-27 22:13:07
【问题描述】:
我正在创建一个使用 Google Drive Android API 将文件上传到 Google Drive App Data Folder 的服务。
我在服务的onCreate() 方法中初始化了GoogleApiClient。然后,我在“GoogleApiClient”的覆盖onConnected() 方法中编写了将文件上传到Google Drive 的代码。
我面临的问题是,当我启动 Service 时,onCreate() 方法被调用。在这个方法中,GoogleApiClient 对象被初始化,connect() 函数被调用。之后,在调用onConnect() 之前(当GoogleApiClient 连接成功时),日志中显示以下消息
“不活动,与服务断开连接”
因此,永远不会调用 onConnect() 方法,并且永远不会执行我的文件上传代码。请在下面找到代码 sn-p。任何建议都会有所帮助。
public class GDriveFileUploadService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private static final String TAG = GDriveFileUploadService.class.getSimpleName();
GoogleApiClient mGoogleApiClient;
public GDriveFileUploadService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"Initializing GoogleApiClient..");
this.mGoogleApiClient = new GoogleApiClient.Builder(GDriveFileUploadService.this)
.addApi(Auth.GOOGLE_SIGN_IN_API, GoogleSignInOptions.DEFAULT_SIGN_IN)
.build();
this.mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.d(TAG,"GoogleApiClient connected in service");
//Code to upload file to Google Drive
}
//Other functions..
}
【问题讨论】:
-
您可能需要查看Authorizing Android Apps 上的文档并了解如何重新连接 GoogleApiClient。
-
同时检查 GoogleApiClient 公共方法,如 reconnect()、connect ()、disconnect (),以帮助您管理恢复连接 GoogleApiClient。
-
@Mr.Rebot 我觉得问题不在于
GoogleApiClient。Service不会等到GoogleApiClient连接并被销毁。那么我们如何确保服务在调用onConnected()函数之前一直保持活动状态呢?
标签: android android-service google-api-client google-drive-android-api appdata