1

我正在编写一个需要在 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 );

我阅读的页面还说,在第一行中,蓝牙故意拼写为“蓝牙”。如果有人能解释这一点,我将不胜感激,除非开发人员打错了字,否则这对我来说毫无意义。

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" );
          }
      } 
  });
}
4

2 回答 2

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;
    }
}

然后,您可以在代码中的任何位置调用此方法,将其传递 aBluetoothDevice并获取该设备服务的 UUID 数组(通常对于小型嵌入式堆栈,该数组只有一项);就像是:

  // 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。您应该将该代码移动到SDK 中AsyncTaskThreadBluetoothChat 示例中。

高温高压

于 2012-06-13T15:01:21.487 回答
-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();
                    }
                }
            }
        }       
    }
};
于 2014-05-23T08:07:49.930 回答