我正在尝试将我的 android 设备与蓝牙兼容设备连接。我知道这个设备的 MAC 地址,你可以在下面的代码中看到。我也做了几个Toasts
只是为了验证代码中的步骤。看来我设法创建了tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
我假设这是因为 Toast 在这行代码中引发了一条消息,说一些蓝牙对象地址:
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
tmp.connect();
但是当我使用 API 级别 15,android 4.0时,代码在语义上失败了
这是我的一段代码
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleConnectAndroidActivity extends Activity {
final static String toast = "IAM HERE";
final static String TAG ="SimpleConnect";
UUID MY_UUID;
BluetoothDevice bd;
BluetoothAdapter ba;
Button connectButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
ba = BluetoothAdapter.getDefaultAdapter();
connectButton = (Button)findViewById(R.id.button1);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
boolean b = ba.checkBluetoothAddress("00:1B:DC:0F:EC:7E");
BluetoothSocket tmp = null;
//If valid bluetoothAddress
if(b) {
final BluetoothDevice device = ba.getRemoteDevice("00:1B:DC:0F:EC:7E"); //Getting the Verifier Bluetooth
//Trying to create a RFCOMM socket to the device
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
try {
tmp.connect();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No connection was made! Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
//Print out the sockets name
String test = tmp.toString();
Toast.makeText(getApplicationContext(), "The bluetooth socket: " +test, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "FALSE, No bluetooth device with this address", Toast.LENGTH_LONG).show();
}
}
});
}
}
我知道这应该在一个单独的线程中完成,是的,我阅读了 Google 提供的蓝牙聊天示例。
有人可以帮我吗?
编辑
这是我从 LogCat 得到的唯一信息:
07-06 10:10:22.085: V/BluetoothSocket.cpp(14019): ...fd 63 created (RFCOMM, lm = 26)
编辑 2
好的,现在有一个新错误,但它是一个更好的错误。当我按下连接按钮时,手机要求输入密码以配对设备,但它已经配对!第二次配对后,错误提示:连接被拒绝,另一个异常提示超时。