|
|
|
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.setCurrent( devicediscoveryui );
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 showExceptionAlert( Exception e, Screen next_screen )
100 {
101 Alert alert = new Alert( "Problem", "Exception: "+e.getClass().getName()+" "+e.getMessage(), null, AlertType.ERROR );
102 alert.setTimeout( Alert.FOREVER );
103 display.setCurrent( alert, 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.startInquiry( DiscoveryAgent.GIAC, new Listener() );
123
124
125 } catch ( BluetoothStateException e )
126 {
127 e.printStackTrace();
128
129 showExceptionAlert( e, 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[]{0x0000, 0x0001, 0x0002, 0x0003, 0x0004,
153 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D,
154 0x0100, 0x0101, 0x0102, 0x0200, 0x0201,
155 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307, 0x0308, 0x0309,
156 0x030A, 0x030B, 0x030C, 0x030D, 0x030E, 0x0310, 0x0311, 0x0312, 0x0313 };
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.searchServices( attr, // attributes to retrieve from remote device
163 new UUID[]{ new UUID( 0x0100 ) }, // 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 showExceptionAlert( e, 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 == -1 || selectedDevice >= devices.size() )
206 {
207 Alert alert = new Alert( "Problem", "No device selected", null, AlertType.ERROR );
208 alert.setTimeout( Alert.FOREVER );
209 display.setCurrent( alert, devicediscoveryui );
210
211 return;
212 }
213
214
215 RemoteDevice remoteDevice = (RemoteDevice)
216 devices.elementAt(selectedDevice);
217
218 // perform service discovery
219 doDiscoverService( remoteDevice );
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.setCurrent( devicediscoveryui );
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.printRemoteDevice( remoteDevice, deviceClass );
256 // store the device in the list for later use
257 devices.addElement( remoteDevice );
258 deviceClasses.addElement( deviceClass );
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() == 0 )
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.setCurrent( alert, devicediscoveryui );
280
281 } else
282 {
283 // update the GUI list to reflect all the found devices
284 devicediscoveryui.showui();
285 display.setCurrent( devicediscoveryui );
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.printServiceRecord( record );
304 // store the service records in list for later use
305 services.addElement( record );
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.setTimeout( Alert.FOREVER );
336 display.setCurrent( alert, 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] |
|