区块链技术博客
www.b2bchain.cn

Android经典蓝牙与调料机或单片机通讯求职学习资料

本文介绍了Android经典蓝牙与调料机或单片机通讯求职学习资料,有助于帮助完成毕业设计以及求职,是一篇很好的资料。

对技术面试,学习经验等有一些体会,在此分享。

android 6.0以上需要动态获取位置权限
private void requestPermission() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, BluetoothParams.MY_PERMISSION_REQUEST_CONSTANT);

} else {
mController.findDevice(BlueToothActivity.this);

}

} else {
mController.findDevice(BlueToothActivity.this);
}
}
//oncreate中蓝牙初始化
//蓝牙核心对象获取
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
//注册蓝牙广播接收器
broadcastReceiver = new myBtReceiver();
IntentFilter intentFilter1 = new IntentFilter();
//开始查找
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
//结束查找
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//查找设备
intentFilter1.addAction(BluetoothDevice.ACTION_FOUND);
//设备扫描模式改变
intentFilter1.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
//绑定状态
intentFilter1.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter1.addAction(ACTIONFILTER);
intentFilter1.addAction(BluetoothDevice.ACTION_UUID);
registerReceiver(broadcastReceiver, intentFilter1);
broadcastReceiver.SetPairlistener(new MakePariBlueToothListener() {
@Override
public void whilePari(BluetoothDevice device) {

}

@Override
public void pairingSuccess(BluetoothDevice device) {
bluetoothFindAdapter.notifyDataSetChanged();//先配对成功,再连接
startConnect(device);

// Toast.makeText(“配对完成”);
}

@Override
public void cancelPari(BluetoothDevice device) {

}
});
mController = new BluetoothController();
if (!mController.isSupportBluetooth()) {
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“当前设备不支持或者没有打开蓝牙”);
return;
}
mController.turnOnBluetooth(this, 1);

public void startConnect(BluetoothDevice device) {

ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接中…”);
AppApplication.clientThread = new ClientThread(bluetoothAdapter, device, uiHandler);
threadExecutor.execute(AppApplication.clientThread);
AppApplication.clientThread.SetConnectBack(new ClientThread.ConnectBack() {
@Override
public void connectsuccess(BluetoothDevice device) {
// 通知 ui 连接的服务器端设备
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接成功!”);
Intent intent = new Intent(BlueToothActivity.this, MainActivity.class);
startActivity(intent);
}

@Override
public void connectfaile(BluetoothDevice device) {
Log.i(“TAGFAILURE”, “HHHH”);
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接失败,请检查对方蓝牙是否打开”);
// mtoast.toast(“连接失败,请检查服务端是否打开。”);
}

@Override
public void connecting(BluetoothDevice device) {
Log.i(“TAGIN”, “HHHHH”);
// mtoast.toast(“请稍等,正在连接中。”);
}
});
}
广播接收器
private class myBtReceiver extends BroadcastReceiver {
MakePariBlueToothListener mMakePariListener;

public void SetPairlistener(MakePariBlueToothListener makePariBlueToothListener) {
this.mMakePariListener = makePariBlueToothListener;
}

@Override
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
//蓝牙设备

//信号强度
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);

