1

I have written an VPN using android's VPNService and it works perfectly. When I run it, it creates a foreground service and sends all traffic through my VPN server. It also has an internal reconnecting mechanism to reconnects VPN server if it disconnects for any reason without stopping service itself.

I like to have this VPN service working all the time. But my problem is that this VPN service is stopped occasionally after a completely random period(sometime it takes just 10 minutes, but other times it works for 2-3 days before stopping).

Since the stopping time is completely random and I cannot find any place in code that creates this situation (I have been debugging for weeks), I thought maybe android OS itself stops my VPNService for some reason. I wonder if there is a way to detect if system has stopped my service from outside or not. Any idea?

Afshin
  • 8,839
  • 1
  • 18
  • 53

1 Answers1

0

Unfortunately, Android OS still can terminate the service in low memory and possibly other situations, even if it's a background running service !

It is not only Android, but all Mobile Operating Systems optimize RAM usage by killing background apps.

This is done so that the foreground app can be given top priority. It ensures smooth functioning of the current app and reduces load on the system.

There's are two approaches as mentioned in this post: Background Service getting killed in android

  • If you are implementing the service, override onStartCommand() and return START_STICKY as the result. It will tell the system that even if it will want to kill your service due to low memory, it should re-create it as soon as memory will be back to normal.
  • If you are not sure 1st approach will work - you'll have to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html . That is a system service, which will execute actions when you'll tell, for example periodically. That will ensure that if your service will be terminated, or even the whole process will die(for example with force close) - it will be 100% restarted by AlarmManager.

I had this issue previously and I've solved it by creating the service running forever even if it's killed manually or from the system it recreates itself.

Community
  • 1
  • 1
Jamal Alkelani
  • 606
  • 7
  • 19
  • as I mentioned in my post, I have already foregrounded my service and it already returning `START_STICKY`. for `AlaramManager`, I'm not sure if I can use it for `VPNService` because it is somehow a special service. So my main question is how I can find out that Service is killed my system for any reason(for example lack of memory). – Afshin Dec 04 '19 at 10:09