我的编程空间,编程开发者的网络收藏夹
学习永远不晚

Android蓝牙通信聊天实现发送和接受功能

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

Android蓝牙通信聊天实现发送和接受功能

很不错的蓝牙通信demo实现发送和接受功能,就用了两个类就实现了,具体内容如下

说下思路把 主要有两个类 主界面类 蓝牙聊天服务类 。 首先创建线程 实际上就是创建BluetoothChatService() (蓝牙聊天服务类) 这个时候把handler 传过去 这样就可以操作UI 界面了,在线程中不断轮询读取蓝牙消息,当主界面点击发送按钮时 调用BluetoothChatService 的发送方法write 方法,这里的write 方法 使用了handler 发送消息,在主界面显示,另一个 客户端 不断读取蓝牙消息 类似的有个read 方法 同样显示到界面上去,这样就完成了通信了。


import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothChat extends Activity {
  // Message types sent from the BluetoothChatService Handler
  public static final int MESSAGE_STATE_CHANGE = 1;
  public static final int MESSAGE_READ = 2;
  public static final int MESSAGE_WRITE = 3;
  public static final int MESSAGE_DEVICE_NAME = 4;
  public static final int MESSAGE_TOAST = 5;
  // Key names received from the BluetoothChatService Handler
  public static final String DEVICE_NAME = "device_name";
  public static final String TOAST = "toast";
  // Intent request codes
  private static final int REQUEST_CONNECT_DEVICE = 1;
  private static final int REQUEST_ENABLE_BT = 2;
  private TextView mTitle;
  private EditText text_chat;
  private EditText text_input;
  private Button but_On_Off;
  private Button but_search; // ------> 在菜单中可以搜索
  private Button but_create; // ------> 在菜单中设置"可被发现"
  private Button mSendButton;
  // 连接到的蓝牙设备的名称
  private String mConnectedDeviceName;
  // String buffer for outgoing messages
  private StringBuffer mOutStringBuffer;
  // Local Bluetooth adapter
  private BluetoothAdapter mBluetoothAdapter = null;
  // Member object for the chat services
  private BluetoothChatService mChatService = null;
  private ArrayList<String> mPairedDevicesList = new ArrayList<String>();
  private ArrayList<String> mNewDevicesList = new ArrayList<String>();
  private String[] strName;
  private String address;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.main);
    mTitle = (TextView) this.findViewById(R.id.text_title);
    text_chat = (EditText) this.findViewById(R.id.text_chat);
    text_input = (EditText) this.findViewById(R.id.text_input);
    but_On_Off = (Button) this.findViewById(R.id.but_off_on);
    but_search = (Button) this.findViewById(R.id.but_search_div);
    but_create = (Button) this.findViewById(R.id.but_cjlj);
    mSendButton = (Button) this.findViewById(R.id.but_fsxx);
    // 获得本地的蓝牙适配器
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    // 如果为null,说明没有蓝牙设备
    if (mBluetoothAdapter == null) {
      Toast.makeText(this, "没有蓝牙设备", Toast.LENGTH_LONG).show();
      finish();
      return;
    }
    if (mBluetoothAdapter.isEnabled()) {
      but_On_Off.setText("关闭蓝牙");
    } else {
      but_On_Off.setText("开启蓝牙");
    }
    but_On_Off.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (!mBluetoothAdapter.isEnabled()) {
          mBluetoothAdapter.enable();
          Toast.makeText(BluetoothChat.this, "蓝牙已开启",
              Toast.LENGTH_SHORT).show();
          but_On_Off.setText("关闭蓝牙");
        } else {
          mBluetoothAdapter.disable();
          Toast.makeText(BluetoothChat.this, "蓝牙已关闭",
              Toast.LENGTH_SHORT).show();
          but_On_Off.setText("开启蓝牙");
        }
      }
    });
    but_search.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        searchDevice();
      }
    });
    but_create.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        final EditText et = new EditText(BluetoothChat.this);
        et.setSingleLine();
        et.setText(mBluetoothAdapter.getName());
        new AlertDialog.Builder(BluetoothChat.this)
            .setTitle("请输入房间名:")
            .setView(et)
            .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog,
                      int which) {
                    String name = et.getText().toString()
                        .trim();
                    if (name.equals("")) {
                      Toast.makeText(BluetoothChat.this,
                          "请输入房间名",
                          Toast.LENGTH_SHORT).show();
                      return;
                    }
                    // 设置房间名
                    mBluetoothAdapter.setName(name);
                  }
                })
            .setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog,
                      int which) {
                  }
                }).create().show();
        // 创建连接,也就是设备本地蓝牙设备可被其他用户的蓝牙搜到
        ensureDiscoverable();
      }
    });
    // 获得一个已经配对的蓝牙设备的set集合
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
        .getBondedDevices();
    if (pairedDevices.size() > 0) {
      for (BluetoothDevice device : pairedDevices) {
        mPairedDevicesList.add("已配对:" + device.getName() + "\n"
            + device.getAddress());
      }
    } else {
      Toast.makeText(this, "没有已配对的设备", Toast.LENGTH_SHORT).show();
    }
    // 当发现一个新的蓝牙设备时注册广播
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);
    // 当搜索完毕后注册广播
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);
  }
  @Override
  public void onStart() {
    super.onStart();
    // If BT is not on, request that it be enabled.
    // setupChat() will then be called during onActivityResult
    if (!mBluetoothAdapter.isEnabled()) {
      Intent enableIntent = new Intent(
          BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
      // Otherwise, setup the chat session
    } else {
      if (mChatService == null)
        setupChat();
    }
  }
  @Override
  public synchronized void onResume() {
    super.onResume();
    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity
    // returns.
    if (mChatService != null) {
      // Only if the state is STATE_NONE, do we know that we haven't
      // started already
      if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
        // Start the Bluetooth chat services
        mChatService.start();
      }
    }
  }
  private void setupChat() {
    mSendButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        // Send a message using content of the edit text widget
        String message = text_input.getText().toString();
        sendMessage(message);
      }
    });
    // Initialize the BluetoothChatService to perform bluetooth connections
    mChatService = new BluetoothChatService(this, mHandler);
    // Initialize the buffer for outgoing messages
    mOutStringBuffer = new StringBuffer("");
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
    // Stop the Bluetooth chat services
    if (mChatService != null)
      mChatService.stop();
    // Make sure we're not doing discovery anymore
    if (mBluetoothAdapter != null) {
      mBluetoothAdapter.cancelDiscovery();
    }
    // Unregister broadcast listeners
    this.unregisterReceiver(mReceiver);
  }
  
  private void ensureDiscoverable() {
    if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
      Intent discoverableIntent = new Intent(
          BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
      discoverableIntent.putExtra(
          BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
      startActivity(discoverableIntent);
    }
  }
  
  private void sendMessage(String message) {
    // Check that we're actually connected before trying anything
    if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
      Toast.makeText(this, "没有连接上", Toast.LENGTH_SHORT).show();
      return;
    }
    // Check that there's actually something to send
    if (message.length() > 0) {
      // Get the message bytes and tell the BluetoothChatService to write
      byte[] send = message.getBytes();
      mChatService.write(send);
      // Reset out string buffer to zero and clear the edit text field
      mOutStringBuffer.setLength(0);
      text_input.setText(mOutStringBuffer);
    }
  }
  // The Handler that gets information back from the BluetoothChatService
  private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
      case MESSAGE_STATE_CHANGE:
        switch (msg.arg1) {
        case BluetoothChatService.STATE_CONNECTED:
          mTitle.setText("已经连接");
          mTitle.append(mConnectedDeviceName);
          // mConversationArrayAdapter.clear();
          break;
        case BluetoothChatService.STATE_CONNECTING:
          mTitle.setText("正在连接中...");
          break;
        case BluetoothChatService.STATE_LISTEN:
        case BluetoothChatService.STATE_NONE:
          mTitle.setText("未连接上");
          break;
        }
        break;
      case MESSAGE_WRITE:
        byte[] writeBuf = (byte[]) msg.obj;
        // construct a string from the buffer
        String writeMessage = new String(writeBuf);
        // mConversationArrayAdapter.add("Me: " + writeMessage);
        text_chat.append("我:" + writeMessage + "\n");
        break;
      case MESSAGE_READ:
        byte[] readBuf = (byte[]) msg.obj;
        // construct a string from the valid bytes in the buffer
        String readMessage = new String(readBuf, 0, msg.arg1);
        // mConversationArrayAdapter.add(mConnectedDeviceName+": " +
        // readMessage);
        text_chat.append(mConnectedDeviceName + ":" + readMessage
            + "\n");
        break;
      case MESSAGE_DEVICE_NAME:
        // save the connected device's name
        mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
        Toast.makeText(getApplicationContext(),
            "连接到 " + mConnectedDeviceName, Toast.LENGTH_SHORT)
            .show();
        break;
      case MESSAGE_TOAST:
        Toast.makeText(getApplicationContext(),
            msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
            .show();
        break;
      }
    }
  };
  // 连接蓝牙设备
  private void linkDevice() {
    if (mBluetoothAdapter.isDiscovering()) {
      mBluetoothAdapter.cancelDiscovery();
    }
    int cou = mPairedDevicesList.size() + mNewDevicesList.size();
    if (cou == 0) {
      Toast.makeText(BluetoothChat.this, "没有搜索到可用的蓝牙设备",
          Toast.LENGTH_SHORT).show();
      return;
    }
    // 把已经配对的蓝牙设备和新发现的蓝牙设备的名称都放入数组中,以便在对话框列表中显示
    strName = new String[cou];
    for (int i = 0; i < mPairedDevicesList.size(); i++) {
      strName[i] = mPairedDevicesList.get(i);
    }
    for (int i = mPairedDevicesList.size(); i < strName.length; i++) {
      strName[i] = mNewDevicesList.get(i - mPairedDevicesList.size());
    }
    address = strName[0].substring(strName[0].length() - 17);
    new AlertDialog.Builder(BluetoothChat.this)
        .setTitle("搜索到的蓝牙设备:")
        .setSingleChoiceItems(strName, 0,
            new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog,
                  int which) {
                // 当用户点击选中的蓝牙设备时,取出选中的蓝牙设备的MAC地址
                address = strName[which].split("\\n")[1].trim();
              }
            })
        .setPositiveButton("连接", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            if (address == null) {
              Toast.makeText(BluetoothChat.this, "请先连接外部蓝牙设备",
                  Toast.LENGTH_SHORT).show();
              return;
            }
            Log.i("sxd", "address:" + address);
            // Get the BLuetoothDevice object
            BluetoothDevice device = mBluetoothAdapter
                .getRemoteDevice(address);
            // Attempt to connect to the device
            mChatService.connect(device);
          }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
          }
        }).create().show();
  }
  // 搜索蓝牙设备蓝牙设备
  private void searchDevice() {
    mTitle.setText("正在努力搜索中...");
    setProgressBarIndeterminateVisibility(true);
    if (mBluetoothAdapter.isDiscovering()) {
      mBluetoothAdapter.cancelDiscovery();
    }
    mNewDevicesList.clear();
    mBluetoothAdapter.startDiscovery();
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 1, 0, "搜索设备");
    menu.add(0, 2, 0, "可被发现");
    return true;
  }
  private final BroadcastReceiver mReceiver = 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);
        // If it's already paired, skip it, because it's been listed
        // already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
          String s = "未配对: " + device.getName() + "\n"
              + device.getAddress();
          if (!mNewDevicesList.contains(s))
            mNewDevicesList.add(s);
        }
        // When discovery is finished, change the Activity title
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
          .equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        if (mNewDevicesList.size() == 0) {
          Toast.makeText(BluetoothChat.this, "没有发现新设备",
              Toast.LENGTH_SHORT).show();
        }
        mTitle.setText("未连接");
        linkDevice();
      }
    }
  };
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
      searchDevice();
      return true;
    case 2:
      // Ensure this device is discoverable by others
      ensureDiscoverable();
      return true;
    }
    return false;
  }
}

