diff --git a/app/build.gradle b/app/build.gradle
index 1190ef781187836e07c8c3182661b68666f2043d..bc39a1084d08f077d7b3212257ff6b73dbe50000 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -7,7 +7,6 @@ buildscript {
 
     dependencies {
         classpath 'io.fabric.tools:gradle:1.21.6'
-        classpath 'io.realm:realm-gradle-plugin:1.1.1'
         classpath 'org.ajoberstar:grgit:1.5.0'
     }
 }
diff --git a/app/src/main/java/info/nightscout/android/UploaderApplication.java b/app/src/main/java/info/nightscout/android/UploaderApplication.java
index aa1944885e68507b24370f9bf2f2b75fe774bda1..1bfc87f81ded988434835da9d0af962dce3ff079 100644
--- a/app/src/main/java/info/nightscout/android/UploaderApplication.java
+++ b/app/src/main/java/info/nightscout/android/UploaderApplication.java
@@ -41,7 +41,8 @@ public class UploaderApplication extends Application {
             Bugfender.setDeviceString("NightscoutURL", prefs.getString(getString(R.string.preference_nightscout_url), "Not set"));
         }
 
-        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
+        Realm.init(this);
+        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
                 .deleteRealmIfMigrationNeeded()
                 .build();
 
diff --git a/app/src/main/java/info/nightscout/android/medtronic/MainActivity.java b/app/src/main/java/info/nightscout/android/medtronic/MainActivity.java
index 843be3010fc7b4a1178ca9d6a5e9a05601e6e024..2e2fab454bf50f53735d055af908f3d63be10a53 100644
--- a/app/src/main/java/info/nightscout/android/medtronic/MainActivity.java
+++ b/app/src/main/java/info/nightscout/android/medtronic/MainActivity.java
@@ -51,10 +51,7 @@ import com.github.mikephil.charting.formatter.IValueFormatter;
 import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
 import com.github.mikephil.charting.listener.ChartTouchListener;
 import com.github.mikephil.charting.listener.OnChartGestureListener;
-import com.github.mikephil.charting.utils.ColorTemplate;
 import com.github.mikephil.charting.utils.ViewPortHandler;
-import com.google.android.gms.appindexing.Action;
-import com.google.android.gms.appindexing.Thing;
 import com.mikepenz.google_material_typeface_library.GoogleMaterial;
 import com.mikepenz.materialdrawer.AccountHeaderBuilder;
 import com.mikepenz.materialdrawer.Drawer;
@@ -84,6 +81,7 @@ import info.nightscout.android.settings.SettingsActivity;
 import info.nightscout.android.upload.nightscout.NightscoutUploadIntentService;
 import io.realm.DynamicRealmObject;
 import io.realm.Realm;
+import io.realm.RealmChangeListener;
 import io.realm.RealmResults;
 import io.realm.Sort;
 import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
@@ -92,7 +90,13 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
     private static final String TAG = MainActivity.class.getSimpleName();
 
     public static int batLevel = 0;
+    public static boolean reducePollOnPumpAway = false;
+    public static long pollInterval = MedtronicCnlIntentService.POLL_PERIOD_MS;
+    public static long lowBatteryPollInterval = MedtronicCnlIntentService.LOW_BATTERY_POLL_PERIOD_MS;
+
     private static long activePumpMac;
+
+
     boolean mEnableCgmService = true;
     SharedPreferences prefs = null;
     private PumpInfo mActivePump;
@@ -104,11 +108,21 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
     private Realm mRealm;
     private StatusMessageReceiver statusMessageReceiver = new StatusMessageReceiver();
     private MedtronicCnlAlarmReceiver medtronicCnlAlarmReceiver = new MedtronicCnlAlarmReceiver();
-    public static long pollInterval = 0;
-    public static long lowBatteryPollInterval = 0;
 
