3

should i put my retrofit calls inside and Android Service class? for my application iam calling retrofit inside in some classes for example like below

 Call<ArrayList<CantItem>> mycall = retrofitcalls.getCanteenItems("url.php", urldatamap);
        mycall.enqueue(new Callback<ArrayList<CantItem>>() {
            @Override
            public void onResponse(Response<ArrayList<CantItem>> response, Retrofit retrofit) {

                int code = response.code();
                Log.d("code ", String.valueOf(code));

                if (code == 200 || code == 201) {
                    ArrayList<CantItem> cantitems = response.body();
                    Log.d("retrieved", "returned items");

                    savedToSharedPrefs(createString(cantitems));
                    cantmap = createMap(cantitems);
                    presenter.updateView(cantmap);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("couldnt retrieve", "failure");
            }
        });

I was wondering should i put this call inside an Android Service class? as my retrofit call runs asynchronously anyway? Every tutorial ive seen seems to run it in either classes or activities. I haven't seen anyone using a service. Im not 100% sure what the best approach is at present. thanks

filthy_wizard
  • 740
  • 11
  • 25

1 Answers1

8

It really depends on your requirements. Do you need the result of the webservice call even if your application killed?

If yes, then put it into a service.

If not then just starts something from your Activity.

jbarat
  • 2,382
  • 21
  • 23
  • I have also tried to put it inside a service but when my app closes so does my service. Can you please tell me what is happening wrong ?? Also if you think that services do not get destroyed when app is closed then what extra code you have wrote to do that ?? – Sudhanshu Gaur Jul 20 '17 at 22:01
  • This StackOverflow question answers your question: https://stackoverflow.com/questions/16651009/android-service-stops-when-app-is-closed – jbarat Jul 21 '17 at 09:01