package com.it2388.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class BluetoothChatService {
  // Debugging
  private static final String TAG = "BluetoothChatService";
  private static final boolean D = true;
  // Name for the SDP record when creating server socket 对于SDP记录名称创建服务器套接字时
  private static final String NAME = "BluetoothChat";
  // Unique UUID for this application
  private static final UUID MY_UUID = UUID
      .fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
  // Member fields
  private final BluetoothAdapter mAdapter;
  private final Handler mHandler;
  private AcceptThread mAcceptThread;
  private ConnectThread mConnectThread;
  private ConnectedThread mConnectedThread;
  private int mState;
  // Constants that indicate the current connection state
  public static final int STATE_NONE = 0; // we're doing nothing 我们什么都不做
  public static final int STATE_LISTEN = 1; // now listening for incoming 现在监听
                        // connections
  public static final int STATE_CONNECTING = 2; // now initiating an outgoing
                          // 启动一个外向
                          // connection
  public static final int STATE_CONNECTED = 3; // now connected to a remote
                          // 连接到一个远程
                          // device
  
  public BluetoothChatService(Context context, Handler handler) {
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    mState = STATE_NONE;
    mHandler = handler;
  }
  
  private synchronized void setState(int state) {
    if (D)
      Log.d(TAG, "setState() " + mState + " -> " + state);
    mState = state;
    // Give the new state to the Handler so the UI Activity can update
    mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1)
        .sendToTarget();
  }
  
  public synchronized int getState() {
    return mState;
  }
  
  public synchronized void start() {
    if (D)
      Log.d(TAG, "start");
    // Cancel any thread attempting to make a connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }
    // Start the thread to listen on a BluetoothServerSocket
    if (mAcceptThread == null) {
      mAcceptThread = new AcceptThread();
      mAcceptThread.start();
    }
    setState(STATE_LISTEN);
  }
  
  public synchronized void connect(BluetoothDevice device) {
    if (D)
      Log.d(TAG, "connect to: " + device);
    // Cancel any thread attempting to make a connection
    if (mState == STATE_CONNECTING) {
      if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
      }
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }
    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device);
    mConnectThread.start();
    setState(STATE_CONNECTING);
  }
  
  public synchronized void connected(BluetoothSocket socket,
      BluetoothDevice device) {
    if (D)
      Log.d(TAG, "connected");
    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }
    // Cancel the accept thread because we only want to connect to one
    // device
    if (mAcceptThread != null) {
      mAcceptThread.cancel();
      mAcceptThread = null;
    }
    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
    // Send the name of the connected device back to the UI Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    setState(STATE_CONNECTED);
  }
  
  public synchronized void stop() {
    if (D)
      Log.d(TAG, "stop");
    if (mConnectThread != null) {
      mConnectThread.cancel();
      mConnectThread = null;
    }
    if (mConnectedThread != null) {
      mConnectedThread.cancel();
      mConnectedThread = null;
    }
    if (mAcceptThread != null) {
      mAcceptThread.cancel();
      mAcceptThread = null;
    }
    setState(STATE_NONE);
  }
  
  public void write(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    synchronized (this) {
      if (mState != STATE_CONNECTED)
        return;
      r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
  }
  
  private void connectionFailed() {
    setState(STATE_LISTEN);
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.TOAST, "不能连接到设备");
    msg.setData(bundle);
    mHandler.sendMessage(msg);
  }
  
  private void connectionLost() {
    setState(STATE_LISTEN);
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.TOAST, "设备连接中断");
    msg.setData(bundle);
    mHandler.sendMessage(msg);
  }
  
  private class AcceptThread extends Thread {
    // The local server socket
    private final BluetoothServerSocket mmServerSocket;
    public AcceptThread() {
      BluetoothServerSocket tmp = null;
      // Create a new listening server socket
      try {
        tmp = mAdapter
            .listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
      } catch (IOException e) {
        Log.e("sxd", " ======== ufcomm exception =======", e);
      }
      mmServerSocket = tmp;
    }
    public void run() {
      if (D)
        Log.d(TAG, "BEGIN mAcceptThread" + this);
      setName("AcceptThread");
      BluetoothSocket socket = null;
      // Listen to the server socket if we're not connected
      while (mState != STATE_CONNECTED) {
        try {
          // This is a blocking call and will only return on a
          // successful connection or an exception
          socket = mmServerSocket.accept();
        } catch (IOException e) {
          Log.e("sxd", "---> accept socket failed <---", e);
          break;
        }
        // If a connection was accepted
        if (socket != null) {
          synchronized (BluetoothChatService.this) {
            switch (mState) {
            case STATE_LISTEN:
            case STATE_CONNECTING:
              // Situation normal. Start the connected thread.
              connected(socket, socket.getRemoteDevice());
              break;
            case STATE_NONE:
            case STATE_CONNECTED:
              // Either not ready or already connected. Terminate
              // new socket.
              try {
                socket.close();
              } catch (IOException e) {
                Log.e(TAG, "Could not close unwanted socket", e);
              }
              break;
            }
          }
        }
      }
      if (D)
        Log.i(TAG, "END mAcceptThread");
    }
    public void cancel() {
      if (D)
        Log.d(TAG, "cancel " + this);
      try {
        mmServerSocket.close();
      } catch (IOException e) {
        Log.e(TAG, "close() of server failed", e);
      }
    }
  }
  
  private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    public ConnectThread(BluetoothDevice device) {
      mmDevice = device;
      BluetoothSocket tmp = null;
      // Get a BluetoothSocket for a connection with the
      // given BluetoothDevice
      try {
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
      } catch (IOException e) {
        Log.e(TAG, "create() failed", e);
      }
      mmSocket = tmp;
    }
    public void run() {
      Log.i(TAG, "BEGIN mConnectThread");
      setName("ConnectThread");
      // Always cancel discovery because it will slow down a connection
      mAdapter.cancelDiscovery();
      // Make a connection to the BluetoothSocket
      try {
        // This is a blocking call and will only return on a
        // successful connection or an exception
        mmSocket.connect();
      } catch (IOException e) {
        Log.e("sxd", "链接发生了异常", e);
        connectionFailed();
        // Close the socket
        try {
          mmSocket.close();
        } catch (IOException e2) {
          Log.e(TAG,
              "unable to close() socket during connection failure",
              e2);
        }
        // Start the service over to restart listening mode
        BluetoothChatService.this.start();
        return;
      }
      // Reset the ConnectThread because we're done
      synchronized (BluetoothChatService.this) {
        mConnectThread = null;
      }
      // Start the connected thread
      connected(mmSocket, mmDevice);
    }
    public void cancel() {
      try {
        mmSocket.close();
      } catch (IOException e) {
        Log.e(TAG, "close() of connect socket failed", e);
      }
    }
  }
  
  private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    public ConnectedThread(BluetoothSocket socket) {
      Log.d(TAG, "create ConnectedThread");
      mmSocket = socket;
      InputStream tmpIn = null;
      OutputStream tmpOut = null;
      // Get the BluetoothSocket input and output streams
      try {
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
      } catch (IOException e) {
        Log.e(TAG, "temp sockets not created", e);
      }
      mmInStream = tmpIn;
      mmOutStream = tmpOut;
    }
    public void run() {
      Log.i(TAG, "BEGIN mConnectedThread");
      byte[] buffer = new byte[1024];
      int bytes;
      // Keep listening to the InputStream while connected
      while (true) {
        try {
          // Read from the InputStream
          bytes = mmInStream.read(buffer);
          // Send the obtained bytes to the UI Activity
          mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
              -1, buffer).sendToTarget();
        } catch (IOException e) {
          Log.e(TAG, "disconnected", e);
          connectionLost();
          break;
        }
      }
    }
    
    public void write(byte[] buffer) {
      try {
        mmOutStream.write(buffer);
        // Share the sent message back to the UI Activity
        mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
            buffer).sendToTarget();
      } catch (IOException e) {
        Log.e(TAG, "Exception during write", e);
      }
    }
    public void cancel() {
      try {
        mmSocket.close();
      } catch (IOException e) {
        Log.e(TAG, "close() of connect socket failed", e);
      }
    }
  }
}
您可能感兴趣的文章:Android蓝牙开发深入解析详解Android——蓝牙技术 带你实现终端间数据传输Android单片机与蓝牙模块通信实例代码Android Bluetooth蓝牙技术使用流程详解分享Android 蓝牙4.0(ble)开发的解决方案android实现蓝牙文件发送的实例代码,支持多种机型Android手机通过蓝牙连接佳博打印机的实例代码Android系统中的蓝牙连接程序编写实例教程Android 获取蓝牙Mac地址的正确方法Android实现蓝牙(BlueTooth)设备检测连接


