Android giving IOException with 'unable to cre

2020-07-30 03:14发布

问题:

Trying to implement the Calendar Quickstart API into Android but when I declare tokens as demonstrated. private final String TOKENS_DIRECTORY_PATH = "tokens";

That String is then used in the builder

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();

But Android returns this error when setting the DataStoreFactory

java.io.IOException: unable to create directory: /tokens

Is there a different method to creating a directory that will work? or must I change the file path of TOKENS_DIRECTORY_PATH?

回答1:

I used this piece of code.

File tokenFolder = new File(Environment.getExternalStorageDirectory() +
            File.separator + TOKENS_DIRECTORY_PATH);
    if (!tokenFolder.exists()) {
        tokenFolder.mkdirs();
    }

    flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(tokenFolder))
            .setAccessType("offline")
            .build();

And get permissions to external storage in Android manifest file

EDIT: The methods specified in Google API documentation for Java doesn't seem to work well for Android. Use this github project as a guide for implementing integrating Google APIs into Android applications.