I’m trying to work with Google Drive API in my Android app but I want to keep things clean. My question is whether I can handle the Google Drive connection stuff without making a separate activity just for that purpose.
Right now I have a background helper class that needs to fetch files from Google Drive. This class isn’t an actual Android Service, it’s just a regular class that handles data loading. The problem is that most examples I see online show you need to override onActivityResult method to deal with authentication callbacks.
public class DataManager {
public void fetchCloudFiles() {
// Need to authenticate with Google Drive here
// But how to handle auth callback without activity?
}
// This is what examples show but I can't use it in my helper class
// protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// // Handle authentication result
// }
}
If I can get access to the main Activity from my helper class, is there a way to make Google Drive authentication work without mixing all that auth code into my main activity? I want to keep the Drive integration separate and clean.
you could also use accountmanager w/ a predefined google account. skip the activity result headache by grabbing an auth token straight from the user’s existing google account on their device. just ask for get_accounts perm and call accountmanager.getauthtoken() in your datamanager class. perfect for background stuff - no ui interruptions.
Skip the activity callbacks and use GoogleSignInClient with a service account instead. Set up OAuth2 credentials in Google Cloud Console, then use GoogleCredentials.fromStream() with your service account key file. This way you don’t need onActivityResult at all - everything happens programmatically. Just initialize your Drive service with these credentials directly in your DataManager constructor. I used this approach for a document sync feature and it ran perfectly in the background. Store your service account JSON in assets and load it at runtime. Don’t forget to enable the Drive API in your Google Cloud project and give the service account the right scopes.
You can definitely implement a callback pattern within your DataManager class. By passing the instance of your activity to DataManager, you can separate the authentication logic from the activity itself. Create an authentication interface in DataManager that your main activity will implement. When authentication is required, invoke a method on that interface, allowing your activity to manage Google sign-in. Once you have the results, send them back through another callback. This method keeps your main activity clean while ensuring all Drive-related functionality is encapsulated within DataManager. This approach has worked well for me in several projects; it allows for clear separation of concerns. Just remember to manage references carefully to avoid memory leaks.