Encountering 400 Error with Google Drive API in Android Application

My Android app intended for uploading text files to Google Drive consistently returns a 400 error (‘keyInvalid’). Below is an updated code example implementing the Drive API.

public class DriveUploadActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AccountManager manager = AccountManager.get(this);
        Account[] userAccounts = manager.getAccounts();
        // Using the first available account for demonstration
        manager.getAuthToken(userAccounts[0], "oauth2:drive", null, true, new TokenCallback(), null);
    }

    private class TokenCallback implements AccountManagerCallback<Bundle> {
        @Override
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                // Simulated Drive service initialization with retrieved token
                Log.i("DriveUpload", "Token acquired: " + token);
                // Further file upload logic would be implemented here
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.driveupload"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application android:label="DriveUploadApp">
        <activity
            android:name=".DriveUploadActivity"
            android:label="DriveUploadActivity"
            android:exported="true">
            <meta-data
                android:name="com.google.android.apps.drive.APP_ID"
                android:value="id=ABCDEFGHIJK" />
            <intent-filter>
                <action android:name="com.google.android.apps.drive.action.OPEN" />
                <data android:mimeType="application/octet-stream" />
            </intent-filter>
        </activity>
    </application>

</manifest>

It appears that the error might be related to the way the API key or the credentials are set up rather than issues within the token retrieval code itself. In my experience, rechecking the configuration in the Google Developers Console is essential. Issues can arise if the package name or the SHA-1 fingerprint does not match what is specified on the console. Additionally, ensure that the correct scopes and permissions are set. Debugging by logging the full response might also provide further insight into the exact cause.