⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 btdiscovery.java

📁 j2me的手机源代码
💻 JAVA
字号:
/*****************************************************************************
 COPYRIGHT All rights reserved Sony Ericsson Mobile Communications AB 2005.

 The software is the copyrighted work of Sony Ericsson Mobile Communications AB.
 The use of the software is subject to the terms of the end-user license
 agreement which accompanies or is included with the software. The software is
 provided "as is" and Sony Ericsson specifically disclaim any warranty or
 condition whatsoever regarding merchantability or fitness for a specific
 purpose, title or non-infringement. No warranty of any kind is made in
 relation to the condition, suitability, availability, accuracy, reliability,
 merchantability and/or non-infringement of the software provided herein.
 *****************************************************************************/

import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import java.io.IOException;
import java.util.*;

/*
 * Class BTDiscovery used for searching of near-by devices.
*/
class BTDiscovery implements DiscoveryListener, Runnable
{
  BTConectionObserver observer;
  List refDeviceList;

  private static long UDI_L2CAP = 0x0100;

  // Bluetooth discovery
  private DiscoveryAgent discoveryAgent;
  private Hashtable bluetoothDevices = new Hashtable();
  private ServiceRecord record;
  private boolean foundService = false;


  public BTDiscovery(BTConectionObserver aObserver, List aDeviceList)
  {
    observer = aObserver;
    refDeviceList = aDeviceList;
    System.out.println("BTDiscovery created");
  }

  public void startBluetoothDiscovery()
  {
    Thread t = new Thread(this);
    t.start();
    System.out.println("BTDiscovery started");
  }

  public void run()
  {
    bluetoothDiscovery();
  }

  // Start a search for BT services.
  // handling when nothing was selected should be added
  public void searchForServices()
  {
    foundService = false;
    System.out.println("Searching for services ...");
    // Get Selected device
    int index = refDeviceList.getSelectedIndex();
    if (index == -1) {
      System.out.println("Nothing selected!");
      return;
    }
    try {
      String devName = refDeviceList.getString(index);
      RemoteDevice remoteDevice;
      remoteDevice = (RemoteDevice)bluetoothDevices.get(devName);
      if (remoteDevice == null) {
        System.out.println("No remote device!");
        return;
      }
      // Look for Services on remoteDevice
      System.out.println("Starting inquery on " + devName);
      /*
       * Add the UUID for L2CAP to make sure that the service record
       * found will support L2CAP.  This value is defined in the
       * Bluetooth Assigned Numbers document.
       */
      UUID[] searchList = { new UUID(UDI_L2CAP), 
                            new UUID(observer.MY_SERVICE_NUMBER, false) };
      try {
        int trans = discoveryAgent.searchServices(null, searchList, remoteDevice, this);
      }
      catch (BluetoothStateException e) {
        System.out.println("EDis01: " + e);
      }
    }
    catch (Exception e) {
      System.out.println("EDis02: " + e);
    }
  }

  public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
  {
    try {
      System.out.println("deviceDisc: " + btDevice.getFriendlyName(false));
      // Add Device to table
      bluetoothDevices.put(btDevice.getFriendlyName(false), btDevice);
    }
    catch (Exception e) {
      System.out.println("EDis03: " + e);
    }
  }

  public void servicesDiscovered(int transID, ServiceRecord[] servRecord)
  {
    System.out.println("servDisc: " + transID + " length = " + servRecord.length);
    int attribs[];
    DataElement data;
    if( foundService ) {
      return;
    }
    for( int i=0; i < servRecord.length; ++i )
    {
      try {
        attribs = servRecord[i].getAttributeIDs();
        for (int j=0; j < attribs.length; j++) {
          System.out.println(" " + attribs[j]);
        }
        String conURL = servRecord[i].getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT , false );
        int index = conURL.indexOf(':');
        String protocol= conURL.substring(0, index);
        if (protocol.equals("btl2cap")) {
          record = servRecord[i];
          System.out.println("record URL=" + conURL );
          foundService = true;
          break;
        }
      }
      catch (Exception e) {
        System.out.println("EDis04: " + e);
      }
    }
  }

  public void serviceSearchCompleted(int transID, int respCode)
  {
    System.out.println("serviceSearchComplete! " + transID + " " + respCode);
    // Start the Connection using the located service.
    if (foundService) {
      observer.createClient(record);
    }
  }

  public void inquiryCompleted(int discType)
  {
    System.out.println("inquiryCompleted! " + discType);
    // Remove old entries
    for( int i=refDeviceList.size(); i > 0; i-- ) {
      refDeviceList.delete(i-1);
    }      
    // Append keys from table
    for( Enumeration e = bluetoothDevices.keys(); e.hasMoreElements(); )
    {
      try {
        String name = (String) e.nextElement();
        refDeviceList.append( name, null );
      }
      catch (Exception exception) {}
    } 
  }

  private void bluetoothDiscovery() 
  {
    System.out.println("bluetoothDiscovery() called");
    LocalDevice localDevice;
    try {
      localDevice = LocalDevice.getLocalDevice();
    }
    catch (BluetoothStateException e) {
      System.out.println("BluetoothStateException: " + e);
      return;
    }
    discoveryAgent = localDevice.getDiscoveryAgent();
    RemoteDevice devices[]; 
    try {
      devices = discoveryAgent.retrieveDevices(DiscoveryAgent.CACHED);
      if (devices != null)
      {
        for (int i=0; i < devices.length; i++) {
          bluetoothDevices.put(devices[i].getFriendlyName(false), devices[i]);
          System.out.println( "Device (cached): " +
                              devices[i].getFriendlyName(false) + 
                              " " + devices[i].getBluetoothAddress() );
        }
      }
      devices = discoveryAgent.retrieveDevices(DiscoveryAgent.PREKNOWN);
      if (devices != null)
      {
        for (int i=0; i < devices.length; i++) {
          bluetoothDevices.put(devices[i].getFriendlyName(false), devices[i]);
          System.out.println( "Device (cached): " +
                              devices[i].getFriendlyName(false) + 
                              " " + devices[i].getBluetoothAddress() );
        }
      }
    }
    catch(IOException e) {
      System.out.println("EDis05: " + e);
    }
    try {
      discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
    }
    catch (BluetoothStateException e) {
      System.out.println("EDis06: " + e);
    }
    System.out.println("return from bluetoothDiscovery()");
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -