在Android 2.0中查找UUID

时间:2012-06-12 19:13:37

标签: android bluetooth uuid

我正在编写一个需要在Android 2.0中运行的程序。我目前正在尝试将我的Android设备连接到嵌入式蓝牙芯片。我已经获得了使用fetchuidsWithSDP()或getUuids()的信息,但我读过的页面解释说这些方法隐藏在2.0 SDK中,必须使用反射调用。我不知道这意味着什么,也没有解释。给出了示例代码,但背后的解释很少。我希望有人可以帮助我理解这里的实际情况,因为我对Android开发很新。

String action = "android.bleutooth.device.action.UUID";
IntentFilter filter = new IntentFilter( action );
registerReceiver( mReceiver, filter );

我读到的页面也说,在第一行蓝牙是故意拼写“bleutooth”。如果有人能够解释这一点,我会很感激,除非开发人员输入错字,否则对我来说没有任何意义。

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive( Context context, Intent intent ) {
    BluetoothDevice deviceExtra = intent.getParcelableExtra("android.bluetooth.device.extra.Device");
    Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");
}

};

我无法掌握如何为嵌入式蓝牙芯片找到正确的UUID。如果有人能提供帮助,我们将非常感激。

编辑:我将添加我的onCreate()方法的其余部分,以便您可以看到我正在使用的内容。

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set up window View
    setContentView(R.layout.main);

    // Initialize the button to scan for other devices.
    btnScanDevice = (Button) findViewById( R.id.scandevice );

    // Initialize the TextView which displays the current state of the bluetooth
    stateBluetooth = (TextView) findViewById( R.id.bluetoothstate );
    startBluetooth();

    // Initialize the ListView of the nearby bluetooth devices which are found.
    listDevicesFound = (ListView) findViewById( R.id.devicesfound );
    btArrayAdapter = new ArrayAdapter<String>( AndroidBluetooth.this,
            android.R.layout.simple_list_item_1 );
    listDevicesFound.setAdapter( btArrayAdapter );

    CheckBlueToothState();

    // Add an OnClickListener to the scan button.
    btnScanDevice.setOnClickListener( btnScanDeviceOnClickListener );

    // Register an ActionFound Receiver to the bluetooth device for ACTION_FOUND
    registerReceiver( ActionFoundReceiver, new IntentFilter( BluetoothDevice.ACTION_FOUND ) );

    // Add an item click listener to the ListView
    listDevicesFound.setOnItemClickListener( new OnItemClickListener()
    {
      public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
      {
          // Save the device the user chose.
          myBtDevice = btDevicesFound.get( arg2 );

          // Open a socket to connect to the device chosen.
          try {
              btSocket = myBtDevice.createRfcommSocketToServiceRecord( MY_UUID );
          } catch ( IOException e ) {
              Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
          } catch ( NullPointerException e ) {
              Log.e( "Bluetooth Socket", "Null Pointer One" );
          }

          // Cancel the discovery process to save battery.
          myBtAdapter.cancelDiscovery();

          // Update the current state of the Bluetooth.
          CheckBlueToothState();

          // Attempt to connect the socket to the bluetooth device.
          try {
              btSocket.connect();                 
              // Open I/O streams so the device can send/receive data.
              iStream = btSocket.getInputStream();
              oStream = btSocket.getOutputStream();
          } catch ( IOException e ) {
              Log.e( "Bluetooth Socket", "IO Exception" );
          } catch ( NullPointerException e ) {
              Log.e( "Bluetooth Socket", "Null Pointer Two" );
          }
      } 
  });
}

2 个答案:

答案 0 :(得分:5)

您可能最好使用同步版本,因此您无需处理设置BroadcastReceiver的所有活动部分。由于您始终在发现之后执行此操作,因此缓存的数据将始终是新鲜的。

这里将UUID数据封装到方法中的功能。此代码位于您链接的博客文章的评论之一:

//In SDK15 (4.0.3) this method is now public as
//Bluetooth.fetchUuisWithSdp() and BluetoothDevice.getUuids()
public ParcelUuid[] servicesFromDevice(BluetoothDevice device) {
    try {
        Class cl = Class.forName("android.bluetooth.BluetoothDevice");
        Class[] par = {};
        Method method = cl.getMethod("getUuids", par);
        Object[] args = {};
        ParcelUuid[] retval = (ParcelUuid[]) method.invoke(device, args);
        return retval;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

然后,您可以在代码中的任何位置调用此方法,向其传递BluetoothDevice并返回该设备服务的UUID数组(通常对于小型嵌入式堆栈,该数组仅为1项);类似的东西:

  // Save the device the user chose.
  myBtDevice = btDevicesFound.get( arg2 );
  //Query the device's services
  ParcelUuid[] uuids = servicesFromDevice(myBtDevice);

  // Open a socket to connect to the device chosen.
  try {
      btSocket = myBtDevice.createRfcommSocketToServiceRecord(uuids[0].getUuid());
  } catch ( IOException e ) {
      Log.e( "Bluetooth Socket", "Bluetooth not available, or insufficient permissions" );
  } catch ( NullPointerException e ) {
      Log.e( "Bluetooth Socket", "Null Pointer One" );
  }

在上面发布的块中。

作为旁注,以您的方式调用所有这些代码将使您的应用程序稍后感到悲伤。调用connect()并获取流的代码块应该在后台线程上完成,因为该方法将阻塞一段时间,并且在主线程上调用此代码将暂时冻结您的UI。您应该将该代码移动到AsyncTaskThread,例如SDK中的BluetoothChat示例。

HTH

答案 1 :(得分:-1)

我也面临同样的问题,这就是我为Android 2.3.3解决它的方法。我认为同样的解决方案也适用于Android 2.2。

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @SuppressLint("NewApi")
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Toast.makeText(getApplicationContext(),"Device: "+device.getName(),Toast.LENGTH_SHORT).show();
            devices.add(device.getName() + "\n" + device.getAddress());
            list.add(device);

        }
        else if(BluetoothDevice.ACTION_UUID.equals(action)){
            Toast.makeText(getApplicationContext(),"I am Here",Toast.LENGTH_SHORT).show();
        }
        else {
            if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Toast.makeText(getApplicationContext(),"Done Scanning..",Toast.LENGTH_SHORT).show();
                Iterator<BluetoothDevice> itr = list.iterator();
                while(itr.hasNext())
                {
                    BluetoothDevice dev=itr.next();
                    if(dev.fetchUuidsWithSdp())
                    {
                        Parcelable a[]=dev.getUuids();
                        Toast.makeText(getApplicationContext(),dev.getName()+":"+a[0],Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }       
    }
};