/** * Binds an Android <code>Activity</code> or <code>Service</code> to the <code>IBeaconService * </code>. The <code>Activity</code> or <code>Service</code> must implement the <code> * IBeaconConsuemr</code> interface so that it can get a callback when the service is ready to * use. * * @param consumer the <code>Activity</code> or <code>Service</code> that will receive the * callback when the service is ready. */ public void bind(IBeaconConsumer consumer) { if (consumers.keySet().contains(consumer)) { Log.i(TAG, "This consumer is already bound"); } else { Log.i(TAG, "This consumer is not bound. binding: " + consumer); consumers.put(consumer, false); Intent intent = new Intent(consumer.getApplicationContext(), IBeaconService.class); consumer.bindService(intent, iBeaconServiceConnection, Context.BIND_AUTO_CREATE); Log.i(TAG, "consumer count is now:" + consumers.size()); } }
// Called when the connection with the service is established public void onServiceConnected(ComponentName className, IBinder service) { Log.d(TAG, "we have a connection to the service now"); serviceMessenger = new Messenger(service); Iterator<IBeaconConsumer> consumerIterator = consumers.keySet().iterator(); while (consumerIterator.hasNext()) { IBeaconConsumer consumer = consumerIterator.next(); Boolean alreadyConnected = consumers.get(consumer); if (!alreadyConnected) { consumer.onIBeaconServiceConnect(); consumers.put(consumer, true); } } }
/** * Unbinds an Android <code>Activity</code> or <code>Service</code> to the <code>IBeaconService * </code>. This should typically be called in the onDestroy() method. * * @param consumer the <code>Activity</code> or <code>Service</code> that no longer needs to use * the service. */ public void unBind(IBeaconConsumer consumer) { if (consumers.keySet().contains(consumer)) { Log.i(TAG, "Unbinding"); consumer.unbindService(iBeaconServiceConnection); consumers.remove(consumer); } else { Log.i(TAG, "This consumer is not bound to: " + consumer); Log.i(TAG, "Bound consumers: "); for (int i = 0; i < consumers.size(); i++) { Log.i(TAG, " " + consumers.get(i)); } } }