1

I need when my app completely close (clear from backgrond) post my request to server and when got response service stop from working , this is my Service class :

public class OnClearFromRecentService extends Service {

    private SharedPreferences prefs;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ClearFromRecentService", "Service Started");

        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Log.d("ClearFromRecentService", "Service Destroyed");

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {

        Log.e("ClearFromRecentService", "END");

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(App.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        String authorization = prefs.getString("token_type","")+" "+prefs.getString("access_token","");

        Call<JsonArray> response = requestInterface.AppOff(ChatList.offline_user,authorization);

        response.enqueue(new Callback<JsonArray>() {
            @Override
            public void onResponse(Call<JsonArray> call, retrofit2.Response<JsonArray> response) {

                String asd = "asd";



                stopSelf();
            }

            @Override
            public void onFailure(Call<JsonArray> call, Throwable t) {

                Log.d(t.getLocalizedMessage(),"failed");

                stopSelf();

            }
        });


    }

definition in manifest :

 <service android:name="com.iranMobleh.OnClearFromRecentService" android:stopWithTask="false" />

and start service from MainActivity like below:

 startService(new Intent(this, OnClearFromRecentService.class));

seem this code true but problem is when app closed it can't wait for retrofit response

Mosius
  • 1,602
  • 23
  • 32
Erfan
  • 3,059
  • 3
  • 22
  • 49

3 Answers3

3

First of all if you set android:stopWithTask="false" then onTaskRemoved will not be called. So set it to android:stopWithTask="true". See Service Documentation.

Now we move to the solution. You have to put your webservice call into a new Service/Job. and start that service/job by an AlarmManager, or WorkManager or EvernoteJobs or JobScheduler when onTaskRemoved is called.

Instead of writing same thing again. I found two good answer perfectly fit for you requirement. This & This.

Just one change in above answers. I think EvernoteJobs or WorkManager would be better than AlarmManager.

It is easy to implement.

public class DemoSyncJob extends Job {

    public static final String TAG = "job_demo_tag";

    @Override
    @NonNull
    protected Result onRunJob(Params params) {
        // run api call here
        return Result.SUCCESS;
    }

   public static void runJobImmediately() {
    int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
            .startNow()
            .build()
            .schedule();
    }
}

Visit Evernote-jobs page for integrating.

Update

You have to make your project compatible with library. Here is the versions that library uses. So make sure you are using minimum these versions.

ext {
    compileSdkVersion = 26
    targetSdkVersion = compileSdkVersion
    minSdkVersion = 14

    buildToolsVersion = '27.0.3'

    supportLibVersion = '26.1.0'
}
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • how can i download this ? cause i try so many time and sees have trouble with download library , are you test it before ? or just give me explain ? – Erfan Aug 13 '18 at 07:50
  • You seem new to Android, bro, you don't need to download it. – Khemraj Sharma Aug 13 '18 at 07:51
  • You simply add `implementation 'com.evernote:android-job:1.2.6'` to your `build.gradle` & Sync project. by adding like dependency, your project will add itautomatically. – Khemraj Sharma Aug 13 '18 at 07:51
0

Use WorkManager to run a worker class in the background.

Or use Evernote's android-job.

Link for evernote android-job library: https://github.com/evernote/android-job

This Guy Codes
  • 125
  • 1
  • 4
0

Better can u try with onDestroy method in the service class, because if the app is force closed then onTaskRemoved method not called for sometimes so I recommend to go with onDestroy method in service class and also,

you can use Intent Service for achieving your Goal, use that service in onDestroy()

you can have a look at following example.

http://stacktips.com/tutorials/android/creating-a-background-service-in-android