我正在尝试使用蓝牙制作一个java android应用程序,我有一些麻烦来显示搜索所有设备配对或不在列表视图中的结果并连接到设备,在我的代码我试图使用它的mac地址连接设备,但它不起作用,我在textview中显示结果,任何想法???? 谢谢。
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();
}
}
}
答案 0 :(得分:0)
最近我们用蓝牙进行了一些应用。我不是android的专家。您可以尝试以下方法
1.检查你的蓝牙设备的UUID
2.连接蓝牙需要在单独的线程中
3.在调试模式下运行app并检查异常或错误
请参阅android bluetooth documentation
如果您仍然遇到相同的问题,请查看蓝牙示例应用程序,否则我将发送我为编写连接而编写的代码
至于
作者Srini
答案 1 :(得分: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();
}
}
}
}
此致 作者Srini