Maybe I do not understand the "open+attach and detach/close" part well enough.
As seen in the code below I open each InterfaceKit instance with
.open(serial). Attach happens automatically, but notifies the attach listener via
AttachListener.attached(final AttachEvent ae). The Phidget is detached/closed by calling
.close() Is this correct?
Code: Select all
public class PhidgetInterfaceService extends Service {
private PhidgetDevices devices;
@Override
public void onCreate() {
Manager.Initialize(this);
devices = new PhidgetDevices();
devices.setOnStateChange(...);
devices.load();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onDestroy() {
devices.close();
Manager.Uninitialize();
}
}
Code: Select all
public class PhidgetDevices {
private Map<String,PhidgetDevice> iks;
public void load(){
List<PhidgetDevice> devices = getDevicesFromTheDatabase();
for (PhidgetDevice device : devices) {
if (!iks.containsKey(device.getSerial())){
iks.put(device.getSerial(), device);
device.setOnStateChange(getStateChangeListener());
device.open();
}
}
}
public void close(){
for (Entry<String,PhidgetDevice> kv : iks.entrySet()){
kv.getValue().close();
}
}
private List<PhidgetDevice> getDevicesFromTheDatabase(){
//initializes a List of PhidgetDevice and sets there property: serial
}
}
Code: Select all
public class PhidgetDevice {
public String serial;
private InterfaceKitPhidget ik = null;
public PhidgetDevice(){
}
public void open(){
if (ik != null) close(); //should never be the case
try {
ik = new InterfaceKitPhidget();
} catch (PhidgetException e) {
e.printStackTrace();
}
ik.addAttachListener(new AttachListener() {
public void attached(final AttachEvent ae) {
//set local variables
//notify observers
}
});
ik.addDetachListener(new DetachListener() {
public void detached(final DetachEvent ae) {
//notify observers
}
});
ik.addSensorChangeListener(new SensorChangeListener() {
public void sensorChanged(SensorChangeEvent se) {
//notify observers
}
});
ik.addInputChangeListener(new InputChangeListener() {
public void inputChanged(InputChangeEvent ie) {
//notify observers
}
});
ik.addOutputChangeListener(new OutputChangeListener() {
public void outputChanged(OutputChangeEvent oe) {
//notify observers
}
});
try {
ik.open(Integer.parseInt(serial));
//ik.waitForAttachment();
} catch (PhidgetException e) {
e.printStackTrace();
}
}
public void close(){
try {
Log.d("PhidgetInterfaceService", "opening device " + serial);
if (ik.isAttached()) ik.close();
} catch (PhidgetException e) {
e.printStackTrace();
}
}
}
LogCat shows "opening device ####" once while the threads are constantly being recreated.
I hope this helps. The code above is cleaned up. If you like I could send you the whole app zipped up?