Android Bluetoothスキャン/接続/送受信
13900 ワード
/**
*
*/
public class BlueToothUtils {
private final String TAG = this.getClass().getSimpleName();
private static BlueToothUtils utils = null;
private BluetoothAdapter bluetoothAdapter;
private final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private Executor executor;
//
private static BluetoothSocket mSocket;
private ArrayList deviceList = new ArrayList<>();//
private Handler handler;
public static BluetoothDevice mDevice = null;
private boolean enabled = false;//
private final int SCANTIME = 5*1000;//
private final int requestCode = 2002;//
public static BlueToothUtils getInstance(){
if (utils == null){
synchronized (BlueToothUtils.class){
if (utils == null){
utils = new BlueToothUtils();
}
}
}
return utils;
}
/**
*
*
*/
public void isOpen(Handler mHandler){
handler = mHandler;
ReceiveUtils.getInstance().setListener(listener);
BluetoothManager bluetoothManager = (BluetoothManager) MyApplication.context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter(); // null:
if (bluetoothAdapter == null){
return;
}
connetGatt();
}
/**
*
*/
public void connetGatt(){
if (bluetoothAdapter != null){
// true: , false:
enabled = bluetoothAdapter.isEnabled();
if (!enabled){
MyApplication.activity.startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
requestCode);
}else {//
Set devicesSet = bluetoothAdapter.getBondedDevices();
deviceList.clear();
for (BluetoothDevice device : devicesSet) {
deviceList.add(device);
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
}
// LogUtils.log(TAG," " + device.getName());
String connetAddress = (String) SPUtils.get(MyApplication.context, SPUtils.BLUETOOTH_ADDRESS, "");
if (device.getAddress().equals(connetAddress)){
if (bluetoothAdapter.isDiscovering()){
scanning(false);
}
LogUtils.log(TAG," " + device.getName());
connet(device);
}
}
}
}
}
/**
*
*/
public void scanning(boolean enable){
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()){
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_OPEN);
}
return;
}
if (bluetoothAdapter != null){
if (enable){
if (handler != null){
handler.postDelayed(new Runnable() {
@Override
public void run() {
bluetoothAdapter.cancelDiscovery();
handler.sendEmptyMessage(BluetoothActivity.SCAN_CLOSE);
LogUtils.log("BlueToothUtils", " ");
}
}, SCANTIME);
}
deviceList.clear();
connetGatt();
// ,android
this.bluetoothAdapter.startDiscovery();
LogUtils.log("BlueToothUtils", " ");
}else {
if (handler != null){
handler.removeCallbacksAndMessages(null);
handler.sendEmptyMessage(BluetoothActivity.SCAN_CLOSE);
}
bluetoothAdapter.cancelDiscovery();
LogUtils.log("BlueToothUtils", " ");
}
}
}
/**
*
*/
public void initIntentFilter() {
//
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// ,
MyApplication.context.registerReceiver(receiver, intentFilter);
}
/**
*
*/
public void unregisterReceiver() {
MyApplication.context.unregisterReceiver(receiver);
}
/**
*
*/
private 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);
// LogUtils.log(TAG," :" + device.getName());
// LogUtils.log(TAG," :" + device.getAddress());
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
deviceList.add(device);
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
}
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
LogUtils.log(TAG," ...");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
LogUtils.log(TAG," ");
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
}
// bluetoothAdapter.cancelDiscovery();
}
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (bluetoothAdapter == null) return;
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
LogUtils.log(TAG," ");
enabled = bluetoothAdapter.isEnabled();
connetGatt();
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
LogUtils.log(TAG," ");
}
}
}
};
/**
*
*/
public void connet(BluetoothDevice device){
if (bluetoothAdapter != null && device != null){
close();
LogUtils.log(TAG," --" + device.getName());
try {
// final BluetoothSocket socket = dev.createRfcommSocketToServiceRecord(SPP_UUID); // ,Android ,
final BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID); // ( ),
executor = Executors.newCachedThreadPool();
//
executor.execute(new Runnable() {
@Override
public void run() {
mSocket = socket;
mDevice = mSocket.getRemoteDevice();
receiveDate(mSocket); //
}
});
} catch (Throwable e) {
close();
}
}
}
/**
*
*
*/
public void sendData(byte[] by) {
if (!isConnected(null)){
// LogUtils.log(TAG, " ");
return;
}
if (null != outputStream) {
outputStream.write(by, 0, by.len);
LogUtils.log( "SerialPortThread-- ");
} else {
LogUtils.log("SerialPortUtils", " ");
}
}
/**
*
*/
public boolean isConnected(BluetoothDevice dev) {
boolean connected = (mSocket != null && mSocket.isConnected());
if (dev == null)
return connected;
return connected && mSocket.getRemoteDevice().equals(dev);
}
/**
*
*/
public void cancle(){
try {
if (bluetoothAdapter != null){
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.disable();
bluetoothAdapter = null;
}
if (mSocket != null){
mSocket.close();
}
ReceiveUtils.getInstance().close();
// unregisterReceiver();
utils = null;
}catch (Exception e){
e.printStackTrace();
}
}
public void receiveDate(BluetoothSocket socket){
try {
mSocket = socket;
if (!mSocket.isConnected()){
mSocket.connect();
}
LogUtils.log(TAG, " --" + mSocket.getRemoteDevice().getName());
outputStream = new DataOutputStream(mSocket.getOutputStream());
DataInputStream in = new DataInputStream(mSocket.getInputStream());
int size = 0;
byte[] buffer;
isExit = false;
while (!isExit){
buffer = new byte[DATA_MAX_LEN];
if (in != null) {
size = in.read(buffer);
if (size > 0) {
checkData(buffer, size);//
}
}
Thread.sleep(10);
}
}catch (Exception e){
LogUtils.log(TAG, " " + e.getMessage());
close();
e.printStackTrace();
}
}
/**
* Socket
*/
public void close() {
try {
Log.e("-----------", " Socket :");
isExit = true;
if (mSocket != null){
mSocket.close();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
/**
* /
*/
public class ReceiveUtils {
private final String TAG = this.getClass().getSimpleName();
private static ReceiveUtils utils = null;
private BluetoothSocket mSocket;
private DataOutputStream outputStream;
//
private boolean isExit = false;
private BlueToothUtils.Listener listener;
/**** */
private static int DATA_MAX_LEN = 10;
/**** */
private static int checkSumLen = 8;
/***** */
private static byte[] b = new byte[DATA_MAX_LEN];
/***** */
private static int unDisposeLen = 0;
/**** : , 0x35*/
private static byte head = (byte) 0xA5;
/**** : , 0xAA*/
private static byte end = (byte) 0x45;
public static ReceiveUtils getInstance(){
if (utils == null){
synchronized (ReceiveUtils.class){
if (utils == null){
utils = new ReceiveUtils();
}
}
}
return utils;
}
public void setListener(BlueToothUtils.Listener listener){
this.listener = listener;
}
public void receiveDate(BluetoothSocket socket){
try {
mSocket = socket;
if (!mSocket.isConnected()){
mSocket.connect();
}
LogUtils.log(TAG, " --" + mSocket.getRemoteDevice().getName());
if (listener != null){
listener.socketNotify(BlueToothUtils.Listener.CONNECTED, mSocket.getRemoteDevice());
SPUtils.set(MyApplication.context, SPUtils.BLUETOOTH_ADDRESS, mSocket.getRemoteDevice().getAddress());
}
outputStream = new DataOutputStream(mSocket.getOutputStream());
DataInputStream in = new DataInputStream(mSocket.getInputStream());
int size = 0;
byte[] buffer;
isExit = false;
while (!isExit){
buffer = new byte[DATA_MAX_LEN];
if (in != null) {
size = in.read(buffer);
if (size > 0) {
//
}
}
Thread.sleep(10);
}
}catch (Exception e){
LogUtils.log(TAG, " " + e.getMessage());
close();
e.printStackTrace();
}
}
/***
*
*/
public void send(byte by) {
try {
if (null != outputStream) {
outputStream.write(by, 0, DATA_MAX_LEN);
// LogWSUtils.logData(by, DATA_MAX_LEN, TAG + "-- ");
// LogUtils.log(TAG, " --" + Arrays.toString(by));
} else {
LogUtils.log(TAG, " ");
}
} catch (IOException e) {
close();
e.printStackTrace();
}
}
/**
* Socket
*/
public void close() {
try {
Log.e("-----------", " Socket :");
isExit = true;
if (mSocket != null){
mSocket.close();
mSocket = null;
}
if (listener != null){
listener.socketNotify(BlueToothUtils.Listener.DISCONNECTED, null);
}
} catch (Throwable e) {
e.printStackTrace();
}
}