vpn: check fragment is visible before adding prefs

As VPN settings listens to network events it may get woken up again
while it's in the background.

Bug: 23596799
Change-Id: If6e07493da447d7ded324ff86b6e7d57c5c615e3
diff --git a/src/com/android/settings/vpn2/VpnSettings.java b/src/com/android/settings/vpn2/VpnSettings.java
index 4e21c05..e5a78b6 100644
--- a/src/com/android/settings/vpn2/VpnSettings.java
+++ b/src/com/android/settings/vpn2/VpnSettings.java
@@ -222,6 +222,7 @@
     public boolean handleMessage(Message message) {
         mUpdater.removeMessages(RESCAN_MESSAGE);
 
+        // Run heavy RPCs before switching to UI thread
         final List<VpnProfile> vpnProfiles = loadVpnProfiles(mKeyStore);
         final List<AppVpnInfo> vpnApps = getVpnApps(getActivity(), /* includeProfiles */ true);
 
@@ -230,10 +231,15 @@
 
         final Set<Integer> readOnlyUsers = getReadOnlyUserProfiles();
 
-        // Refresh the PreferenceGroup which lists VPNs
+        // Refresh list of VPNs
         getActivity().runOnUiThread(new Runnable() {
             @Override
             public void run() {
+                // Can't do anything useful if the context has gone away
+                if (!isAdded()) {
+                    return;
+                }
+
                 // Find new VPNs by subtracting existing ones from the full set
                 final Set<Preference> updates = new ArraySet<>();