-    public static void setActivePumpMac(long pumpMac) {
-        activePumpMac = pumpMac;
+    public static long getNextPoll(PumpStatusEvent pumpStatusData) {
+        long nextPoll = pumpStatusData.getEventDate().getTime() + pumpStatusData.getPumpTimeOffset()
+                + MedtronicCnlIntentService.POLL_GRACE_PERIOD_MS;
+
+        if (pumpStatusData.getBatteryPercentage() > 25) {
+            // poll every 5 min
+            nextPoll += MainActivity.pollInterval;
+        } else {
+            // if pump battery seems to be empty reduce polling to save battery (every 15 min)
+            //TODO add message & document it
+            nextPoll += MainActivity.lowBatteryPollInterval;
+        }
+
+        return nextPoll;
     }
 
     @Override
@@ -128,9 +142,10 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
             stopCgmService();
         }
 
-        //set poll intervals
+        // setup preferences
         MainActivity.pollInterval = Long.parseLong(prefs.getString("pollInterval", Long.toString(MedtronicCnlIntentService.POLL_PERIOD_MS)));
         MainActivity.lowBatteryPollInterval = Long.parseLong(prefs.getString("lowBatPollInterval", Long.toString(MedtronicCnlIntentService.LOW_BATTERY_POLL_PERIOD_MS)));
+        MainActivity.reducePollOnPumpAway = prefs.getBoolean("doublePollOnPumpAway", false);
 
         // Disable battery optimization to avoid missing values on 6.0+
         // taken from https://github.com/NightscoutFoundation/xDrip/blob/master/app/src/main/java/com/eveningoutpost/dexdrip/Home.java#L277L298
@@ -158,8 +173,8 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
                 statusMessageReceiver,
                 new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_STATUS_MESSAGE));
         LocalBroadcastManager.getInstance(this).registerReceiver(
-                new RefreshDataReceiver(),
-                new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_REFRESH_DATA));
+                new UpdatePumpReceiver(),
+                new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_UPDATE_PUMP));
 
         mEnableCgmService = Eula.show(this, prefs);
 
@@ -483,6 +498,8 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
         } else if (key.equals("lowBatPollInterval")) {
             MainActivity.lowBatteryPollInterval = Long.parseLong(sharedPreferences.getString("lowBatPollInterval",
                     Long.toString(MedtronicCnlIntentService.LOW_BATTERY_POLL_PERIOD_MS)));
+        } else if (key.equals("doublePollOnPumpAway")) {
+            MainActivity.reducePollOnPumpAway = sharedPreferences.getBoolean("doublePollOnPumpAway", false);
         }
     }
 
@@ -527,9 +544,17 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
         }
     }
 
+    public static void setActivePumpMac(long pumpMac) {
+        activePumpMac = pumpMac;
+    }
+
     private PumpInfo getActivePump() {
         if (activePumpMac != 0L && (mActivePump == null || !mActivePump.isValid() || mActivePump.getPumpMac() != activePumpMac)) {
-            mActivePump = null;
+            if (mActivePump != null) {
+                // remove listener on old pump
+                mActivePump.removeChangeListeners();
+                mActivePump = null;
+            }
 
             PumpInfo pump = mRealm
                     .where(PumpInfo.class)
@@ -538,29 +563,52 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
 
             if (pump != null && pump.isValid()) {
                 mActivePump = pump;
+                mActivePump.addChangeListener(new RealmChangeListener<PumpInfo>() {
+                    long lastQueryTS = 0;
+                    @Override
+                    public void onChange(PumpInfo pump) {
+                        // prevent double updating after deleting old events below
+                        if (pump.getLastQueryTS() == lastQueryTS || !pump.isValid()) {
+                            return;
+                        }
+
+                        PumpStatusEvent pumpStatusData = pump.getPumpHistory().last();;
+
+                        lastQueryTS = pump.getLastQueryTS();
+
+                        startCgmService(MainActivity.getNextPoll(pumpStatusData));
+
+                        // Delete invalid or old records from Realm
+                        // TODO - show an error message if the valid records haven't been uploaded
+                        final RealmResults<PumpStatusEvent> results =
+                                mRealm.where(PumpStatusEvent.class)
+                                        .equalTo("sgv", 0)
+                                        .or()
+                                        .lessThan("eventDate", new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)))
+                                        .findAll();
+
+                        if (results.size() > 0) {
+                            mRealm.executeTransaction(new Realm.Transaction() {
+                                @Override
+                                public void execute(Realm realm) {
+                                    // Delete all matches
+                                    Log.d(TAG, "Deleting " + results.size() + " records from realm");
+                                    results.deleteAllFromRealm();
+                                }
+                            });
+                        }
+
+                        // TODO - handle isOffline in NightscoutUploadIntentService?
+                        uploadCgmData();
+                        refreshDisplay();
+                    }
+                });
             }
         }
 
         return mActivePump;
     }
 
