From 6c985c2b0433a08add3bbf55fdb30102157b4ede Mon Sep 17 00:00:00 2001 From: Mike Beattie Date: Tue, 28 Aug 2012 22:10:26 +1200 Subject: [PATCH] altosdroid: add timer to stop service * Stops when no UI clients, and no bluetooth connection remains Signed-off-by: Mike Beattie --- .../AltosDroid/TelemetryService.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/altosdroid/src/org/altusmetrum/AltosDroid/TelemetryService.java b/altosdroid/src/org/altusmetrum/AltosDroid/TelemetryService.java index d11fc53a..ffe96946 100644 --- a/altosdroid/src/org/altusmetrum/AltosDroid/TelemetryService.java +++ b/altosdroid/src/org/altusmetrum/AltosDroid/TelemetryService.java @@ -20,6 +20,8 @@ package org.altusmetrum.AltosDroid; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.concurrent.TimeoutException; +import java.util.Timer; +import java.util.TimerTask; import android.app.Notification; //import android.app.NotificationManager; @@ -61,6 +63,9 @@ public class TelemetryService extends Service { private int NOTIFICATION = R.string.telemetry_service_label; //private NotificationManager mNM; + // Timer - we wake up every now and then to decide if the service should stop + private Timer timer = new Timer(); + ArrayList mClients = new ArrayList(); // Keeps track of all current registered clients. final Handler mHandler = new IncomingHandler(this); final Messenger mMessenger = new Messenger(mHandler); // Target we publish for clients to send messages to IncomingHandler. @@ -204,12 +209,28 @@ public class TelemetryService extends Service { } + private void onTimerTick() { + if (D) Log.d(TAG, "Timer wakeup"); + try { + if (mClients.size() <= 0 && state != STATE_CONNECTED) { + stopSelf(); + } + } catch (Throwable t) { + Log.e(TAG, "Timer failed: ", t); + } + } + + @Override public void onCreate() { // Create a reference to the NotificationManager so that we can update our notifcation text later //mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); setState(STATE_READY); + + // Start our timer - first event in 10 seconds, then every 10 seconds after that. + timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 10000L, 10000L); + } @Override @@ -248,6 +269,9 @@ public class TelemetryService extends Service { // Demote us from the foreground, and cancel the persistent notification. stopForeground(true); + // Stop our timer + if (timer != null) {timer.cancel();} + // Tell the user we stopped. Toast.makeText(this, R.string.telemetry_service_stopped, Toast.LENGTH_SHORT).show(); } -- 2.30.2