【问题标题】:Inactivity, disconnecting from the service - using GoogleApiClient in Service不活动,与服务断开连接 - 在服务中使用 GoogleApiClient
【发布时间】: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 我觉得问题不在于GoogleApiClientService 不会等到 GoogleApiClient 连接并被销毁。那么我们如何确保服务在调用onConnected() 函数之前一直保持活动状态呢?

标签: android android-service google-api-client google-drive-android-api appdata


【解决方案1】:

使用这个JobService

首先你需要创建一个启动服务来运行主服务

@TargetApi( Build.VERSION_CODES.LOLLIPOP )
public class BootService extends JobService {

@Override
public void onCreate() {
    super.onCreate();

    new Handler().postDelayed(() -> {
        if ( PreferenceManager.getToken(BootService.this) != null && !PreferenceManager.isNeedProvideInfo(this)) {
            startService(new Intent(BootService.this, MainService.class));
        }
    }, 1000);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // service On start
    return START_STICKY;

  ...
 }

}

主要的服务应该是这样的

public class MainService extends JobIntentService {

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2018-02-15
    • 1970-01-01
    • 2010-12-07
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    相关资源
    最近更新 更多