Log.i(“TAGTAGDEVICE”, “扫描到设备:” + bluetoothDevice.getName() + “–>” + bluetoothDevice.getAddress());
Message message = new Message();
message.what = DISCOVERY_DEVICE;
message.obj = bluetoothDevice;
uiHandler.sendMessage(message);

} else if (TextUtils.equals(action, BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {

int bondSate = bluetoothDevice.getBondState();
switch (bondSate) {
case BluetoothDevice.BOND_NONE:
Log.d(“TAGBOND3”, “已解除配对”);
mMakePariListener.cancelPari(bluetoothDevice);
break;
case BluetoothDevice.BOND_BONDING:
mMakePariListener.whilePari(bluetoothDevice);
break;

case BluetoothDevice.BOND_BONDED:
Log.d(“TAGBOND2”, “已配对”);
mMakePariListener.pairingSuccess(bluetoothDevice);
break;
}
} else if (ACTIONFILTER.equals(action)) {
try {
//1.确认配对
ClsUtils.setPairingConfirmation(bluetoothDevice.getClass(), bluetoothDevice, true);
//2.终止有序广播
Log.i(“order…”, “isOrderedBroadcast:” + isOrderedBroadcast() + “,isInitialStickyBroadcast:” + isInitialStickyBroadcast());
abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
//3.调用setPin方法进行配对…
boolean ret = ClsUtils.setPin(bluetoothDevice.getClass(), bluetoothDevice, pin);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
Message message = new Message();
message.what = START_DISCOVERY;
uiHandler.sendMessage(message);
} else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
Message message = new Message();
message.what = STOP_DISCOVERY;
message.obj = bluetoothDevice;
uiHandler.sendMessage(message);
}else if(TextUtils.equals(action, BluetoothDevice.ACTION_UUID)){
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);

if(uuidExtra == null) {
Log.i(“TAGUUID”,d.getName()+”hh”+uuidExtra.toString());
//Log.e(TAG, “UUID = null”);
}
}
}
}
工具类

public class BluetoothController {
private BluetoothAdapter bluetoothAdapter;

public BluetoothController() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

/*
是否支持蓝牙
*/
public boolean isSupportBluetooth() {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
return false;
} else {
return true;
}
}

public boolean getBluetoothStatus() {
assert (bluetoothAdapter != null);
return bluetoothAdapter.isEnabled();
}

public void turnOnBluetooth(Activity activity, int requestCode) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
}

public void turnOffBluetooth() {
bluetoothAdapter.disable();
}

/*
打开蓝牙可见性
*/
public void enableVisibly(Context context) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}

/*
是否在搜索
*/
public boolean isDiscovering() {
return bluetoothAdapter.isDiscovering();
}
public void cancelDiscovery() {
if (isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}

/*
查找设备
*/
public void findDevice(Activity activity) {
assert (bluetoothAdapter != null);
if (!isDiscovering()) {
if (Build.VERSION.SDK_INT >= 6.0) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
BluetoothParams.MY_PERMISSION_REQUEST_CONSTANT);
}
bluetoothAdapter.startDiscovery();
}

}

/**
*     * 获取远程设备
* <p>
*     *
* <p>
*     * @param address
* <p>
*     * @return
* <p>
*    
*/

public BluetoothDevice getRemoteDevice(String address) {

return bluetoothAdapter.getRemoteDevice(address);

}

/**
*     * 获取客户端设备
* <p>
*     * @param name
* <p>
*     * @param uuid
* <p>
*     * @return
* <p>
*    
*/

public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) {

try {

return bluetoothAdapter.listenUsingRfcommWithServiceRecord(name, uuid);

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

/*获取绑定设备

*/
public List<BluetoothDevice> getBondedDeviceList() {
return new ArrayList<>(bluetoothAdapter.getBondedDevices());
}
}

客户端发送与接收线程
public class ClientThread implements Runnable {
final String TAG = “ClientThread”;

BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;

Handler uiHandler;
Handler writeHandler;

public static BluetoothSocket socket;
OutputStream out;
InputStream in;
BufferedReader reader;

ConnectBack mConnectBack;
private Thread readerThread;

public void SetConnectBack(ConnectBack ConnectBack) {
this.mConnectBack = ConnectBack;
}

public ClientThread(BluetoothAdapter bluetoothAdapter, BluetoothDevice device,
Handler handler) {
this.bluetoothAdapter = bluetoothAdapter;
this.device = device;
this.uiHandler = handler;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(BluetoothParams.UUID));
} catch (IOException e) {
e.printStackTrace();
}
socket = tmp;
}

public BluetoothSocket getSocket() {
return socket;
}

@Override
public void run() {

Log.e(TAG, “—————– do client thread run()”);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}

