网上好多代码都在搞什么自动配对,搞的好复杂,其实实际应用没有必要的,只要把Android当作主机,主动配对蓝牙串口保存下来,然后根据蓝牙的地址进行连接并收发消息
其实蓝牙配对其实就好比手机选择wifi热点输入密码一样,平时应用有必要自动配对吗?
package com.example.zmy.bluetoothserialnew;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainActivity extends ActionBarActivity {
String macAddress = "";
boolean connecting = false;
boolean connected = false;
int connetTime = 0;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mBluetoothDevice = null;
private BluetoothSocket socket = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//@Override
public void OnButtonClick(View v)
{
Log.i("info", "OnButtonclick....");
ConnectThread blueThread = new ConnectThread("00:06:71:00:40:16");
blueThread.start();
}
public void OnButtonSendClick(View v)
{
sendMessage(socket, "comfrom android cell phone....");
}
//----------------------------------------------------------------------------------------
private class ConnectThread extends Thread {
public ConnectThread(String mac) {
macAddress = mac;
}
public void run() {
connecting = true;
connected = false;
if(mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
Log.i("info", "device is:" + mBluetoothDevice);
mBluetoothAdapter.cancelDiscovery();
initSocket();
//adapter.cancelDiscovery();
while (!connected && connetTime <= 10) {
try {
socket.connect();
connected = true;
} catch (IOException e1) {
connetTime++;
connected = false;
// 关闭 socket
try {
socket.close();
socket = null;
} catch (IOException e2) {
//TODO: handle exception
Log.e("exception", "Socket", e2);
}
} finally {
connecting = false;
}
//connectDevice();
}
// 重置ConnectThread
//synchronized (BluetoothService.this) {
//ConnectThread = null;
//}
BluetoothSocketListener bluetoothListener = new BluetoothSocketListener(socket);
bluetoothListener.run();
}
public void cancel() {
try {
socket.close();
socket = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
connecting = false;
}
}
/**
* 取得BluetoothSocket
*/
private void initSocket() {
BluetoothSocket temp = null;
try {
Method m = mBluetoothDevice.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//这里端口为1
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
socket = temp;
}
}
private void sendMessage(BluetoothSocket socket, String msg) {
//OutputStream outStream;
try {
//outStream = socket.getOutputStream();
PrintWriter outStream = new PrintWriter(socket.getOutputStream(),true);
byte[] byteString = (msg + " ").getBytes();
byteString[byteString.length - 1] = 0;
//outStream.write(byteString);
outStream.write(msg);
outStream.flush();
Log.i("info", "sendmessage:" + msg + "....................");
} catch (IOException e) {
Log.i("BLUETOOTH_COMMS", e.getMessage());
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
//private TextView textView;
//private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket) {
this.socket = socket;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead);
Log.i("msg", message);
//handler.post(new MessagePoster(textView, message));
//JniTestHelper.sendToUI(message);
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
}