package edu.ucla.iBeaconNav; import java.util.List; import java.util.LinkedList; import java.util.Collection; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.Looper; import android.os.Messenger; import android.os.RemoteException; import android.preference.PreferenceManager; public class Task extends Service { /* Private data */ private Messenger messenger; private Beacon beacon; private Sensors sensors; private boolean running; /* Public methods */ public void tellMain(CMD.Response cmd, Object value) { try { android.os.Message msg = android.os.Message.obtain(); msg.what = cmd.ordinal(); msg.obj = value; this.messenger.send(msg); } catch (Exception e) { Util.debug("Task: error sending message", e); } } public void notify(String text, int icon) { // Notify Main this.tellMain(CMD.Response.NOTIFY, text); // Notification bar Notification note = new Notification.Builder(this) .setContentTitle("iBeaconNav!") .setContentText("iBeaconNav!") .setSmallIcon(icon) .build(); this.startForeground(1, note); } public boolean isRunning() { return this.running; } /* Private methods */ private void handle(CMD.Command cmd, Messenger mgr) { // Validate messenger if (cmd != CMD.Command.REGISTER && mgr != null && mgr != this.messenger) Util.debug("Task: handle - invalid messenger"); // Handle the command switch (cmd) { // Setup communication with Main case REGISTER: Util.debug("Task: handle - register"); this.messenger = mgr; this.tellMain(CMD.Response.REGISTER, this); break; // Create client thread case CONNECT: Util.debug("Task: handle - connect"); this.running = true; this.beacon.connect(); this.sensors.connect(); this.notify("Connected", android.R.drawable.presence_online); break; // Stop client thread case DISCONNECT: Util.debug("Task: handle - register"); this.running = false; this.beacon.disconnect(); this.sensors.disconnect(); this.stopForeground(true); break; // Reset heading case RSTHEAD: this.sensors.reset_heading(); break; // Reset distance case RSTDST: this.sensors.reset_distance(); break; } } /* Service Methods */ @Override public void onCreate() { Util.debug("Task: onCreate"); super.onCreate(); this.beacon = new Beacon(this); this.sensors = new Sensors(this); } @Override public void onDestroy() { Util.debug("Task: onDestroy"); super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Util.debug("Task: onStartCommand"); int rval = super.onStartCommand(intent, flags, startId); CMD.Command cmd = (CMD.Command)intent.getExtras().get("Command"); Messenger mgr = (Messenger)intent.getExtras().get("Messenger"); this.handle(cmd, mgr); return rval; } @Override public IBinder onBind(Intent intent) { Util.debug("Task: onBind"); return null; } }