try {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
socket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
socket.close();
mConnectBack.connectfaile(device);
return;
} catch (IOException closeException) {
}
mConnectBack.connectfaile(device);
return;
}
mConnectBack.connectsuccess(device);
ConcectReader();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, “————– exception”);
}
}

private void ConcectReader() throws IOException {
// out = null;
out = socket.getOutputStream();
// in = null;
in = socket.getInputStream();
//如果ble需要对事件广播进行监听;如果只是普通蓝牙直接使用接口函数即可,但是需要使用循环(for)不断读一个字节的函数,不能直接读一串。
new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
byte[] oneByte = new byte[1];
byte[] buffer = new byte[1024];
int len = 0;
String content;
try{
while ((len = in.read(oneByte, 0, 1)) != -1) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

public void send(String data) {

try {
out = socket.getOutputStream();
out.write(data.getBytes(“utf-8”));
Log.e(TAG, “———- write data ok ” + data);
} catch (IOException e) {
e.printStackTrace();
}
}

public void send(byte[] data) {
try {
out = socket.getOutputStream();
out.write(data);
Log.e(TAG, “———- write data ok ” + data);
} catch (IOException e) {
e.printStackTrace();
}
}

public interface ConnectBack {

public void connectsuccess(BluetoothDevice device);

public void connectfaile(BluetoothDevice device);

public void connecting(BluetoothDevice device);
}

}

android 6.0以上需要动态获取位置权限
private void requestPermission() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, BluetoothParams.MY_PERMISSION_REQUEST_CONSTANT);

} else {
mController.findDevice(BlueToothActivity.this);

}

} else {
mController.findDevice(BlueToothActivity.this);
}
}
//oncreate中蓝牙初始化
//蓝牙核心对象获取
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
//注册蓝牙广播接收器
broadcastReceiver = new myBtReceiver();
IntentFilter intentFilter1 = new IntentFilter();
//开始查找
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
//结束查找
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//查找设备
intentFilter1.addAction(BluetoothDevice.ACTION_FOUND);
//设备扫描模式改变
intentFilter1.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
//绑定状态
intentFilter1.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter1.addAction(ACTIONFILTER);
intentFilter1.addAction(BluetoothDevice.ACTION_UUID);
registerReceiver(broadcastReceiver, intentFilter1);
broadcastReceiver.SetPairlistener(new MakePariBlueToothListener() {
@Override
public void whilePari(BluetoothDevice device) {

}

@Override
public void pairingSuccess(BluetoothDevice device) {
bluetoothFindAdapter.notifyDataSetChanged();//先配对成功,再连接
startConnect(device);

// Toast.makeText(“配对完成”);
}

@Override
public void cancelPari(BluetoothDevice device) {

}
});
mController = new BluetoothController();
if (!mController.isSupportBluetooth()) {
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“当前设备不支持或者没有打开蓝牙”);
return;
}
mController.turnOnBluetooth(this, 1);

public void startConnect(BluetoothDevice device) {

ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接中…”);
AppApplication.clientThread = new ClientThread(bluetoothAdapter, device, uiHandler);
threadExecutor.execute(AppApplication.clientThread);
AppApplication.clientThread.SetConnectBack(new ClientThread.ConnectBack() {
@Override
public void connectsuccess(BluetoothDevice device) {
// 通知 ui 连接的服务器端设备
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接成功!”);
Intent intent = new Intent(BlueToothActivity.this, MainActivity.class);
startActivity(intent);
}

@Override
public void connectfaile(BluetoothDevice device) {
Log.i(“TAGFAILURE”, “HHHH”);
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接失败,请检查对方蓝牙是否打开”);
// mtoast.toast(“连接失败,请检查服务端是否打开。”);
}

