Android realizes one to one Bluetooth chat APP

  • 2021-09-11 21:19:01
  • OfStack

Learning, 3 days of Android Bluetooth development, the beginning is a fog, looking at others said Google official demo feeling very easy, all myself also try to write a very simple chat demo. But think very simple, do it themselves also spent, nearly a day to get this basic process design. The following is a few points of heart to post code later

1) Write a simple demo, remember that 1 must have the overall process before starting to dig the code
2) Since demo is new knowledge after all, log point 1 in the middle of the code can't be less, this is a sharp weapon for you to debug quickly
3) Or thinking in java, think about what is mutable, what is immutable, and then separate, so as to achieve the encapsulation of the code, it feels very good. But now I still feel difficult to understand
4) Start thinking about how to deal with problems with object-oriented process, which is also an idea of encapsulating code

Basic functions of Bluetooth chat:

1. Implement a 1-to-1 Bluetooth connection
2. Achieve 1-to-1 chat

Very simple function, thinking is also very clear, but in-depth to write, just know, water or depth, java unfamiliar words.
Here, how to turn on Bluetooth is not repeated, please Baidu yourself.

Thoughts:

1) Initialize, turn on the Bluetooth of the mobile phone, start the Bluetooth server thread, and wait for the connection
2) Pairing and obtaining the Bluetooth address address of a mobile phone.
3) Open the connection thread to connect the Bluetooth of the mobile phone
4) After the connection is successful, the Bluetooth chat thread is opened for chat communication.

The above four steps are the main ideas, There are several details in it, Is that some logical problems in development, Security issues between threads, It also needs to be handled well. What makes me feel deeply is that, 1-to-1 chatting is equivalent to the Prime Minister's communication as a server, so 1 starts to turn on two service monitoring, and 1 has one access. Here, it is necessary to find out which is the access object and which is the access object. If it is not used as a server, the server thread can be closed.

Stick the code below


/**
 *  The client starts the connection thread 
 *  Through Bluetooth mac Address acquisition connection 
 * @author Administrator
 *
 */
 private class ConnectThread extends Thread {

 private BluetoothDevice mDevice;
 private BluetoothSocket btSocket = null;

 public ConnectThread(String address) {
  // TODO Auto-generated constructor stub
  mDevice = mBluetoothAdapter.getRemoteDevice(address);
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  connect(mDevice);
 }

 private void connect(BluetoothDevice btDev) {

  Method creMethod;
  try {
  creMethod = BluetoothDevice.class.getMethod("createBond");
  creMethod.invoke(btDev);

  } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  try {
  btSocket = btDev.createRfcommSocketToServiceRecord(MYUUID);
  System.out.println("========" + "start connect");
  Log.d("BlueToothTestActivity", " Start a connection ...");
  btSocket.connect();
  mClientSocket = btSocket;
  isConnected=true;
  mHandler.sendEmptyMessage(SUCCESS_SERVICE_BEGIN_TALKING);

  //  As a client   Shut down   Server side   Link waiting 
  if (acceptThread != null) {
   acceptThread.close();
  }
  startTalk();
  } catch (IOException e) {
  // TODO Auto-generated catch block
  System.out.println("???????????????? close socket");
  close();
  System.out.println(e.toString());
  e.printStackTrace();
  }

 }

 private void close() {
  if (btSocket != null) {
  try {
   btSocket.close();
   mHandler.sendEmptyMessage(FAILED_SERVICE_SOCRCKET);
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  }
 }

}

/**
 *  Design of server side 
 *  Each Bluetooth client must first open the server and wait for access 
 * @author Administrator
 *
*/
 private class AcceptThread extends Thread {
 private final BluetoothServerSocket mmServerSocket;

 public AcceptThread() {
  // Use a temporary object that is later assigned to mmServerSocket,
  // because mmServerSocket is final
  BluetoothServerSocket tmp = null;
  try {
  // MY_UUID is the app's UUID string, also used by the client
  // code
  tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("Fisrt", MYUUID);
  } catch (IOException e) {
  mHandler.sendEmptyMessage(FAILED_SERVICE_SOCRCKET);

  }
  mmServerSocket = tmp;
 }

 public void run() {
  BluetoothSocket socket = null;
  // Keep listening until exception occurs or a socket is returned
  while (isRun) {
  try {
   socket = mmServerSocket.accept();
   mHandler.sendEmptyMessage(SUCCESS_SERVICE_SOCRCKET);

   Log.e("TAG", "========== server start ====");

  } catch (IOException e) {
   mHandler.sendEmptyMessage(FAILED_SERVICE_SOCRCKET);
   close();
  }



  // If a connection was accepted
  if (socket != null) {
   //  Successful server connection , Start the chat thread , Pass   Same as 1 A  socket  Prevent the problem of null value in multithreaded assignment 
   isConnected=true;
   mClientSocket = socket;
   mTalkThread = new TalkThread();
   mTalkThread.start();

   // Do work to manage the connection (in a separate thread)
   //  Beware of insecurity in multithreaded operation 
   synchronized (BlueConnectService.this) {
   //close();
   }
  }

  }
 }

 public void close() {
  isRun = false;
  try {
  mmServerSocket.close();
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }

}

/**
 * Design the chat thread after successful connection  1. Setting up a stream , Get through a connection  2. Send and receive data  3. Display data 
 * It should be noted that when chatting, , Need the same 1 A socket Establish a connection to obtain the corresponding input and output stream 
 */

 private class TalkThread extends Thread {

 private final BluetoothSocket talkSocket;
 private final InputStream mIs;
 private final OutputStream mOs;
 private boolean isRunning = true;

 public TalkThread() {
  // TODO Auto-generated constructor stub
  talkSocket = mClientSocket;
  if (talkSocket == null) {
  System.out.println("================= talkThread erro ");
  // return;
  }

  InputStream is = null;
  OutputStream os = null;
  try {
  is = talkSocket.getInputStream();
  os = talkSocket.getOutputStream();
  } catch (IOException e) {
  // TODO Auto-generated catch block
  try {
   System.out.println("???????????????? close socket");
   talkSocket.close();
   CloseUtil.closeStream(is, os);
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  e.printStackTrace();
  }

  mIs = is;
  mOs = os;

 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  super.run();
  byte[] buffer = new byte[1024];
  int len;
  while (isRunning) {
  try {
   len = mIs.read(buffer);
   mHandler.obtainMessage(READ_MESSAGE, len, -1, buffer).sendToTarget();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   try {
   isRunning = false;
   isConnected=false;
   System.out.println("???????????????? close socket");
   talkSocket.close();
   //  Need to restart the server 
   //  Start the server 

   } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
   }
   CloseUtil.closeStream(mIs, mOs);

  }
  }

 }

 public void write(byte[] bytes) {
  try {
  mOs.write(bytes);
  mHandler.obtainMessage(WRITE_MESSAGE, bytes.length, -1, bytes).sendToTarget();
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }

}

Related articles: