Source code listing for DiscoveryMain.java

001 package net.benhui.btgallery.discovery;
002 
003 import javax.microedition.midlet.*;
004 import javax.microedition.lcdui.*;
005 import javax.bluetooth.*;
006 import java.util.*;
007 import net.benhui.btgallery.Util;
008 import javax.microedition.lcdui.Command;
009 import javax.microedition.lcdui.Displayable;
010 
011 /**
012  *
013  <p>Title: MIDlet that demostrate Bluetooth Device and Service discovery</p>
014  <p>Description: Important areas are doDiscoverDevice(), doDiscoverService() and Listener class</p>
015  <p>Copyright: Copyright (c) 2003</p>
016  @author Ben Hui (www.benhui.net)
017  @version 1.0
018  *
019  * LICENSE:
020  * This code is licensed under GPL. (See http://www.gnu.org/copyleft/gpl.html)
021  *
022  */
023 public class DiscoveryMain extends MIDlet implements CommandListener
024 {
025   // commonly used singleton object
026   public static DiscoveryMain instance;
027   private static Display display;
028 
029   // GUI component/screen
030   private DeviceDiscoveryUI devicediscoveryui = null;
031   private ServiceDiscoveryUI servicediscoveryui = null;
032 
033   // Bluetooth singleton object
034   LocalDevice device;
035   DiscoveryAgent agent;
036 
037   // list of RemoteDevice discovered
038   public static Vector devices = new Vector();
039   // list of DeviceClass discovered (not used in this example)
040   public static Vector deviceClasses = new Vector();
041   // list of ServiceRecrod discovered for one RemoteDevice
042   public static Vector services = new Vector();
043   // index of the currently selected RemoteDevice, obtained from DeviceDiscoveryUI
044   public static int selectedDevice = -1;
045 
046   public DiscoveryMain()
047   {
048     instance = this;
049   }
050 
051   /**
052    * Implements MIDlet lifecycle
053    */
054   public void startApp()
055   {
056     display = Display.getDisplay(this);
057 
058     devicediscoveryui = new DeviceDiscoveryUI();
059     servicediscoveryui = new ServiceDiscoveryUI();
060 
061     // show list of device.
062     // it is an empty list at start up
063     devicediscoveryui.showui();
064     display.setCurrentdevicediscoveryui );
065   }
066 
067   /**
068    * Implements MIDlet lifecycle
069    */
070   public void pauseApp() {
071   }
072 
073   /**
074    * Implements MIDlet lifecycle
075    */
076   public void destroyApp(boolean unconditional) {
077   }
078 
079   /**
080    *  exit MIDlet
081    */
082   public static void quitApp() {
083     instance.destroyApp(true);
084     instance.notifyDestroyed();
085     instance = null;
086   }
087 
088   // utility function
089   public static void log(String s)
090   {
091     System.out.println(s);
092   }
093 
094   /**
095    * An utility function that show a alert box that display an exception message.
096    @param e
097    @param next_screen
098    */
099   public void showExceptionAlertException e, Screen next_screen )
100   {
101     Alert alert = new Alert"Problem""Exception: "+e.getClass().getName()+" "+e.getMessage(), null, AlertType.ERROR );
102     alert.setTimeoutAlert.FOREVER );
103     display.setCurrentalert, next_screen );
104   }
105 
106   /**
107    * Perform Bluetooth device discovery.
108    *
109    */
110   public void doDiscoverDevice()
111   {
112     try
113     {
114       //
115       // initialize the JABWT stack
116       device = LocalDevice.getLocalDevice()// obtain reference to singleton
117       device.setDiscoverable(DiscoveryAgent.GIAC)// set Discover mode to GIAC
118       agent = device.getDiscoveryAgent()// obtain reference to singleton
119 
120       // start Bluetooth inquiry (GIAC mode)
121       // inquiry response direct to Listener object
122       agent.startInquiryDiscoveryAgent.GIAC, new Listener() );
123 
124 
125     catch BluetoothStateException e )
126     {
127       e.printStackTrace();
128 
129       showExceptionAlerte, devicediscoveryui );
130 
131     }
132 
133   }
134   /**
135    * Perform service discovery on a remote device.
136    @param remote the remote device to inquire services for
137    */
138   public void doDiscoverService(RemoteDevice remote)
139   {
140     try
141     {
142       //
143       // this large array of integer values will tell JABWT to query
144       // for all known attributes
145       // see https://www.bluetooth.org/foundry/assignnumb/document/service_discovery
146       // section 4.5 for meaning of these IDs
147       //
148       // note: you don't have to retrieve all attribute everytime. in fact, you
149       // can put null for attr and retrieve just the default values. that probably
150       // good enough for most cases. we list all attributes for demo purpose
151       //
152       int[] attr = new int[]{0x00000x00010x00020x00030x0004,
153           0x00050x00060x00070x00080x00090x000A0x000B0x000C0x000D,
154           0x01000x01010x01020x02000x0201,
155           0x03010x03020x03030x03040x03050x03060x03070x03080x0309,
156           0x030A0x030B0x030C0x030D0x030E0x03100x03110x03120x0313 };
157       //
158       // search for L2CAP services, most services based on L2CAP
159       //
160       // note: Rococo simulator required a new instance of Listener for
161       // every search. not sure if this is also the case in real devices
162       agent.searchServicesattr, // attributes to retrieve from remote device
163                            new UUID[]{ new UUID0x0100 )  }// search criteria, 0x0100 = L2CAP
164                            remote,
165                            new Listener())// direct discovery response to Listener object
166     }
167     catch BluetoothStateException e )
168     {
169       e.printStackTrace();
170       showExceptionAlerte, devicediscoveryui );
171 
172     }
173 
174   }
175 
176   /**
177    * Handle user action and input.
178    * All GUI Command are directed to this function for simplicity of this demo.
179    @param c
180    @param d
181    */
182   public void commandAction(Command c, Displayable d)
183   {
184     if d == devicediscoveryui && c.getLabel().equals("Discover Devices") )
185     {
186       // clear previous founding first
187       devices.removeAllElements();
188       deviceClasses.removeAllElements();
189 
190       // perform discovery
191       doDiscoverDevice();
192 
193       // tell user to wait
194       devicediscoveryui.setMsg("[Please Wait...]");
195 
196 
197     else if d == devicediscoveryui && c.getLabel().equals("Discover Services") )
198     {
199       // remove all existing records first
200       services.removeAllElements();
201 
202       selectedDevice = devicediscoveryui.getSelectedIndex();
203 
204       // make sure user did select a device from the GUI list
205       if selectedDevice == -|| selectedDevice >= devices.size() )
206       {
207         Alert alert = new Alert"Problem""No device selected", null, AlertType.ERROR );
208         alert.setTimeoutAlert.FOREVER );
209         display.setCurrentalert, devicediscoveryui );
210 
211         return;
212       }
213 
214 
215       RemoteDevice remoteDevice = (RemoteDevice)
216           devices.elementAt(selectedDevice);
217 
218       // perform service discovery
219       doDiscoverServiceremoteDevice );
220 
221     else if d == devicediscoveryui && c.getLabel().equals("Exit") )
222     {
223       // exit application
224       quitApp();
225 
226     else if d == servicediscoveryui && c.getLabel().equals("Back") )
227     {
228       // go back to DeviceDiscoveryUI screen
229       display.setCurrentdevicediscoveryui );
230 
231     }
232   }
233 
234   /**
235    *
236    <p>Title: DiscoveryListener implementation that handle discovery response (callback)</p>
237    <p>Description: </p>
238    <p>Copyright: Copyright (c) 2003</p>
239    @author Ben Hui (www.benhui.net)
240    @version 1.0
241    */
242   class Listener implements DiscoveryListener
243   {
244     /**
245      * Implements DiscoveryListener interface.
246      * This function in invoked for each RemoteDevice discovered by JABWT.
247      * See JSR-82 API spec for documentation.
248      @param remoteDevice
249      @param deviceClass
250      */
251     public void deviceDiscovered(RemoteDevice remoteDevice,
252                                  DeviceClass deviceClass)
253     {
254       log("A remote Bluetooth device is discovered:");
255       Util.printRemoteDeviceremoteDevice, deviceClass );
256       // store the device in the list for later use
257       devices.addElementremoteDevice );
258       deviceClasses.addElementdeviceClass );
259     }
260 
261     /**
262      * Implements DiscoveryListener interface.
263      * This function is invoked when the device discovery is completed.
264      * See JSR-82 API spec for documentation.
265      @param complete
266      */
267     public void inquiryCompleted(int complete)
268     {
269       log("service discovery completed with return code:"+complete);
270       log(""+devices.size()+" devices are discovered");
271 
272 
273       if devices.size() == )
274       {
275         // cannot find any Bluetooth device, tell user about this
276         Alert alert = new Alert"Problem!""No Bluetooth device found", null, AlertType.INFO );
277         alert.setTimeout(3000);
278         devicediscoveryui.setMsg("[Press Inquiry]");
279         display.setCurrentalert, devicediscoveryui );
280 
281       else
282       {
283         // update the GUI list to reflect all the found devices
284         devicediscoveryui.showui();
285         display.setCurrentdevicediscoveryui );
286 
287       }
288 
289     }
290     /**
291      * Implements DiscoveryListener interface.
292      * This function is invoked when services are found on a RemoteDevice.
293      * See JSR-82 API spec for documentation.
294      @param transId
295      @param records
296      */
297     public void servicesDiscovered(int transId, ServiceRecord[] records)
298     {
299       log("Remote Bluetooth services is discovered:");
300       for int i=0; i< records.length;  i ++ )
301       {
302         ServiceRecord record = records[i];
303         Util.printServiceRecordrecord );
304         // store the service records in list for later use
305         services.addElementrecord );
306       }
307     }
308 
309     /**
310      * Implements DiscoveryListener interface.
311      * This function is invoked when service discovery is completed on a RemoteDevice.
312      * See JSR-82 API spec for documentation.
313      @param transId
314      @param complete
315      */
316     public void serviceSearchCompleted(int transId, int complete)
317     {
318       log("service discovery completed with return code:"+complete);
319       log(""+services.size()+" services are discovered");
320 
321       if complete == SERVICE_SEARCH_COMPLETED || complete ==  SERVICE_SEARCH_NO_RECORDS )
322       {
323         // reflect the GUI to show all found services
324         servicediscoveryui.showui();
325         display.setCurrent(servicediscoveryui);
326       else
327       {
328         // other possible complete values are
329         // SERVICE_SEARCH_DEVICE_NOT_REACHABLE
330         // SERVICE_SEARCH_ERROR
331         // SERVICE_SEARCH_TERMINATED
332         //
333         // tell user about the problem
334         Alert alert = new Alert"Problem!""Service Discovery incomplete", null, AlertType.ERROR );
335         alert.setTimeoutAlert.FOREVER );
336         display.setCurrentalert, devicediscoveryui );
337       }
338 
339     }
340 
341   // Listener
342 
343 }
Java2html
Benhui.net news
Feb 14, 2004 - New downloads from our Bluetooth section. BlueChat example application with full source code. Learn more! Bluetooth more! [more]
Feb 14, 2004 - Found out what SonyEricsson P900 has to offer for J2ME developers. Review our P900 developer review. [more]
Feb 14, 2004 - Check out Ben's latest Java Bluetooth development article at JDJ Feb issue. Get it off the shelf while it last. [more]
Dec 15, 2003 - Our Bluetooth section open! Check out our Bluetooth Browser, Code gallery, and tons of links. [more]
Nov 08, 2003 - Join us to chat with Michael Yuan. Learn more about Enterprise J2ME. [more]
Nov 08, 2003 - 35 more links added to our popular J2ME Master Links [more]
Nov 08, 2003 - MIDP 2.0 phone list is updated to include the latest and greatest phones. And with links, too! Check it out. [more]
Sept 21, 2003 - Add MIDP 2.0 phone list section. [more]
Aug 28, 2003 - Spy your mobile device even more with our Mobile Speed tool. [more]
Aug 22, 2003 - Spy your mobile device with our new Mobile Echo tool. [more]
Aug 22, 2003 - A new forum section is added to our links database. Questions? Dunno where to start? Start from here!
Aug 22, 2003 - Another 20 links added to our database. You have links to suggest? email us!

Aug 01, 2003 - the new benhui.net goes live! Fully updated with lots of J2ME links, UML diagrams, and special features.

Aug 01, 2003 - check out our latest featured phone - Nokia 3650 [more]

  

Featured Phone

 

Featured People

  

Featured Site

 

 

 

Copyright (c) 2003. BenHui.Net. All rights reserved.

All trademarks are owned by their respective companies.

Feedback to webmaster | Questions? | Privacy | Terms of Use