Run long task when onDestroy() is called

796 Views Asked by At

I want to run a long operation task from onDestroy() from a fragment. My goal is to call a network call to delete some data in case the user closes the application by swiping it from recent apps. I wish to start an intent when onDestroy() is called.

At the moment, whenever i try to initiate the intent, i loose the context before i get a chance to operate the call since onDestroy() already killed my application.

I don't want to use this option : Performing long running operation in onDestroy since running a thread like so isn't the right way of doing it, and seems like a dangerous hack.

Calling the operation from onDestroy() of the activity resulted with the same error.

Offcourse, i wouldn't want any work on the ui thread and "postponing" the onDestroy() until my operation is done.

Just for clearance, while getContext() isn't null, by the time i reach SomeService class, the context is already null since sending an intent is an asynchronous operation.

@Override
    public void onDestroy() {
         Intent intent = new Intent(getContext(), SomeService.class);
         getContext().startService(intent);
         super.onDestroy();
    }
2

There are 2 best solutions below

0
On

I'd advise to start and bind service during say onCreate() of your Activity and then having bound service you can easily start cleanup utility placed in your Service, i.e. you should divide service starting and starting of cleanup.

Like:

//somewhere in onCreate()
myServiceIntent = new Intent(this.getApplicationContext(), MyService.class);
context.startService(myServiceIntent);
context.bindService(myServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

and then in onDestroy()

public void onDestroy() {
     myService.cleanup();
     super.onDestroy();
}

Read more about service binding

0
On

Be aware onDestroy() is not guaranteed to be called.

Use application context.

Bound service will live as long as any component is bound to it, so your variant with started service is better, just don't forget to use stopSelf() after a job is completed.