免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

Android蓝牙通信聊天实现发送和接受功能

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

Android蓝牙通信聊天实现发送和接受功能

很不错的蓝牙通信demo实现发送和接受功能,就用了两个类就实现了,具体内容如下 说下思路把 主要有两个类 主界面类 和 蓝牙聊天服务类 。 首先创建线程 实际上就是创建BluetoothChatService() (蓝牙聊天服务类) 这个时
2022-06-06

Android基于socket实现的简单C/S聊天通信功能

本文实例讲述了Android基于socket实现的简单C/S聊天通信功能。分享给大家供大家参考,具体如下: 主要想法:在客户端上发送一条信息,在后台开辟一个线程充当服务端,收到消息就立即回馈给客户端。 第一步:创建一个继续Activity的
2022-06-06

编程热搜

  • Android:VolumeShaper
    VolumeShaper(支持版本改一下,minsdkversion:26,android8.0(api26)进一步学习对声音的编辑,可以让音频的声音有变化的播放 VolumeShaper.Configuration的三个参数 durati
    Android:VolumeShaper
  • Android崩溃异常捕获方法
    开发中最让人头疼的是应用突然爆炸,然后跳回到桌面。而且我们常常不知道这种状况会何时出现,在应用调试阶段还好,还可以通过调试工具的日志查看错误出现在哪里。但平时使用的时候给你闹崩溃,那你就欲哭无泪了。 那么今天主要讲一下如何去捕捉系统出现的U
    Android崩溃异常捕获方法
  • android开发教程之获取power_profile.xml文件的方法(android运行时能耗值)
    系统的设置–>电池–>使用情况中,统计的能耗的使用情况也是以power_profile.xml的value作为基础参数的1、我的手机中power_profile.xml的内容: HTC t328w代码如下:
    android开发教程之获取power_profile.xml文件的方法(android运行时能耗值)
  • Android SQLite数据库基本操作方法
    程序的最主要的功能在于对数据进行操作,通过对数据进行操作来实现某个功能。而数据库就是很重要的一个方面的,Android中内置了小巧轻便,功能却很强的一个数据库–SQLite数据库。那么就来看一下在Android程序中怎么去操作SQLite数
    Android SQLite数据库基本操作方法
  • ubuntu21.04怎么创建桌面快捷图标?ubuntu软件放到桌面的技巧
    工作的时候为了方便直接打开编辑文件,一些常用的软件或者文件我们会放在桌面,但是在ubuntu20.04下直接直接拖拽文件到桌面根本没有效果,在进入桌面后发现软件列表中的软件只能收藏到面板,无法复制到桌面使用,不知道为什么会这样,似乎并不是很
    ubuntu21.04怎么创建桌面快捷图标?ubuntu软件放到桌面的技巧
  • android获取当前手机号示例程序
    代码如下: public String getLocalNumber() { TelephonyManager tManager =
    android获取当前手机号示例程序
  • Android音视频开发(三)TextureView
    简介 TextureView与SurfaceView类似,可用于显示视频或OpenGL场景。 与SurfaceView的区别 SurfaceView不能使用变换和缩放等操作,不能叠加(Overlay)两个SurfaceView。 Textu
    Android音视频开发(三)TextureView
  • android获取屏幕高度和宽度的实现方法
    本文实例讲述了android获取屏幕高度和宽度的实现方法。分享给大家供大家参考。具体分析如下: 我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现。下面就介绍讲一讲如何获取屏幕的物理尺寸 下面的代码即
    android获取屏幕高度和宽度的实现方法
  • Android自定义popupwindow实例代码
    先来看看效果图:一、布局
  • Android第一次实验
    一、实验原理 1.1实验目标 编程实现用户名与密码的存储与调用。 1.2实验要求 设计用户登录界面、登录成功界面、用户注册界面,用户注册时,将其用户名、密码保存到SharedPreference中,登录时输入用户名、密码,读取SharedP
    Android第一次实验

目录