itslonua
7/1/2016 - 1:19 PM

IntentService PrivatBank Exchange Api

IntentService PrivatBank Exchange Api

package com.example.architector.realmrest;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BankingService extends IntentService {

    private static final String API_URL = "https://api.privatbank.ua/p24api/";

    private static final String ACTION_GET_CURRENCY = "action.ACTION_GET_CURRENCY";
    private static final String EXTRA_CURRENCY_ID = "extra.EXTRA_CURRENCY_ID";

    private BankingApi mRestService;
    private Realm mRealm;

    public BankingService() {
        super("BankingService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_URL)
                .build();

        mRestService = retrofit.create(BankingApi.class);
        mRealm = Realm.getDefaultInstance();
    }

    public static void getCurrentCurrencyRates(Context context, int currencyId) {
        Intent intent = new Intent(context, BankingService.class);
        intent.setAction(ACTION_GET_CURRENCY);
        intent.putExtra(EXTRA_CURRENCY_ID, currencyId);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_GET_CURRENCY.equals(action)) {
                final int currencyId = intent.getIntExtra(EXTRA_CURRENCY_ID, 0);
                actionGetCurrency(currencyId);
            }
        }
    }

    private void actionGetCurrency(int currencyId) {
        Call<Currency> currencyRates = mRestService.getUsdRates(currencyId);
        currencyRates.enqueue(new Callback<Currency>() {
            @Override
            public void onResponse(Call<Currency> call, Response<Currency> response) {
                if (response.isSuccessful())
                    saveData(response);
            }

            @Override
            public void onFailure(Call<Currency> call, Throwable t) {
                // Log error here
            }
        });
    }

    private void saveData(Response<Currency> response) {
        try {
            mRealm.beginTransaction();
            mRealm.copyToRealmOrUpdate(response.body());
            mRealm.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mRealm.close();
    }
}