您的位置:首页 > 移动开发 > Android开发

Android·蓝牙通信实现

2017-04-14 13:14 253 查看
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
@BindView(R.id.button)
Button button;
@BindView(R.id.button_client)
Button buttonClient;
@BindView(R.id.lvDevices)
ListView lvDevices;
@BindView(R.id.ConstraintLayout)
android.support.constraint.ConstraintLayout ConstraintLayout;
@BindView(R.id.et_client)
EditText etClient;

private String Tag = "MainActivity";
private BluetoothAdapter mBluetoothAdapter;
private List<String> bluetoothDevices = new ArrayList<String>();
private ArrayAdapter<String> arrayAdapter;
private final UUID MY_UUID = UUID
.fromString("abcd1234-ab12-ab12-ab12-abcdef123456");//随便定义一个
private BluetoothSocket clientSocket;
private BluetoothDevice device;
private OutputStream os;
private AcceptThread acceptThread;
private final String NAME = "Bluetooth_Socket";
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
private InputStream is;//输入流
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), String.valueOf(msg.obj));

super.handleMessage(msg);
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
mBluetoothAdapter.enable();
acceptThread = new AcceptThread();
acceptThread.start();
// 设置广播信息过滤
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setProgressBarVisibility(true);
setTitle("正在扫描……");
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
setTitle("从新扫描……");
}
mBluetoothAdapter.startDiscovery();
}
});
buttonClient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
os.write(etClient.getText().toString().trim().getBytes("utf-8"));
etClient.setText("");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
bluetoothDevices.add(device.getName() + ":" + device.getAddress());
}
}
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, bluetoothDevices);
lvDevices.setAdapter(arrayAdapter);
lvDevices.setOnItemClickListener(this);//Activity实现OnItemClickListener接口
//每搜索到一个设备就会发送一个该广播
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(receiver, filter);
//当全部搜索完后发送该广播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, filter);
}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//如果找到这个设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//获得这个设备的信息
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//如果没有被配对过,再添加
boolean getname = false;
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//查看是否有添加过
for (int i = 0; i < bluetoothDevices.size(); i++) {
if (bluetoothDevices.get(i).equals(device.getName() + ":" + device.getAddress())) {
getname = true;
}
}
if (!getname) {
bluetoothDevices.add(device.getName() + ":" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
}
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setTitle("扫描完成");
}
}
};

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = arrayAdapter.getItem(position);
String address = s.substring(s.indexOf(":") + 1).trim();//把地址解析出来
//主动连接蓝牙服务端
try {
//判断当前是否正在搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
try {
if (device == null) {
//获得远程设备
device = mBluetoothAdapter.getRemoteDevice(address);
}
if (clientSocket == null) {
Log.e(Tag, "clientSocket is not null");

//创建客户端蓝牙Socket
clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
//开始连接蓝牙,如果没有配对则弹出对话框提示我们进行配对
clientSocket.connect();
//获得输出流(客户端指向服务端输出文本)
os = clientSocket.getOutputStream();
}
} catch (Exception e) {
}
if (os != null) {
Log.e(Tag, "os is not null");
//往服务端写信息
os.write("蓝牙信息来了".getBytes("utf-8"));
}
} catch (Exception e) {
}
}

class AcceptThread extends Thread {
public AcceptThread() {
try {
serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (Exception e) {
}
}

public void run() {
try {
socket = serverSocket.accept();
is = socket.getInputStream();
//循环读取数据
while (true) {
Log.e(Tag, "1");
byte[] buffer = new byte[1024];
Log.e(Tag, "2");
//等待获取数据
int count = is.read(buffer);
Log.e(Tag, "3");
Message msg = new Message();
Log.e(Tag, "4");
msg.obj = new String(buffer, 0, count, "utf-8");
Log.e(Tag, "5");
handler.sendMessage(msg);
Log.e(Tag, "6");
}
} catch (Exception e) {
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: