0

I want to clear my app from background Service class if a certain scenario is encountered. How to call finishAffinity() from Service class? Any help will be greatly appreciated.

Jas
  • 3,207
  • 2
  • 15
  • 45
  • you cannot, just use a bound service pattern and send a callback to your activity so that it can finish by itself – pskink Jun 22 '16 at 12:31
  • My requirement is that I want to quit my application if it stays in background for 5 minutes. So I wrote a Service class with timer task. In my timer task, I check whether app is in foreground or background and it is working properly. So if my app is in background for 5 minutes, I want to quit the app. Is it possible to do this? – Jas Jun 22 '16 at 12:36
  • quit app f it stays in background? what for? if it is in background, who cares if it is physically killed or not? – pskink Jun 22 '16 at 12:40
  • Mine is an augmented reality app. So it consumes lot of memory and battery power and I want to do some optimization. That's why – Jas Jun 22 '16 at 12:42
  • memory is not an issue, battery power? so it seems you are not finishing some background jobs in `onPause` / `onStop` / `onDestroy` – pskink Jun 22 '16 at 12:45
  • I will check that. But meanwhile can u please help me with this issue? – Jas Jun 22 '16 at 12:51

3 Answers3

1

Make method in your activity to finish itself using interface like below:

Calling activity class method from Service class

And then add below code to finish all your activities in that activity method:

ActivityCompat.finishAffinity(this);
Community
  • 1
  • 1
Er. Kaushik Kajavadara
  • 1,657
  • 2
  • 16
  • 37
0

The easy way is to cast context to Activity here is a sample for Kotlin API 16+

val activity = context as Activity
finishAffinity(activity)

Java API 16+

Activity activity = (Activity) context; 
finishAffinity(activity);
DarkPh03n1X
  • 600
  • 1
  • 7
  • 17
0

Convert context to activity like this: (Activity)context then yon can call finishAffinity like this : ((Activity)context).finishAffinity();

Ghazal
  • 123
  • 2
  • 9