Implementing Google Drive in Android without dedicated Activity

Hey everyone, I’m working on an Android app and I want to add Google Drive functionality. But here’s the thing: I don’t want to create a separate activity just for this. Is there a way to use Google Drive with my existing app structure?

I’ve got this background class that handles data loading from Google Drive. It’s not an Android service, just a regular class that doesn’t deal with UI stuff. The problem is, all the examples I’ve seen for Google Drive integration use onActivityResult to handle authentication.

So I’m wondering:

  1. Can I somehow get the authentication info without making my class an activity?
  2. If I can get a reference to the current Activity, is it possible to set up Google Drive integration in a way that doesn’t mess with my existing code?

Any tips or tricks would be super helpful! Thanks in advance!

I’ve implemented Google Drive integration in a similar way before. One approach that worked well was using a callback mechanism. In my case, I defined an interface in the background class with methods for authentication success and failure. Then, the main activity implemented this interface so it could handle UI-related tasks when authentication was completed. This approach kept the GoogleSignInClient logic within the background class decoupled from the UI, while still allowing the activity to respond appropriately. In addition, it’s important to handle any exceptions or edge cases that might arise during authentication.

I’ve tackled this issue in a recent project. One approach that worked well was using a singleton pattern for Google Drive integration. Create a DriveManager class that handles all Drive operations, including authentication. This class can hold a WeakReference to the current Activity, which you update whenever your main Activity resumes.

For authentication, use the GoogleSignInClient as others suggested, but initialize it in your Application class. This way, you can access it from anywhere in your app. When you need to authenticate, use the activity reference in your DriveManager to start the intent.

Remember to handle token expiration and refresh scenarios. Also, consider using coroutines for background operations if you’re working with Kotlin. This setup kept my code clean and avoided creating a separate activity just for Drive functionality.

hey mate, i’ve done smth similar before. u can use GoogleSignInClient for auth without an activity. just pass the context to ur background class and use startIntentSenderForResult() from there. it’ll handle the auth flow without messin with ur existing structure. good luck!