Get OAuth 2.0 access token using Retrofit 2.x

Retrofit is an awesome and easy to use library. You can use Retrofit for any Android or Java application which need to interact with our OAuth2.0 server to get access token.

You just need to build the retrofit properly to get it done. It doesn’t require any advance knowledge. Let’s see how it can be done easily.

To get the access token using Retrofit we need to do –

Add Retrofit in your project via Maven or Gradle. Complete installation guide can be found here.

Now let’s create the Retrofit builder. And before doing that we need to create a service interface.

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface AccessTokenServiceInterface {

    Call<TokenResponse> getToken(@Field("client_id") String client_id, @Field("client_secret") String client_secret, @Field("scope") String scope, @Field("grant_type") String grant_type);

And now the builder.

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class Http {
    public static void main(String[] args) {
        Retrofit retrofit = new Retrofit.Builder()

        AccessTokenServiceInterface service = retrofit.create(AccessTokenServiceInterface.class);

        //grant types = client_credentials
        Call<TokenResponse> call = service.getToken("OAUTH CLIENT ID", "OAUTH CLIENT SECRET", "basic email", "client_credentials");
        try {
            Response<TokenResponse> response = call.execute();
        } catch (IOException e) {

And also we need to map the JSON response from our OAuth 2.0 server. So we need a model to map that. Let’s create model class


public class TokenResponse {

    private String tokenType;
    private Integer expiresIn;
    private String accessToken;

    public String getTokenType() {
        return tokenType;

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;

    public Integer getExpiresIn() {
        return expiresIn;

    public void setExpiresIn(Integer expiresIn) {
        this.expiresIn = expiresIn;

    public String getAccessToken() {
        return accessToken;

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;


Now run Http.main and you will get your access token.

That’s it. Now run the Http.main and you will get the access token easily. Download these scripts from our PreviewTechnologies/access-token-retrofit GitHub repository.

This article also available on our support portal.

Android – Get current location of user by using LocationManager API

Sometimes we need to get user current location from Android device. Its very simple while we use LocationManager API of Android. We just need a custom location manager and a location listener with  necessary permission in Manifest.xml file.  lets see how to do it.

Step-1: Follow the code in manifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature android:name="android.hardware.location.gps" />

        <activity android:name=".MainActivity" />

            android:value="@integer/google_play_services_version" />

        <activity android:name=".HomeActivity">
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

Step-2: Follow these code for TestLocationManager.Java

public class TestLocationManager {

private int minDistanceForUpdateLocation;
private int minTimeForUpdateLocastion;
LocationManager locationManager;
TestLocationListener locationListener;
Context ctx;
private boolean isGPSProviderEnable, isNetworkProviderEnable;

public TestLocationManager(Context ctx){
this.ctx = ctx;

public TestLocationManager(Context ctx, int minTimeForUpdateLocastion, int minDistanceForUpdateLocation ){
this.minDistanceForUpdateLocation =minDistanceForUpdateLocation;
this.minTimeForUpdateLocastion= minTimeForUpdateLocastion;
this.ctx = ctx;

//Set Location Manager and Listener
public void setLocationManagerAndListener(){
this.locationListener = new TestSendLocationListener(this.ctx);
this.locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);

isGPSProviderEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkProviderEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTimeForUpdateLocastion, minDistanceForUpdateLocation, locationListener);
}else if(isNetworkProviderEnable){
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTimeForUpdateLocastion, minDistanceForUpdateLocation, locationListener);


//Get Minimum Distance for updating location
public int getMinDistanceForUpdateLocation() {
return minDistanceForUpdateLocation;
//Set Minimum Distance for updating location
public void setMinDistanceForUpdateLocation(int minDistanceForUpdateLocation) {
this.minDistanceForUpdateLocation = minDistanceForUpdateLocation;

//Get Minimum Time for updating location
public int getMinTimeForUpdateLocastion() {
return minTimeForUpdateLocastion;

//Set Minimum Time for updating location
public void setMinTimeForUpdateLocastion(int minTimeForUpdateLocastion) {
this.minTimeForUpdateLocastion = minTimeForUpdateLocastion;

Step:3- Follow these code for

public class TestLocationListener implements LocationListener {

private double lat, lng, alt, acc, time;
Context ctx;
ConnectivityDetector connectivityDetector;

public TestLocationListener(Context ctx){
this.ctx = ctx;

public void onLocationChanged(Location location) { = location.getLatitude();
this.lng = location.getLongitude();
this.alt = location.getAltitude();
this.acc = location.getAccuracy();
this.time = location.getTime();

Toast.makeText(ctx, “Lat : “” \n Lng : “+this.lng+” \nAlt : “+this.alt+” \n Acc : “+this.acc+” \n Time : “+this.time, Toast.LENGTH_LONG).show();

//to whatever you want with location


public void onStatusChanged(String provider, int status, Bundle extras) {


public void onProviderEnabled(String provider) {


public void onProviderDisabled(String provider) {


Step:4 – There is the code for . where we will implement our TesetLocationManager and TestLocationListener .

public class MainActivity extends AppCompatActivity{

    private Toolbar toolbar;
    private Location mLastLocation;

    protected void onCreate(Bundle savedInstanceState) {

 // setup toolbar
 toolbar = (Toolbar) findViewById(;

 navigationView = (NavigationView) findViewById(;
 //Set default item selected on nivigation
 navigationView.getMenu().performIdentifierAction(, 0);

 //get real time permission for location

 protected void onStart() {

 protected void onStop() {

 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 super.onRequestPermissionsResult(requestCode, permissions, grantResults);
 switch (requestCode) {
 // If request is cancelled, the result arrays are empty.
 if (grantResults.length > 0
 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();

 //setup location manager and listener

 //get last known location
 //mLastLocation = getUserLocation();

 } else {
 Toast.makeText(getApplicationContext(), "Permission denied! You must have to allow this permission", Toast.LENGTH_LONG).show();

 //Check Permission and get call log list
 private void getPermissionForLocation() {
 // Here, thisActivity is the current activity
 if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
 && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
 != PackageManager.PERMISSION_GRANTED) {

 // Should we show an explanation?
 if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
 Manifest.permission.ACCESS_COARSE_LOCATION) ||
 Manifest.permission.ACCESS_FINE_LOCATION)) {

 // Show an expanation to the user *asynchronously* -- don't block
 // this thread waiting for the user's response! After the user
 // sees the explanation, try again to request the permission.

 new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},

 } else {
 // No explanation needed, we can request the permission.
 new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},

 } else {
 //Check permission for location

 //setup location location manager and listener
 private void setupLocationManagerAndListener(){
 TestLocationManager locationManager = new TestLocationManager(MainActivity.this, 10000, 10);
 TestLocationListener locationListener = new TestLocationListener(getApplicationContext());


We can find our expected location on onLocationChanged() method of file. So i think you got your expected result. If you have any question then put it on comment box. Thanks.