在Android 2.0的查找的UUID [英] Finding UUIDs in Android 2.0

查看:147
本文介绍了在Android 2.0的查找的UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个程序,它需要在Android 2.0的运行。目前我正在试图以我的Andr​​oid设备连接到嵌入式蓝牙芯片。我一直在给定的信息为使用fetchuidsWithSDP(),或getUuids(),但我阅读网页解释说,这些方法都隐藏在2.0 SDK,并且必须使用反射调用。我不知道这意味着什么,也没有解释。有鉴于例如code,但其背后很少的解释。我希望有人能帮助我了解什么是真正回事,因为我很新的Andr​​oid开发。

 字符串操作=android.bleutooth.device.action.UUID;
IntentFilter的过滤器=新IntentFilter的(动作);
registerReceiver(mReceiver,过滤器);
 

我也看到该网页说,在第一线蓝牙拼写bleutooth的宗旨。如果任何人都可以解释的是,我会AP preciate的,以及它是没有意义的我,除非开发人员做了一个错字。

 私人最终的BroadcastReceiver mReceiver =新的BroadcastReceiver(){
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
    BluetoothDevice类deviceExtra = intent.getParcelableExtra(android.bluetooth.device.extra.Device);
    Parcelable [] uuidExtra = intent.getParcelableArrayExtra(android.bluetooth.device.extra.UUID);
}
 

};

我有麻烦抓我究竟是如何找到正确的UUID我的嵌入式蓝牙芯片。如果有人能够帮助这将会是很大的AP preciated。

编辑:我要加我的onCreate()方法的其余部分,所以你可以看到我正在使用。

 公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);

    //设置窗口中查看
    的setContentView(R.layout.main);

    //初始化按钮扫描其他设备。
    btnScanDevice =(按钮)findViewById(R.id.scandevice);

    //初始化其中显示了蓝牙的当前状态的TextView的
    stateBluetooth =(TextView中)findViewById(R.id.bluetoothstate);
    startBluetooth();

    //初始化这是发现附近的蓝牙设备的ListView控件。
    listDevicesFound =(ListView控件)findViewById(R.id.devicesfound);
    btArrayAdapter =新的ArrayAdapter<字符串>(AndroidBluetooth.this,
            android.R.layout.simple_list_item_1);
    listDevicesFound.setAdapter(btArrayAdapter);

    CheckBlueToothState();

    //添加一个OnClickListener的扫描按钮。
    btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);

    //注册一个ActionFound接收器的蓝牙设备ACTION_FOUND
    registerReceiver(ActionFoundReceiver,新的IntentFilter(BluetoothDevice.ACTION_FOUND));

    //添加一个项目单击监听到ListView
    listDevicesFound.setOnItemClickListener(新OnItemClickListener()
    {
      公共无效onItemClick(适配器视图<>为arg0,查看ARG1,INT ARG2,长ARG3)
      {
          //保存用户选择的设备。
          myBtDevice = btDevicesFound.get(ARG2);

          //打开一个套接字连接到所选择的设备。
          尝试 {
              btSocket = myBtDevice.createRfcommSocketToServiceRecord(MY_UUID);
          }赶上(IOException异常E){
              Log.e(蓝牙套接字,蓝牙无法使用,或者没有足够的权限);
          }赶上(NullPointerException异常E){
              Log.e(蓝牙套接字,空指针一);
          }

          //取消的发现过程,以节省电池。
          myBtAdapter.cancelDiscovery();

          //更新蓝牙的当前状态。
          CheckBlueToothState();

          //尝试插座连接到蓝牙设备。
          尝试 {
              btSocket.connect();
              //打开I / O流,以便设备可以发送/接收数据。
              的IStream = btSocket.getInputStream();
              ostream的= btSocket.getOutputStream();
          }赶上(IOException异常E){
              Log.e(蓝牙套接字,IO异常);
          }赶上(NullPointerException异常E){
              Log.e(蓝牙套接字,空指针二);
          }
      }
  });
}
 