@Override
public void connecting(BluetoothDevice device) {
Log.i(“TAGIN”, “HHHHH”);
// mtoast.toast(“请稍等,正在连接中。”);
}
});
}
广播接收器
private class myBtReceiver extends BroadcastReceiver {
MakePariBlueToothListener mMakePariListener;

public void SetPairlistener(MakePariBlueToothListener makePariBlueToothListener) {
this.mMakePariListener = makePariBlueToothListener;
}

@Override
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
//蓝牙设备

//信号强度
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);

Log.i(“TAGTAGDEVICE”, “扫描到设备:” + bluetoothDevice.getName() + “–>” + bluetoothDevice.getAddress());
Message message = new Message();
message.what = DISCOVERY_DEVICE;
message.obj = bluetoothDevice;
uiHandler.sendMessage(message);

} else if (TextUtils.equals(action, BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {

int bondSate = bluetoothDevice.getBondState();
switch (bondSate) {
case BluetoothDevice.BOND_NONE:
Log.d(“TAGBOND3”, “已解除配对”);
mMakePariListener.cancelPari(bluetoothDevice);
break;
case BluetoothDevice.BOND_BONDING:
mMakePariListener.whilePari(bluetoothDevice);
break;

case BluetoothDevice.BOND_BONDED:
Log.d(“TAGBOND2”, “已配对”);
mMakePariListener.pairingSuccess(bluetoothDevice);
break;
}
} else if (ACTIONFILTER.equals(action)) {
try {
//1.确认配对
ClsUtils.setPairingConfirmation(bluetoothDevice.getClass(), bluetoothDevice, true);
//2.终止有序广播
Log.i(“order…”, “isOrderedBroadcast:” + isOrderedBroadcast() + “,isInitialStickyBroadcast:” + isInitialStickyBroadcast());
abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
//3.调用setPin方法进行配对…
boolean ret = ClsUtils.setPin(bluetoothDevice.getClass(), bluetoothDevice, pin);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
Message message = new Message();
message.what = START_DISCOVERY;
uiHandler.sendMessage(message);
} else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
Message message = new Message();
message.what = STOP_DISCOVERY;
message.obj = bluetoothDevice;
uiHandler.sendMessage(message);
}else if(TextUtils.equals(action, BluetoothDevice.ACTION_UUID)){
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);

if(uuidExtra == null) {
Log.i(“TAGUUID”,d.getName()+”hh”+uuidExtra.toString());
//Log.e(TAG, “UUID = null”);
}
}
}
}
工具类

public class BluetoothController {
private BluetoothAdapter bluetoothAdapter;

public BluetoothController() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

/*
是否支持蓝牙
*/
public boolean isSupportBluetooth() {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
return false;
} else {
return true;
}
}

public boolean getBluetoothStatus() {
assert (bluetoothAdapter != null);
return bluetoothAdapter.isEnabled();
}

public void turnOnBluetooth(Activity activity, int requestCode) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
}

public void turnOffBluetooth() {
bluetoothAdapter.disable();
}

/*
打开蓝牙可见性
*/
public void enableVisibly(Context context) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}

/*
是否在搜索
*/
public boolean isDiscovering() {
return bluetoothAdapter.isDiscovering();
}
public void cancelDiscovery() {
if (isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}

/*
查找设备
*/
public void findDevice(Activity activity) {
assert (bluetoothAdapter != null);
if (!isDiscovering()) {
if (Build.VERSION.SDK_INT >= 6.0) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
BluetoothParams.MY_PERMISSION_REQUEST_CONSTANT);
}
bluetoothAdapter.startDiscovery();
}

}

/**
*     * 获取远程设备
* <p>
*     *
* <p>
*     * @param address
* <p>
*     * @return
* <p>
*    
*/

public BluetoothDevice getRemoteDevice(String address) {

return bluetoothAdapter.getRemoteDevice(address);

}

/**
*     * 获取客户端设备
* <p>
*     * @param name
* <p>
*     * @param uuid
* <p>
*     * @return
* <p>
*    
*/