-    /**
-     * ATTENTION: This was auto-generated to implement the App Indexing API.
-     * See https://g.co/AppIndexing/AndroidStudio for more information.
-     */
-    public Action getIndexApiAction() {
-        Thing object = new Thing.Builder()
-                .setName("Main Page") // TODO: Define a title for the content shown.
-                // TODO: Make sure this auto-generated URL is correct.
-                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
-                .build();
-        return new Action.Builder(Action.TYPE_VIEW)
-                .setObject(object)
-                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
-                .build();
-    }
-
-
     private class StatusMessageReceiver extends BroadcastReceiver {
         private class StatusMessage {
             private long timestamp;
@@ -650,6 +698,8 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
             PumpInfo pump = getActivePump();
 
             if (pump != null && pump.isValid()) {
+                Log.d(TAG, "history display refresh size: " + pump.getPumpHistory().size());
+                Log.d(TAG, "history display refresh date: " + pump.getPumpHistory().last().getEventDate());
                 pumpStatusData = pump.getPumpHistory().last();
             }
 
@@ -790,7 +840,10 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
         }
     }
 
-    private class RefreshDataReceiver extends BroadcastReceiver {
+    /**
+     * has to be done in MainActivity thread
+     */
+    private class UpdatePumpReceiver extends BroadcastReceiver {
 
         @Override
         public void onReceive(Context context, Intent intent) {
@@ -799,55 +852,8 @@ public class MainActivity extends AppCompatActivity implements OnSharedPreferenc
             if (mRealm.isClosed()) {
                 return;
             }
-
-            PumpStatusEvent pumpStatusData = null;
-
-            PumpInfo pump = getActivePump();
-
-            if (pump != null && pump.isValid()) {
-                pumpStatusData = pump.getPumpHistory().last();
-            } else {
-                return;
-            }
-
-            long nextPoll = pumpStatusData.getEventDate().getTime() + pumpStatusData.getPumpTimeOffset()
-                    + MedtronicCnlIntentService.POLL_GRACE_PERIOD_MS;
-
-            if (pumpStatusData.getBatteryPercentage() > 25) {
-                // poll every 5 min
-                nextPoll += MainActivity.pollInterval;
-            } else {
-                // if pump battery seems to be empty reduce polling to save battery (every 15 min)
-                //TODO configurable???
-                //TODO add message & document it
-                nextPoll += MainActivity.lowBatteryPollInterval;
-            }
-            startCgmService(nextPoll);
-
-            // Delete invalid or old records from Realm
-            // TODO - show an error message if the valid records haven't been uploaded
-            final RealmResults<PumpStatusEvent> results =
-                    mRealm.where(PumpStatusEvent.class)
-                            .equalTo("sgv", 0)
-                            .or()
-                            .lessThan("eventDate", new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)))
-                            .findAll();
-
-            if (results.size() > 0) {
-                mRealm.executeTransaction(new Realm.Transaction() {
-                    @Override
-                    public void execute(Realm realm) {
-                        // Delete all matches
-                        Log.d(TAG, "Deleting " + results.size() + " records from realm");
-                        results.deleteAllFromRealm();
-                    }
-                });
-            }
-
-            // TODO - handle isOffline in NightscoutUploadIntentService?
-            uploadCgmData();
-
-            refreshDisplay();
+            //init local pump listener
+            getActivePump();
         }
     }
 