解决方案

你可能会更好过使用同步的版本,所以你不必处理设置的所有运动部件的 BroadcastReceiver的。因为你总是在发现的高跟鞋做这个,缓存的数据永远是新鲜的。

让封装成一个方法的UUID数据,这里的功能。这code是在你链接的博客文章的评论之一:

  //在SDK15(4.0.3)这种方法是现在公众
//Bluetooth.fetchUuisWithSdp()和BluetoothDevice.getUuids()
公共ParcelUuid [] servicesFromDevice(BluetoothDevice类设备){
    尝试 {
        类的cl =的Class.forName(android.bluetooth.BluetoothDevice);
        类[]面值= {};
        方法方法= cl.getMethod(getUuids,标准杆);
        [对象]的args = {};
        ParcelUuid [] RETVAL =(ParcelUuid [])method.invoke(设备参数);
        返回RETVAL;
    }赶上(例外五){
        e.printStackTrace();
        返回null;
    }
}
 

您就可以在任何地方调用此方法在code,传递一个 BluetoothDevice类和找回的UUID的数组,该设备提供的服务(通常为小型嵌入式堆叠阵列只有1个项目);是这样的:

  //保存用户选择的设备。
  myBtDevice = btDevicesFound.get(ARG2);
  //查询设备的服务
  ParcelUuid []的UUID = servicesFromDevice(myBtDevice);

  //打开一个套接字连接到所选择的设备。
  尝试 {
      btSocket = myBtDevice.createRfcommSocketToServiceRecord(UUID的[0] .getUuid());
  }赶上(IOException异常E){
      Log.e(蓝牙套接字,蓝牙无法使用,或者没有足够的权限);
  }赶上(NullPointerException异常E){
      Log.e(蓝牙套接字,空指针一);
  }
 

在你上面贴块。

作为一个侧面说明,称这一切code。在你会让你的应用程序后伤心的方式。的code调用块连接()并获得流应在后台线程中完成的,因为这种方法会阻塞一段时间,调用此$ C在主线程$ C将临时冻结您的UI。你应该将那个code到的AsyncTask 像SDK中BluetoothChat样呢。

心连心

I am writing a program which needs to be run in Android 2.0. I am currently trying to connect my android device to an embedded bluetooth chip. I have been given information as to use fetchuidsWithSDP(), or getUuids(), but the page I read explained that these methods are hidden in the 2.0 SDK, and must be called using reflection. I have no idea what that means and there is no explanation. There is example code given, but very little explanation behind it. I was hoping someone could help me understand what is actually going on here, as I am very new to Android development.

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

The page I read also says that in the first line bluetooth is spelled "bleutooth" on purpose. If anyone can explain that, I would appreciate that as well as it makes no sense to me, unless the developers made a typo.

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

};

I am having trouble grasping how exactly I find the correct UUID for my embedded bluetooth chip. If anyone could help it'd be greatly appreciated.

EDIT: I am going to add the rest of my onCreate() method so you can see what I'm working with.

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

解决方案

You're probably better off using the synchronous version so you don't have to deal with all the moving parts of setting up the BroadcastReceiver. Since you are always doing this on the heels of discovery, the cached data will always be fresh.

Here the functionality of getting the UUID data encapsulated up into a method. This code was in one of the comments of the blog post you linked:

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

You can then call this method anywhere in your code, passing it a BluetoothDevice and getting back an array of UUIDs for that device's services (typically for small embedded stacks the array is only 1 item); something like:

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

in the block you posted above.

As a side note, calling all this code in the manner you have will make your application sad later. The block of code calling connect() and obtaining the streams should be done on a background thread because that method will block for a period of time and calling this code on the main thread will freeze your UI temporarily. You should move that code into an AsyncTask or a Thread like the BluetoothChat sample in the SDK does.

HTH

这篇关于在Android 2.0的查找的UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