How to resolve NetworkOnMainThreadException when working with Google Drive API on Android

I’m encountering a NetworkOnMainThreadException while trying to implement the Google Drive API in my Android application. My application functions smoothly on Android version 2.3.3, but it crashes on version 4.1.1. The issue seems to occur when I attempt to acquire the token response from Google’s API.

Below is the problematic code snippet:

String tokenCode = data.getStringExtra("token_code");
GoogleTokenResponse tokenResponse;
try {
    tokenResponse = driveFlow.newTokenRequest(tokenCode).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credentials = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
        .build()
        .setFromTokenResponse(tokenResponse);
    
    driveService = new Drive.Builder(httpTransport, jsonFactory, credentials).build();
} catch (IOException e) {
    e.printStackTrace();
}

The exception occurs during the execution of the method. Once I catch the NetworkOnMainThreadException, my driveService becomes null. I’ve ensured that the internet permission is granted in my manifest. Any suggestions on how to resolve this issue? Do I need to run the network call on a separate thread?

The NetworkOnMainThreadException is a protective measure enforced by Android since API level 11, preventing potential UI freezes caused by long-running network operations on the main thread. To resolve this, move your API call to a background thread. You can achieve this easily with AsyncTask. Place your token request logic in the doInBackground method and process the response in onPostExecute. Alternatively, consider using a Thread or ExecutorService to handle threading, ensuring that you update your UI components only from the main thread after the background operation is complete.

Hit this same issue migrating an old app to newer API levels. Android started blocking network calls on the main thread from API 11 onwards - that’s why it works fine on 2.3.3 but crashes on newer versions. Skip AsyncTask if you don’t want the complexity. Just spin up a background thread for the Google Drive token request, then use a Handler to push results back to the UI thread. Watch out for exceptions though - they won’t bubble up to your main handlers from background threads, so catch them there. This way you keep most of your existing code and satisfy Android’s threading rules.

same thing happened 2 me! android 4.0+ won’t let u make network calls on the main thread. just wrap your code in new Thread(() -> { your code here }).start() - but dont forget to use runOnUiThread() if u need to update any UI elements after.