80,492
社区成员
发帖
与我相关
我的任务
分享
BluetoothSocket mSocket;
//上面这句我放在了onCreate的外面,其实我也不知道到底该放在哪
public void onconbtnClick(View v) {
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// device doesn't support Bluetooth
Toast.makeText(MainActivity.this,"该设备不支持蓝牙。" , Toast.LENGTH_SHORT).show();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
/*Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);*/
final AlertDialog.Builder normalDialog =
new AlertDialog.Builder(MainActivity.this);
normalDialog.setTitle("蓝牙未开启");
normalDialog.setMessage("蓝牙未开启。是否要开启蓝牙?");
normalDialog.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);
}
});
normalDialog.setNegativeButton("关闭",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//...To-do
}
});
normalDialog.show();
return;
}
String macAddr = "00:19:10:08:0D:6A";
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddr);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
try {
mSocket = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
mBluetoothAdapter.cancelDiscovery();
new Thread(){
@Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mSocket.connect();
} catch (IOException e) {
try {
mSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
super.run();
}
}.start();
try {
OutputStream os = mSocket.getOutputStream();
os.write("发送的数据".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
大佬有源码吗
帮忙给我看一下吧,能讲就顺便讲讲,谢谢