1

I have a singleton class with the "block/allow logic" for my VPN tunnel. Packets sent into the tunnel are not emitted, applications are allowed to bypass based on an allowance list, therefore it can behave as a simple implementation of a firewall.

What I want to do is, when I change the Set<String> of blocked application packagenames, I would like the service thread to run vpnservice.builder.establish() again, using this blocked application set.

An obvious choice for this - in case an "ordinary" foreground service if the service extends LifecycleService, as shown here. However, my service has to extend android.net.VpnService, which does not implement LifecycleOwner. A possible implementation (with some modifications needed) is shown here.

My questions are:

  1. Is there a better, cleaner, more elegant way for my VPN service to observe changes in my blockedPackageName Collection, in my singleton class?
  2. If there is not another way, will implementing LifecycleOwner work in the way I expect it (how I described it, basically)?
  3. If(2), is it enough to add lifecycle.handleLifecycleEvent(Lifecycle.Event.XXXX); in my service's onCreate and onDestroy methods (see below)? Do these do anything apart from preventing memory leaks?

    //MyVpnService class
    @Override
    public void onDestroy() {
        Log.i(TAG, "Destroyed.");
        stopVpn();
        //what is the purpose of this line for my goals? 
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
    }
    

P.S.: I read the official documentation with regards to Lifecycle components, but I could not find enough code examples for my cases to make the matter more clear.

JJD
  • 50,076
  • 60
  • 203
  • 339
itarill
  • 323
  • 1
  • 14

1 Answers1

0

The best solution I find was to send a broadcast with a custom intent from the singleton class, and signing up a broadcast receiver for this intent in the vpnservice class on start. For sending a broadcast from any class, you need context - lucky for me, I already needed context in my singleton, for which context.getApplicationContext() works fine without leaking.

itarill
  • 323
  • 1
  • 14