How to get offline token and refresh token and auto-refresh access to Google API

To get the refresh token you have to set both accessType = "offline" and approvalPrompt = "force".

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT,
            JSON_FACTORY,
            CLIENT_ID,
            CLIENT_SECRET,  
            SCOPE)
.setAccessType("offline")
.setApprovalPrompt("force")
.build();

One thing you should be careful about: a refresh token is returned (in addition to the access token) only when the user gives consent explicitly for the requested scopes. Basically, when the approval page is shown. All subsequent flows will only return an access token.

Now, in order to test your application and make sure you receive the refresh token the first time around, you could use the approval_prompt=force parameter (builder.setApprovalPrompt("force")) to make sure the approval page is shown in the flow and you obtain explicit consent from the user. After you sort out any issues and make sure the refresh tokens are stored properly, you can remove that flag (the default is auto)

More information is also available in the offline access section in the developer guide.