1

I have obtained images from the camera and want to save it to a directory after some processing which takes about 10 seconds. I tried the following methods :

1) Asynctask(Problem : if the user closes(swipes) the app, the asyncTask is killed)

2) Intent Service(Problem : same as Asynctask)

3) Foreground Service(Problem : Hangs the UI of the application)

4) Running on UI Thread(Problem : Hangs the application).

So my question is what should I use to save my images(with some processing) such that all tasks are done even if app is closed and the UI does not hang(freeze).

Any help would be appreciated.

Siddharth Sharma
  • 310
  • 1
  • 2
  • 11

2 Answers2

2

You cannot prevent Android from killing your process. If the user wants it killed (for example, using "force stop"), it will get killed. There is nothing you can do to prevent that.

When the user swipes the task from the recent tasks list, the behaviour is different in different versions of Android (and also different manufacturers have different behavour). However, in most cases, the OS Process hosting your app (including any services) is simply killed. If the app had a running Service that wants to be restarted, Android will create a new OS Process and reinstantiate the Service and restart it.

You can mitigate this a bit by putting your Service in a separate OS process. To do this, add android:process=":remote" to the <service> declaration. On some versions of Android, swiping the task from the recent tasks list will then kill the OS process hosting your activities, but NOT kill the OS process hosting your Service.

In any case you need to make your app robust so that it can handle being killed and restarted.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Thanks for helping but I needed the service to continue even if the app was swapped(doing it for force stop would probably have been difficult) – Siddharth Sharma Dec 08 '16 at 15:47
0

Thanks everyone for suggestions. How I finally was able to achieve this was using a foreground service which itself created and asynctask to perform the work in the background. I am a novice so don't exactly know how it's working, but it doesn't cause any app freezing/lag and does the work even if the app is swiped from the recent tasks list. (tested in Android L(5.1.1) and M)

Siddharth Sharma
  • 310
  • 1
  • 2
  • 11