diff --git a/app/src/main/java/info/nightscout/android/medtronic/message/PumpStatusResponseMessage.java b/app/src/main/java/info/nightscout/android/medtronic/message/PumpStatusResponseMessage.java
index 67802a3cba0db138e3e5366f8b948b3714e36071..4ef072df354fe1c0fb4ecdb5d72f3f4f0c1072fd 100644
--- a/app/src/main/java/info/nightscout/android/medtronic/message/PumpStatusResponseMessage.java
+++ b/app/src/main/java/info/nightscout/android/medtronic/message/PumpStatusResponseMessage.java
@@ -125,6 +125,7 @@ public class PumpStatusResponseMessage extends MedtronicSendMessageResponseMessa
 
         // TODO - this should go in the sgvDate, and eventDate should be the time of this poll.
         sgvDate = MessageUtils.decodeDateTime(rtc, offset);
+        Log.d(TAG, "original sgv date: " + sgvDate);
 
         // Predictive low suspend
         // TODO - there is more status info in this byte other than just a boolean yes/no
diff --git a/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlAlarmManager.java b/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlAlarmManager.java
index 9547688cbdf4801add9c7c36bcc7bbf5fcb13390..240a2bfe44d853781c7d44f79dbae445d04555df 100644
--- a/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlAlarmManager.java
+++ b/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlAlarmManager.java
@@ -36,26 +36,37 @@ public class MedtronicCnlAlarmManager {
         setAlarm(System.currentTimeMillis());
     }
 
+    /**
+     * set the alarm in the future
+     *
+     * @param inFuture number of millin in the future
+     */
+    public static void setAlarmAfterMillis(long inFuture) {
+        setAlarm(System.currentTimeMillis() + inFuture);
+    }
+
     // Setting the alarm to call onRecieve
     public static void setAlarm(long millis) {
         if (alarmManager == null || pendingIntent == null)
             return;
 
+        Log.d(TAG, "request to set Alarm at " + new Date(millis));
+
         long now = System.currentTimeMillis();
         // don't trigger the past
         if (millis < now)
             millis = now;
 
         // only accept alarm nearer than the last one
-        if (nextAlarm < millis && nextAlarm >= now) {
-            return;
-        }
+        //if (nextAlarm < millis && nextAlarm > now) {
+        //    return;
+        //}
 
         cancelAlarm();
 
         nextAlarm = millis;
 
-        Log.d(TAG, "AlarmManager set to fire   at " + new Date(millis));
+        Log.d(TAG, "Alarm set to fire at " + new Date(millis));
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(millis, null), pendingIntent);
         } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
