Join Now
Quality Rating:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)
Expertise Level:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)

This page was last modified 14:06, 11 December 2007.

Como encontrar dispositivos e serviços Bluetooth

From Forum Nokia Wiki

Para utilizar o protocolo Bluetooth em aplicações Java ME, seu dispositivo precisa implementar JSR-82, Bluetooth API.

Um dos principais desafios em aplicações Bluetooth é descobrir os endereços de conexão, para devices com serviços específicos disponíveis.

No próximo exemplo implementaremos este código usando uma classe chamada BtManager.

Vamos começar criando a classe e algumas variáveis para armazenar nossos resultados.

import java.util.Vector;
// bluetooth classes
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
 
public class BTManager implements DiscoveryListener {
  // used to store devices we found
  public Vector btDevicesFound;
  // used to store service information for each device 
  public Vector btServicesFound;
  
  public BTManager() {
    btDevicesFound = new Vector();
    btServicesFound = new Vector();
  }
 
  public int find(UUID[] aServices){        
    // search for devices
    findDevices();
    // search for services in the devices found
    findServices(aServices);
    return btDevicesFound.size();
  }

Como você pode ver, implementaremos a interface DiscoveryListener. Esta interface fornece todos os callbacks para nossas chamadas Bluetooth. Vamos começar procurando por dispositivos:

public int findDevices() {
    try {
      // cleans previous elements
      btDevicesFound.removeAllElements();
      // resets status variable
      isBTSearchComplete = false;
      LocalDevice local = LocalDevice.getLocalDevice();
      DiscoveryAgent discoveryAgent = local.getDiscoveryAgent();      
      // start discovery of new devices
      discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
      while ((!isBTSearchComplete)) {
        //waits for a fixed time, to avoid long search
        synchronized (this) {          
          this.wait(BTManager.BLUETOOTH_TIMEOUT);
        }
        // check if search is completed
        if (!isBTSearchComplete) {
          // search no yet completed so let's cancel it
          discoveryAgent.cancelInquiry(this);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    // returns the number of devices found
    return btDevicesFound.size();
  }
 
  public void deviceDiscovered(RemoteDevice remoteDevice,
      DeviceClass deviceClass) {
    btDevicesFound.addElement(remoteDevice);
  }
 
  public void inquiryCompleted(int param) {
    isBTSearchComplete = true;
    // notifies and wake main thread that device search is completed
    synchronized (this) {
      this.notify();
    }
  }

Agora que temos uma lista de dispositivos, vamos procurar apenas aqueles serviços que nos interessam:

public void findServices(UUID[] aServices) {
     // cleans previous elements
     btServicesFound.removeAllElements();
     try {
       LocalDevice local = LocalDevice.getLocalDevice();
       DiscoveryAgent discoveryAgent = local.getDiscoveryAgent();
      // discover services
      if (btDevicesFound.size() > 0) {
        for (int i = 0; i < btDevicesFound.size(); i++) {
          isBTSearchComplete = false;
          // adds a null element in case we don't found service
          btServicesFound.addElement(null);
          int transID = discoveryAgent.searchServices(null, aServices,
              (RemoteDevice) (btDevicesFound.elementAt(i)), this);
          // wait for service discovery ends
          synchronized (this) {
            this.wait(BTManager.BLUETOOTH_TIMEOUT);
          }
          if (!isBTSearchComplete) {
            discoveryAgent.cancelServiceSearch(transID);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }   
  }
 
 public void servicesDiscovered(int param, ServiceRecord[] serviceRecord) {
    int index = btServicesFound.size() - 1;    
    for (int i = 0; i < serviceRecord.length; i++) {
      btServicesFound.setElementAt(serviceRecord[i], index);
    }    
  }
 
 public void serviceSearchCompleted(int transID, int respCode) {
    isBTSearchComplete = true;
    // notifies and wake mains thread that service search is completed
    synchronized (this) {
      this.notify();
    }
  }

Depois que pegamos todos os dados armazenados em nossos Vectors, precisamos apenas adicionar dois novos métodos, um para buscar a URL de conexão e outro para obter o nome amigável (friendly name) do aparelho, pois para o usuário final endereços MAC de dispositivos Bluetooth não são muito úteis.

public String getDeviceName(int deviceID) {
    try {
      return ((RemoteDevice) btDevicesFound.elementAt(deviceID))
          .getFriendlyName(false);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "Error";
  }
 
  public String getServiceURL(int deviceID) {
    try {
      return ((ServiceRecord) btServicesFound.elementAt(deviceID))
          .getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "Error";
  }

Com esses últimos métodos completamos nossa classe Bluetooth finder. Você pode checar o código-fonte complete onde eu mostro um exemplo de como usá-lo para buscar por um dispositivo GPS Bluetooth.

Downloads

Related Discussions
Thread Thread Starter Forum Replies Last Post
BT dongle vtambe Symbian Tools & SDKs 2 2004-02-17 17:38
Data frame of nokia phones arc_hit Bluetooth Technology 1 2007-09-12 19:37
is it possible to connect Emulator with PC using bluetooth mmdfarook Mobile Java Tools & SDKs 1 2007-01-26 15:22
Bluetooth problem petokala Symbian Tools & SDKs 2 2002-08-26 06:22
getting started with C++ and Symbian doggett78 General Symbian C++ 1 2003-06-06 06:06
 
Powered by MediaWiki
     
     RDF Facets:
     
     
     qfnZtypeQUqfnTypeZCommunityContentQ
     qfnZtypeQUqfnTypeZWebpageQ
     qfnZtypeQUqfnTypeZWikiContentQ
     qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX