To communicate with contactless targets, the MIDlet must first determine which types of contactless targets the device supports, and then register a listener that notifies the MIDlet when a supported contactless target is detected. The MIDlet must register a listener separately for each type of contactless target.
Note: The following instructions only cover the contactless communication functionality of the MIDlet. For instructions on creating a full MIDlet, see sections Getting started and Implementing MIDlet lifecycle requirements.
To detect contactless targets:
Import the required Contactless Communication API packages:
// packages required for determining supported types and registering a target listener import javax.microedition.contactless.ContactlessException; import javax.microedition.contactless.DiscoveryManager; import javax.microedition.contactless.TargetListener; import javax.microedition.contactless.TargetProperties; import javax.microedition.contactless.TargetType;
Determine the contactless target types supported by the device by using
the DiscoveryManager.getSupportedTargetTypes
method:
TargetType[] supportedTargetTypes = DiscoveryManager.getSupportedTargetTypes();
Register a TargetListener
for a supported contactless
target type by using the DiscoveryManager.addTargetListener
method.
If you want to register the TargetListener
for multiple
contactless target types, call the method separately for each type.
The following code snippet creates a custom method
that registers a TargetListener
for NDEF targets
(TargetType.NDEF_TAG
).
public void registerNDEFListener(TargetListener targetListener) { // determine the contactless target types supported by the device TargetType[] supportedTargetTypes = DiscoveryManager.getSupportedTargetTypes(); // check if the NDEF_TAG type is supported by the device, // and if it is, register the listener for it for (int i=0; i<supportedTargetTypes.length; i++) { if (supportedTargetTypes[i].equals(TargetType.NDEF_TAG)) { try { // create a DiscoveryManager instance DiscoveryManager discoveryManager = DiscoveryManager.getInstance(); // register the specified TargetListener (parameter) for the NDEF_TAG type discoveryManager.addTargetListener(targetListener, TargetType.NDEF_TAG); } catch (SecurityException e) { // handle SecurityException from DiscoveryManager.getInstance() } catch (ContactlessException e) { // handle ContactlessException from discoveryManager.addTargetListener() } catch (IllegalStateException e) { // handle IllegalStateException from discoveryManager.addTargetListener() } catch (NullPointerException e) { // handle NullPointerException from discoveryManager.addTargetListener() } // break the for loop, since a matching target type has been found break; } } }
Now that you have set the MIDlet to detect contactless targets,
define how it communicates with them by implementing the TargetListener
.