@@ -69,7 +80,7 @@ public class MedtronicCnlAlarmManager {
 
     // restarting the alarm after MedtronicCnlIntentService.POLL_PERIOD_MS from now
     public static void restartAlarm() {
-        setAlarm(System.currentTimeMillis() + MainActivity.pollInterval + MedtronicCnlIntentService.POLL_GRACE_PERIOD_MS);
+        setAlarmAfterMillis(MainActivity.pollInterval + MedtronicCnlIntentService.POLL_GRACE_PERIOD_MS);
     }
 
     // Cancel the alarm.
diff --git a/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlIntentService.java b/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlIntentService.java
index 8dd84f8581f30066a7ceb33c94b0982e6e9c3c44..d56b74b45e076b91467e9215d6b5a8bd92c0211f 100644
--- a/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlIntentService.java
+++ b/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCnlIntentService.java
@@ -38,6 +38,8 @@ import info.nightscout.android.xdrip_plus.XDripPlusUploadReceiver;
 import io.realm.Realm;
 import io.realm.RealmResults;
 
+import static info.nightscout.android.medtronic.MainActivity.setActivePumpMac;
+
 public class MedtronicCnlIntentService extends IntentService {
     public final static int USB_VID = 0x1a79;
     public final static int USB_PID = 0x6210;
@@ -154,10 +156,11 @@ public class MedtronicCnlIntentService extends IntentService {
 
             if (info == null) {
                 // TODO - use realm.createObject()?
-                info = new ContourNextLinkInfo();
-                info.setSerialNumber(cnlReader.getStickSerial());
+                info = realm.createObject(ContourNextLinkInfo.class, cnlReader.getStickSerial());
+                //info = new ContourNextLinkInfo();
+                ///info.setSerialNumber(cnlReader.getStickSerial());
 
-                info = realm.copyToRealm(info);
+                //info = realm.copyToRealm(info);
             }
 
             cnlReader.getPumpSession().setStickSerial(info.getSerialNumber());
@@ -182,17 +185,19 @@ public class MedtronicCnlIntentService extends IntentService {
 
                 long pumpMAC = cnlReader.getPumpSession().getPumpMAC();
                 Log.i(TAG, "PumpInfo MAC: " + (pumpMAC & 0xffffff));
-                MainActivity.setActivePumpMac(pumpMAC);
                 PumpInfo activePump = realm
                         .where(PumpInfo.class)
                         .equalTo("pumpMac", pumpMAC)
                         .findFirst();
 
                 if (activePump == null) {
-                    activePump = realm.createObject(PumpInfo.class);
-                    activePump.setPumpMac(pumpMAC);
+                    activePump = realm.createObject(PumpInfo.class, pumpMAC);
+                    //activePump.setPumpMac(pumpMAC);
                 }
 
+                activePump.updateLastQueryTS();
+
+
                 byte radioChannel = cnlReader.negotiateChannel(activePump.getLastRadioChannel());
                 if (radioChannel == 0) {
                     sendStatus("Could not communicate with the 640g. Are you near the pump?");
@@ -200,8 +205,11 @@ public class MedtronicCnlIntentService extends IntentService {
 
                     // reduce polling interval to half until pump is available
                     //TODO: make it configurable???
-                    MedtronicCnlAlarmManager.setAlarm(System.currentTimeMillis() + (MainActivity.pollInterval  + MedtronicCnlIntentService.POLL_GRACE_PERIOD_MS)/2L);
+                    MedtronicCnlAlarmManager.setAlarmAfterMillis(
+                            (MainActivity.pollInterval  + MedtronicCnlIntentService.POLL_GRACE_PERIOD_MS) / (MainActivity.reducePollOnPumpAway?2L:1L)
+                    );
                 } else {
+                    setActivePumpMac(pumpMAC);
                     activePump.setLastRadioChannel(radioChannel);
                     sendStatus(String.format(Locale.getDefault(), "Connected to Contour Next Link on channel %d.", (int) radioChannel));
                     Log.d(TAG, String.format("Connected to Contour Next Link on channel %d.", (int) radioChannel));
@@ -224,21 +232,9 @@ public class MedtronicCnlIntentService extends IntentService {
                     pumpRecord.setPumpTimeOffset(pumpOffset);
                     pumpRecord.setPumpDate(new Date(pumpTime - pumpOffset));
                     cnlReader.updatePumpStatus(pumpRecord);
-                    activePump.getPumpHistory().add(pumpRecord);
-
-                    // start reading other data in debug only
-                    if (BuildConfig.DEBUG) {
-                        // read basal pattern
-                        //cnlReader.getBasalPatterns();
-
-                        // Read history
-                        //cnlReader.getHistory();
-                    }
-
 
                     cnlReader.endEHSMSession();
 
-                    boolean cancelTransaction = true;
                     if (pumpRecord.getSgv() != 0) {
                         // Check that the record doesn't already exist before committing
                         RealmResults<PumpStatusEvent> checkExistingRecords = activePump.getPumpHistory()
@@ -248,18 +244,17 @@ public class MedtronicCnlIntentService extends IntentService {
                                 .findAll();
 
                         // There should be the 1 record we've already added in this transaction.
-                        if (checkExistingRecords.size() <= 1) {
-                            realm.commitTransaction();
-                            cancelTransaction = false;
+                        if (checkExistingRecords.size() == 0) {
+                            activePump.getPumpHistory().add(pumpRecord);
                         }
 
-                        // Tell the Main Activity we have new data
-                        sendMessage(Constants.ACTION_REFRESH_DATA);
+                        Log.d(TAG, "history reading size: " + activePump.getPumpHistory().size());
+                        Log.d(TAG, "history reading date: " + activePump.getPumpHistory().last().getEventDate());
                     }
 
-                    if (cancelTransaction) {
-                        realm.cancelTransaction();
-                    }
+                    realm.commitTransaction();
+                    // Tell the Main Activity we have new data
+                    sendMessage(Constants.ACTION_UPDATE_PUMP);
                 }
             } catch (UnexpectedMessageException e) {
                 Log.e(TAG, "Unexpected Message", e);
@@ -306,6 +301,10 @@ public class MedtronicCnlIntentService extends IntentService {
         }
     }
 
+    private void setActivePumpMac(long pumpMAC) {
+        MainActivity.setActivePumpMac(pumpMAC);
+    }
+
     // reliable wake alarm manager wake up for all android versions
     public static void wakeUpIntent(Context context, long wakeTime, PendingIntent pendingIntent) {
         final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
@@ -345,6 +344,7 @@ public class MedtronicCnlIntentService extends IntentService {
         public static final String ACTION_USB_PERMISSION = "info.nightscout.android.medtronic.USB_PERMISSION";
         public static final String ACTION_REFRESH_DATA = "info.nightscout.android.medtronic.service.CGM_DATA";
         public static final String ACTION_USB_REGISTER = "info.nightscout.android.medtronic.USB_REGISTER";
+        public static final String ACTION_UPDATE_PUMP = "info.nightscout.android.medtronic.UPDATE_PUMP";
 
         public static final String EXTENDED_DATA = "info.nightscout.android.medtronic.service.DATA";
     }
diff --git a/app/src/main/java/info/nightscout/android/model/medtronicNg/PumpInfo.java b/app/src/main/java/info/nightscout/android/model/medtronicNg/PumpInfo.java
index 3b25a51612206e6ffc265a1b6e1e18190b056d71..dac3391fc883cfb4cf6806b1aad6ca4e74fd016f 100644
--- a/app/src/main/java/info/nightscout/android/model/medtronicNg/PumpInfo.java
+++ b/app/src/main/java/info/nightscout/android/model/medtronicNg/PumpInfo.java
@@ -2,6 +2,8 @@ package info.nightscout.android.model.medtronicNg;
 
 import io.realm.RealmList;
 import io.realm.RealmObject;
+import io.realm.Sort;
+import io.realm.annotations.Ignore;
 import io.realm.annotations.PrimaryKey;
 
 /**
@@ -12,6 +14,7 @@ public class PumpInfo extends RealmObject {
     private long pumpMac;
     private String deviceName;
     private byte lastRadioChannel;
+    private long lastQueryTS = 0;
     private RealmList<ContourNextLinkInfo> associatedCnls;
     private RealmList<PumpStatusEvent> pumpHistory;
 
@@ -19,7 +22,7 @@ public class PumpInfo extends RealmObject {
         return pumpMac;
     }
 
-    public void setPumpMac(long pumpMac) {
+    private void setPumpMac(long pumpMac) {
         this.pumpMac = pumpMac;
     }
 
@@ -58,4 +61,12 @@ public class PumpInfo extends RealmObject {
     public long getPumpSerial() {
         return pumpMac & 0xffffff;
     }
+
+    public long getLastQueryTS() {
+        return lastQueryTS;
+    }
+
+    public void updateLastQueryTS() {
+        lastQueryTS = System.currentTimeMillis();
+    }
 }
diff --git a/app/src/main/java/info/nightscout/android/upload/nightscout/NightscoutUploadIntentService.java b/app/src/main/java/info/nightscout/android/upload/nightscout/NightscoutUploadIntentService.java
index 188ed1c704b88fc3a6af81768739eb8fef99f00a..596c6a480293b6aa6ea555085fcf3bb4905c1688 100644
--- a/app/src/main/java/info/nightscout/android/upload/nightscout/NightscoutUploadIntentService.java
+++ b/app/src/main/java/info/nightscout/android/upload/nightscout/NightscoutUploadIntentService.java
@@ -42,7 +42,7 @@ public class NightscoutUploadIntentService extends IntentService {
     private static final SimpleDateFormat ISO8601_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
     private static final int SOCKET_TIMEOUT = 60 * 1000;
     private static final int CONNECTION_TIMEOUT = 30 * 1000;
-    Context mContext;
+    private Context mContext;
     private Realm mRealm;
 
     public NightscoutUploadIntentService() {
@@ -62,6 +62,7 @@ public class NightscoutUploadIntentService extends IntentService {
 
         Log.i(TAG, "onCreate called");
         mContext = this.getBaseContext();
+
     }
 
     @Override
@@ -92,6 +93,7 @@ public class NightscoutUploadIntentService extends IntentService {
         } else {
             Log.i(TAG, "No records has to be uploaded");
         }
+        mRealm.close();
 
         NightscoutUploadReceiver.completeWakefulIntent(intent);
     }
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 5833c20d33506c1cbb1d357cf8781ccd9ea78d12..48268a1e642c4b34d2d4e52b74dbdd9963f34731 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -52,8 +52,8 @@
     <string name="menu_name_status">Status</string>
     <string name="menu_name_battery_status">unknown</string>
 
-    <string name="preferences_poll_interval">poll interval</string>
-    <string name="preferences_low_battery_poll_interval">poll interval on low pump battery</string>
+    <string name="preferences_poll_interval">Poll interval</string>
+    <string name="preferences_low_battery_poll_interval">Poll interval on low pump battery</string>
     <string name="no_registered_contour_next_link_devices">No registered Contour Next Link devices</string>
     <string name="to_register_a_contour_next_link_you_must_first_plug_it_in_and_get_a_reading_from_the_pump">To register a Contour Next Link you must first plug it in, and get a reading from the pump.</string>
     <string name="serial_number">Serial number</string>
diff --git a/app/src/main/res/xml/preferences.xml b/app/src/main/res/xml/preferences.xml
index c42c9a0faab8db5a821d966e873dd0e1e477c320..0183e9581d19c4460d5007c0d754336c9a092668 100644
--- a/app/src/main/res/xml/preferences.xml
+++ b/app/src/main/res/xml/preferences.xml
@@ -25,6 +25,14 @@
             android:summary="%s"
             android:entries="@array/poll_interval"
             android:entryValues="@array/poll_interval_millis"/>
+        <info.nightscout.android.utils.CustomSwitchPreference
+            android:disableDependentsState="false"
+            android:key="doublePollOnPumpAway"
+            android:summaryOff="Normal polling if pump is away"
+            android:summaryOn="Double polling if pump is away"
+            android:switchTextOff="off"
+            android:switchTextOn="on"
+            android:title="Polling interval if pump is away"/>
         <ListPreference
             android:key="lowBatPollInterval"
             android:defaultValue="900000"
diff --git a/build.gradle b/build.gradle
index 9da42b0b994170c75de5ee547bfabc0007cf8dd7..fa343792dd739dcc26b1521ca4931cdda922476f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -8,7 +8,7 @@ buildscript {
         classpath 'com.android.tools.build:gradle:2.2.3'
         // NOTE: Do not place your application dependencies here; they belong
         // in the individual module build.gradle files
-        classpath "io.realm:realm-gradle-plugin:1.0.0"
+        classpath 'io.realm:realm-gradle-plugin:2.2.2'
     }
 }