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>