SoFunction
Updated on 2025-04-07

Bluetooth principle Android code implementation

This article shares the code of Android implementation Bluetooth for your reference. The specific content is as follows

package .;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;

public class MainActivity extends Activity
{

  private BluetoothAdapter adapter;

  private MyReceiver receiver;

  private ListView mListView;

  private List<BluetoothDevice> mDevices;

  private . mDeviceAdapter;

  private BluetoothSocket mSocket;

  private EditText et;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    (savedInstanceState);
    setContentView(.activity_main);
    mListView = (ListView) findViewById();
    et = (EditText) findViewById();
    adapter = ();
    ().setContext(this);
    init();
  }

  private void init()
  {
    initListView();
    // Determine whether Bluetooth function is supported    if (adapter == null)
    {
      (this, "This phone does not support Bluetooth", Toast.LENGTH_LONG).show();
      return;
    }
    // Determine whether the Bluetooth function is turned on    if (!())
    {
      // Forced to open//      ();
      Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivity(intent);
    }

    IntentFilter filter = new IntentFilter();
    // Register the broadcast to start the scan    (BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    // Register the end of the broadcast    (BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    // Register to scan the broadcast of the device that has been found    (BluetoothDevice.ACTION_FOUND);
    receiver = new MyReceiver();
    registerReceiver(receiver, filter);
    startBlueServer();
  }

  /**
    * Start Bluetooth service
    */
  private void startBlueServer()
  {
    new Thread()
    {
      @Override
      public void run()
      {
        while (true)
        {
          try
          {
            BluetoothServerSocket serverSocket = adapter
                .listenUsingRfcommWithServiceRecord(
                    "Bluetooth Service",
                    ("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));
            mSocket = ();//block            ().setSocket(mSocket);
          }
          catch (IOException e)
          {
            ();
          }
        }
      }
    }.start();
  }

  public void doClick(View view)
  {
    switch (())
    {
      case :
        ();
        ();
        // Determine whether it is scanning. If it is not scanning, start scanning        if (!() && ())
        {
          (this, "Start scanning for surrounding Bluetooth devices", Toast.LENGTH_LONG)
              .show();
        }
        break;
      case :
        if ("".equals(().toString()))
        {
          (this, "Content cannot be empty", Toast.LENGTH_SHORT).show();
          return;
        }
        if (().getSocket() == null)
        {
          (this, "Didn't connect to the device yet", Toast.LENGTH_SHORT).show();
          return;
        }
        new Thread()
        {
          @Override
          public void run()
          {
            ().sendMessage(
                ().toString());
          }
        }.start();
        break;
      case :
        ().closeSocket();
        break;
    }
  }

  @Override
  protected void onDestroy()
  {
    ();
    if (receiver != null)
    {
      // Log out of the broadcast      unregisterReceiver(receiver);
    }
  }

  private void initListView()
  {
    mDevices = new ArrayList<BluetoothDevice>();
    mDeviceAdapter = new .(this, mDevices);
    (mDeviceAdapter);
    (new ()
    {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
          int position, long id)
      {
        try
        {
          mSocket = mDevices
              .get(position)
              .createRfcommSocketToServiceRecord(
                  ("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));
          ();//block          (, "Connected successfully",
              Toast.LENGTH_SHORT).show();
          ().setSocket(mSocket);
        }
        catch (IOException e)
        {
          ();
        }

      }
    });
  }

  public class MyReceiver extends BroadcastReceiver
  {

    @Override
    public void onReceive(Context context, Intent intent)
    {
      String action = ();
      if ((BluetoothAdapter.ACTION_DISCOVERY_STARTED))
      {
        ("info", "Start Scan");
      }
      else if ((BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
      {
        ("info", "Scan end");
      }
      else if ((BluetoothDevice.ACTION_FOUND))
      {
        BluetoothDevice device = intent
            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        ("info", () + ":" + ());
        if (mDevices != null)
        {
          for (int i = 0; i < (); i++)
          {
            if (()
                .equals((i).getAddress()))
            {
              return;
            }
          }
          (device);
          ();
        }
      }
    }

  }
}


The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.