1

Android 2.0 で実行する必要があるプログラムを作成しています。現在、Android デバイスを組み込みの Bluetooth チップに接続しようとしています。fetchuidsWithSDP() または getUuids() の使用に関する情報が提供されましたが、私が読んだページでは、これらのメソッドは 2.0 SDK に隠されているため、リフレクションを使用して呼び出す必要があると説明されていました。意味がわからないし、説明もない。サンプルコードが提供されていますが、その背後にある説明はほとんどありません。私は Android 開発に非常に慣れていないので、誰かがここで実際に何が起こっているのかを理解するのを手伝ってくれることを望んでいました.

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

私が読んだページには、最初の行で bluetooth が意図的に「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");
}

};

埋め込まれた bluetooth チップの正しい 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データをメソッドにカプセル化する機能を示します。このコードは、リンクしたブログ投稿のコメントの1つに含まれていました。

//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が一時的にフリーズするためです。そのコードを、SDKのBluetoothChatサンプルなどAsyncTaskに移動する必要があります。Thread

HTH

于 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 に答える