public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) {

try {

return bluetoothAdapter.listenUsingRfcommWithServiceRecord(name, uuid);

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

/*获取绑定设备

*/
public List<BluetoothDevice> getBondedDeviceList() {
return new ArrayList<>(bluetoothAdapter.getBondedDevices());
}
}

客户端发送与接收线程
public class ClientThread implements Runnable {
final String TAG = “ClientThread”;

BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;

Handler uiHandler;
Handler writeHandler;

public static BluetoothSocket socket;
OutputStream out;
InputStream in;
BufferedReader reader;

ConnectBack mConnectBack;
private Thread readerThread;

public void SetConnectBack(ConnectBack ConnectBack) {
this.mConnectBack = ConnectBack;
}

public ClientThread(BluetoothAdapter bluetoothAdapter, BluetoothDevice device,
Handler handler) {
this.bluetoothAdapter = bluetoothAdapter;
this.device = device;
this.uiHandler = handler;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(BluetoothParams.UUID));
} catch (IOException e) {
e.printStackTrace();
}
socket = tmp;
}

public BluetoothSocket getSocket() {
return socket;
}

@Override
public void run() {

Log.e(TAG, “—————– do client thread run()”);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}

try {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
socket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
socket.close();
mConnectBack.connectfaile(device);
return;
} catch (IOException closeException) {
}
mConnectBack.connectfaile(device);
return;
}
mConnectBack.connectsuccess(device);
ConcectReader();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, “————– exception”);
}
}

private void ConcectReader() throws IOException {
// out = null;
out = socket.getOutputStream();
// in = null;
in = socket.getInputStream();
//如果ble需要对事件广播进行监听;如果只是普通蓝牙直接使用接口函数即可,但是需要使用循环(for)不断读一个字节的函数,不能直接读一串。
new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
byte[] oneByte = new byte[1];
byte[] buffer = new byte[1024];
int len = 0;
String content;
try{
while ((len = in.read(oneByte, 0, 1)) != -1) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

public void send(String data) {

try {
out = socket.getOutputStream();
out.write(data.getBytes(“utf-8”));
Log.e(TAG, “———- write data ok ” + data);
} catch (IOException e) {
e.printStackTrace();
}
}

public void send(byte[] data) {
try {
out = socket.getOutputStream();
out.write(data);
Log.e(TAG, “———- write data ok ” + data);
} catch (IOException e) {
e.printStackTrace();
}
}

public interface ConnectBack {

public void connectsuccess(BluetoothDevice device);

public void connectfaile(BluetoothDevice device);

public void connecting(BluetoothDevice device);
}

}

android 6.0以上需要动态获取位置权限
private void requestPermission() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, BluetoothParams.MY_PERMISSION_REQUEST_CONSTANT);

} else {
mController.findDevice(BlueToothActivity.this);

}

} else {
mController.findDevice(BlueToothActivity.this);
}
}
//oncreate中蓝牙初始化
//蓝牙核心对象获取
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
//注册蓝牙广播接收器
broadcastReceiver = new myBtReceiver();
IntentFilter intentFilter1 = new IntentFilter();
//开始查找
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
//结束查找
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//查找设备
intentFilter1.addAction(BluetoothDevice.ACTION_FOUND);
//设备扫描模式改变
intentFilter1.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
//绑定状态
intentFilter1.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter1.addAction(ACTIONFILTER);
intentFilter1.addAction(BluetoothDevice.ACTION_UUID);
registerReceiver(broadcastReceiver, intentFilter1);
broadcastReceiver.SetPairlistener(new MakePariBlueToothListener() {
@Override
public void whilePari(BluetoothDevice device) {

}

@Override
public void pairingSuccess(BluetoothDevice device) {
bluetoothFindAdapter.notifyDataSetChanged();//先配对成功,再连接
startConnect(device);

// Toast.makeText(“配对完成”);
}

@Override
public void cancelPari(BluetoothDevice device) {

}
});
mController = new BluetoothController();
if (!mController.isSupportBluetooth()) {
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“当前设备不支持或者没有打开蓝牙”);
return;
}
mController.turnOnBluetooth(this, 1);

