0

我正在尝试使用蓝牙制作一个 java android 应用程序,在列表视图中搜索所有配对或未配对的设备并连接到设备后显示结果时遇到了一些麻烦,在我的代码中我试图连接一个使用它的mac地址的设备,但它不起作用,我在文本视图中显示结果,知道吗????谢谢你。

public class Conexion_bluetooth extends Activity {
TextView out; 

// Debugging
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket mmSocket=null;
private static final String TAG = "BluetoothChat";
private static final boolean D = true;

private static final int REQUEST_ENABLE_BT = 3;

private BluetoothAdapter mBluetoothAdapter = null;

ListView lstDispositivos;
ListView lstDispositivos2;

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     if(D) Log.e(TAG, "+++ ON CREATE +++");

     // Set up the window layout
     setContentView(R.layout.activity_conexion_bluetooth);

     // Get local Bluetooth adapter
     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

     // If the adapter is null, then Bluetooth is not supported
     if (mBluetoothAdapter == null) {
         Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
         finish();
         return;
     }
 }

@Override
//Comprueba que el bluetooth esta conectado
public void onStart() {
    super.onStart();
    if(D) Log.e(TAG, "++ ON START ++");

    // Si el bluetooth no está activado muestra un mensaje solicitando permiso para activarle
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        Toast.makeText(this, "conectando...", Toast.LENGTH_LONG).show();

    }else{
        Toast.makeText(this, "conectado", Toast.LENGTH_LONG).show();
    }
}

public void buscar(View view){
    //TextView dispositivos = (TextView) findViewById(R.id.dispositivos);


    if (mBluetoothAdapter.isDiscovering()) {
        Toast.makeText(this, "\nCancel discovery...", Toast.LENGTH_LONG).show();
        mBluetoothAdapter.cancelDiscovery(); 
    }else{
        Toast.makeText(this, "\nStarting discovery...", Toast.LENGTH_LONG).show();
        //mBluetoothAdapter.
        mBluetoothAdapter.startDiscovery(); 
        Toast.makeText(this, "\nDone with discovery...", Toast.LENGTH_LONG).show();
    }

    final TextView dispositivos = (TextView) findViewById(R.id.dispositivos);
    String dispositivo[] = new String[]{};
    final Vector<String> dispositivosBT = new Vector<String>();
    //final int dispEncontrados=0;

    // Create a BroadcastReceiver for ACTION_FOUND
    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            //String dispositivosBT[] = new String[]{};
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //setContentView(R.layout.dispositivos_bluetooth);//determinamos que al iniciar la aplicacion aparezca esta pantalla
                    // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    //  Add the name and address to an array adapter to show in a ListView
                    dispositivos.append("\n" + device.getName() + "\n" + device.getAddress());
            }
        }
    };
    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

    //dispositivosBT = new String[dispositivos.length()];
    //final ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, dispositivosBT);
    final TextView dispositivosSincronizados = (TextView) findViewById(R.id.dispositivosSincronizados);
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) {
            // Add the name and address to an array adapter to show in a ListView
            dispositivosSincronizados.append("\n" + device.getName() + "\n" + device.getAddress());
        }
    }
}
public void paraBusqueda(View view){
    if (mBluetoothAdapter.isDiscovering()) {
        Toast.makeText(this, "\nCancel discovery...", Toast.LENGTH_LONG).show();
        mBluetoothAdapter.cancelDiscovery();
    }else{
        Toast.makeText(this, "\nis not discovering...", Toast.LENGTH_LONG).show();
    }

}

public void pararBluetooth(){
    if (mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);        
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_conexion_bluetooth, menu);
    return true;
}

public void conectar(View view){
    String address = "00:15:83:07:d1:14";
 device = mBluetoothAdapter.getRemoteDevice(address);
 Toast.makeText(getApplicationContext(), "cONNECTING", Toast.LENGTH_SHORT).show();
 try {

 mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
 mmSocket.connect();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
}

}

4

2 回答 2

0

最近我们用蓝牙玩了一些应用程序。我不是安卓专家。您可以尝试以下方法。
1.检查你的蓝牙设备的UUID
2.连接到蓝牙需要在一个单独的线程中
3.在调试模式下运行应用程序并检查异常或错误。
请参阅android 蓝牙文档
如果您仍然有同样的问题,请查看蓝牙示例应用程序,否则我将发送我为建立连接而编写的代码。

问候
斯里尼

于 2012-07-09T11:59:12.727 回答
0

使用AsyncTask我们可以建立蓝牙连接。

 public class BluetoothConnectionActivity extends Activity {

    private Button connectButton;

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            connectButton = (Button) findViewById(R.id.connectButton);
            connectButton.setOnclickListener(View.onClickListener() {
                        @Override
                    public void onClick(View v) {
                           String address = "00:15:83:07:d1:14";
                   new ConnectAsyncTask(address).execute();
                    }
                    });


        }

    private class ConnectAsyncTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected void onPostExecute(Boolean isConnected) {
            Toast.makeText(getApplicationContext(), "Connecting...",
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        protected Boolean doInBackground(String... param) {
            BluetoothDevice device = BluetoothAdapter
                    .getDefaultBluetoothAdapter().getRemoteDevice(param[0]);
            try {
                BluetoothSocket mmSocket = device
                        .createRfcommSocketToServiceRecord(MY_UUID);
                mmSocket.connect();
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("BluetoothConnectivity", "ERROR:" + e.getMessage());
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean isConnected) {
            if (isConnected) {
                Toast.makeText(getApplicationContext(), "Connected",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Failed to connected",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}

问候斯里尼

于 2012-07-10T05:11:44.483 回答