BlackCursor
BlackCursor

Reputation: 1492

Inactivity, disconnecting from the service - using GoogleApiClient in Service

I am creating a service to upload files to Google Drive App Data Folder using Google Drive Android API.

I initialized the GoogleApiClient in the onCreate() method of the service. Then, I have written the code to upload the file to Google Drive in the overridden onConnected() method of the `GoogleApiClient'.

The problem I am facing is that, when I start the Service, The onCreate() method gets called. In this method, the GoogleApiClient object is initialized and the connect() function is called. Afterwards, before the onConnect() is called (when GoogleApiClient is connected successfully), the following message is shown in the log

"Inactivity, disconnecting from the service"

So, the onConnect() method is never called and my file upload code is never executed. Please find the code snippet below. Any suggestions would be helpful.

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..

}

Upvotes: 1

Views: 7980

Answers (1)

younes
younes

Reputation: 832

use this JobService and

First you need to create a boot Service that runs the main service

@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;

  ...
 }

}

The main service should be this way

public class MainService extends JobIntentService {

Upvotes: 0

Related Questions