public void startConnect(BluetoothDevice device) {

ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接中…”);
AppApplication.clientThread = new ClientThread(bluetoothAdapter, device, uiHandler);
threadExecutor.execute(AppApplication.clientThread);
AppApplication.clientThread.SetConnectBack(new ClientThread.ConnectBack() {
@Override
public void connectsuccess(BluetoothDevice device) {
// 通知 ui 连接的服务器端设备
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接成功!”);
Intent intent = new Intent(BlueToothActivity.this, MainActivity.class);
startActivity(intent);
}

@Override
public void connectfaile(BluetoothDevice device) {
Log.i(“TAGFAILURE”, “HHHH”);
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
ToastUtils.setBgResource(R.color.gray);
ToastUtils.showShort(“连接失败,请检查对方蓝牙是否打开”);
// mtoast.toast(“连接失败,请检查服务端是否打开。”);
}

@Override
public void connecting(BluetoothDevice device) {
Log.i(“TAGIN”, “HHHHH”);
// mtoast.toast(“请稍等,正在连接中。”);
}
});
}
广播接收器
private class myBtReceiver extends BroadcastReceiver {
MakePariBlueToothListener mMakePariListener;

public void SetPairlistener(MakePariBlueToothListener makePariBlueToothListener) {
this.mMakePariListener = makePariBlueToothListener;
}

@Override
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
//蓝牙设备

//信号强度
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);

Log.i(“TAGTAGDEVICE”, “扫描到设备:” + bluetoothDevice.getName() + “–>” + bluetoothDevice.getAddress());
Message message = new Message();
message.what = DISCOVERY_DEVICE;
message.obj = bluetoothDevice;
uiHandler.sendMessage(message);

} else if (TextUtils.equals(action, BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {

int bondSate = bluetoothDevice.getBondState();
switch (bondSate) {
case BluetoothDevice.BOND_NONE:
Log.d(“TAGBOND3”, “已解除配对”);
mMakePariListener.cancelPari(bluetoothDevice);
break;
case BluetoothDevice.BOND_BONDING:
mMakePariListener.whilePari(bluetoothDevice);
break;

case BluetoothDevice.BOND_BONDED:
Log.d(“TAGBOND2”, “已配对”);
mMakePariListener.pairingSuccess(bluetoothDevice);
break;
}
} else if (ACTIONFILTER.equals(action)) {
try {
//1.确认配对
ClsUtils.setPairingConfirmation(bluetoothDevice.getClass(), bluetoothDevice, true);
//2.终止有序广播
Log.i(“order…”, “isOrderedBroadcast:” + isOrderedBroadcast() + “,isInitialStickyBroadcast:” + isInitialStickyBroadcast());
abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
//3.调用setPin方法进行配对…
boolean ret = ClsUtils.setPin(bluetoothDevice.getClass(), bluetoothDevice, pin);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
Message message = new Message();
message.what = START_DISCOVERY;
uiHandler.sendMessage(message);
} else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
Message message = new Message();
message.what = STOP_DISCOVERY;
message.obj = bluetoothDevice;
uiHandler.sendMessage(message);
}else if(TextUtils.equals(action, BluetoothDevice.ACTION_UUID)){
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);

if(uuidExtra == null) {
Log.i(“TAGUUID”,d.getName()+”hh”+uuidExtra.toString());
//Log.e(TAG, “UUID = null”);
}
}
}
}
工具类

public class BluetoothController {
private BluetoothAdapter bluetoothAdapter;

public BluetoothController() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

/*
是否支持蓝牙
*/
public boolean isSupportBluetooth() {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
return false;
} else {
return true;
}
}

public boolean getBluetoothStatus() {
assert (bluetoothAdapter != null);
return bluetoothAdapter.isEnabled();
}

public void turnOnBluetooth(Activity activity, int requestCode) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
}

public void turnOffBluetooth() {
bluetoothAdapter.disable();
}

/*
打开蓝牙可见性
*/
public void enableVisibly(Context context) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}

/*
是否在搜索
*/
public boolean isDiscovering() {
return bluetoothAdapter.isDiscovering();
}
public void cancelDiscovery() {
if (isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}

/*
查找设备
*/
public void findDevice(Activity activity) {
assert (bluetoothAdapter != null);
if (!isDiscovering()) {
if (Build.VERSION.SDK_INT >= 6.0) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
BluetoothParams.MY_PERMISSION_REQUEST_CONSTANT);
}
bluetoothAdapter.startDiscovery();
}

}

/**
*     * 获取远程设备
* <p>
*     *
* <p>
*     * @param address
* <p>
*     * @return
* <p>
*    
*/

public BluetoothDevice getRemoteDevice(String address) {

return bluetoothAdapter.getRemoteDevice(address);

}

/**
*     * 获取客户端设备
* <p>
*     * @param name
* <p>
*     * @param uuid
* <p>
*     * @return
* <p>
*    
*/

public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid) {

try {

return bluetoothAdapter.listenUsingRfcommWithServiceRecord(name, uuid);

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

/*获取绑定设备

*/
public List<BluetoothDevice> getBondedDeviceList() {
return new ArrayList<>(bluetoothAdapter.getBondedDevices());
}
}

客户端发送与接收线程
public class ClientThread implements Runnable {
final String TAG = “ClientThread”;

BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;

Handler uiHandler;
Handler writeHandler;

public static BluetoothSocket socket;
OutputStream out;
InputStream in;
BufferedReader reader;

ConnectBack mConnectBack;
private Thread readerThread;

public void SetConnectBack(ConnectBack ConnectBack) {
this.mConnectBack = ConnectBack;
}

public ClientThread(BluetoothAdapter bluetoothAdapter, BluetoothDevice device,
Handler handler) {
this.bluetoothAdapter = bluetoothAdapter;
this.device = device;
this.uiHandler = handler;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(BluetoothParams.UUID));
} catch (IOException e) {
e.printStackTrace();
}
socket = tmp;
}

public BluetoothSocket getSocket() {
return socket;
}

@Override
public void run() {

Log.e(TAG, “—————– do client thread run()”);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}

try {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
socket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
socket.close();
mConnectBack.connectfaile(device);
return;
} catch (IOException closeException) {
}
mConnectBack.connectfaile(device);
return;
}
mConnectBack.connectsuccess(device);
ConcectReader();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, “————– exception”);
}
}

private void ConcectReader() throws IOException {
// out = null;
out = socket.getOutputStream();
// in = null;
in = socket.getInputStream();
//如果ble需要对事件广播进行监听;如果只是普通蓝牙直接使用接口函数即可,但是需要使用循环(for)不断读一个字节的函数,不能直接读一串。
new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
byte[] oneByte = new byte[1];
byte[] buffer = new byte[1024];
int len = 0;
String content;
try{
while ((len = in.read(oneByte, 0, 1)) != -1) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

public void send(String data) {

try {
out = socket.getOutputStream();
out.write(data.getBytes(“utf-8”));
Log.e(TAG, “———- write data ok ” + data);
} catch (IOException e) {
e.printStackTrace();
}
}

public void send(byte[] data) {
try {
out = socket.getOutputStream();
out.write(data);
Log.e(TAG, “———- write data ok ” + data);
} catch (IOException e) {
e.printStackTrace();
}
}

public interface ConnectBack {

public void connectsuccess(BluetoothDevice device);

public void connectfaile(BluetoothDevice device);

public void connecting(BluetoothDevice device);
}

}

专业,详细。

部分转自互联网,侵权删除联系

赞(0) 打赏
部分文章转自网络,侵权联系删除b2bchain区块链学习技术社区 » Android经典蓝牙与调料机或单片机通讯求职学习资料
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

b2b链

联系我们联系我们