欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

蓝牙原理Android代码实现

程序员文章站 2024-03-05 20:46:37
本文实例为大家分享了android实现蓝牙原理代码,供大家参考,具体内容如下 package com.example.se7en.testbluetooth;...

本文实例为大家分享了android实现蓝牙原理代码,供大家参考,具体内容如下

package com.example.se7en.testbluetooth;

import android.app.activity;
import android.bluetooth.bluetoothadapter;
import android.bluetooth.bluetoothdevice;
import android.bluetooth.bluetoothserversocket;
import android.bluetooth.bluetoothsocket;
import android.content.broadcastreceiver;
import android.content.context;
import android.content.intent;
import android.content.intentfilter;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.adapterview;
import android.widget.edittext;
import android.widget.listview;
import android.widget.toast;

import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
import java.util.uuid;

public class mainactivity extends activity
{

  private bluetoothadapter adapter;

  private myreceiver receiver;

  private listview mlistview;

  private list<bluetoothdevice> mdevices;

  private com.example.se7en.testbluetooth.deviceadapter mdeviceadapter;

  private bluetoothsocket msocket;

  private edittext et;

  @override
  protected void oncreate(bundle savedinstancestate)
  {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    mlistview = (listview) findviewbyid(r.id.lv);
    et = (edittext) findviewbyid(r.id.et);
    adapter = bluetoothadapter.getdefaultadapter();
    bluetoothhandler.getinstance().setcontext(this);
    init();
  }

  private void init()
  {
    initlistview();
    // 判断是否支持蓝牙功能
    if (adapter == null)
    {
      toast.maketext(this, "该手机不支持蓝牙功能", toast.length_long).show();
      return;
    }
    // 判断蓝牙功能是否打开
    if (!adapter.isenabled())
    {
      // 强行打开
//      adapter.enable();
      intent intent=new intent(bluetoothadapter.action_request_enable);
      startactivity(intent);
    }

    intentfilter filter = new intentfilter();
    // 注册扫描开始的广播
    filter.addaction(bluetoothadapter.action_discovery_started);
    // 注册扫描结束的广播
    filter.addaction(bluetoothadapter.action_discovery_finished);
    // 注册扫描已经找到设备的广播
    filter.addaction(bluetoothdevice.action_found);
    receiver = new myreceiver();
    registerreceiver(receiver, filter);
    startblueserver();
  }

  /**
   * 启动蓝牙服务
   */
  private void startblueserver()
  {
    new thread()
    {
      @override
      public void run()
      {
        while (true)
        {
          try
          {
            bluetoothserversocket serversocket = adapter
                .listenusingrfcommwithservicerecord(
                    "蓝牙服务",
                    uuid.fromstring("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));
            msocket = serversocket.accept();//阻塞
            bluetoothhandler.getinstance().setsocket(msocket);
          }
          catch (ioexception e)
          {
            e.printstacktrace();
          }
        }
      }
    }.start();
  }

  public void doclick(view view)
  {
    switch (view.getid())
    {
      case r.id.btn:
        mdevices.clear();
        mdeviceadapter.notifydatasetchanged();
        // 判断是否正在扫描,如果没在扫描那么就开始扫描
        if (!adapter.isdiscovering() && adapter.startdiscovery())
        {
          toast.maketext(this, "开始扫描周围的蓝牙设备", toast.length_long)
              .show();
        }
        break;
      case r.id.send:
        if ("".equals(et.gettext().tostring()))
        {
          toast.maketext(this, "内容不能为空", toast.length_short).show();
          return;
        }
        if (bluetoothhandler.getinstance().getsocket() == null)
        {
          toast.maketext(this, "还未连接设备", toast.length_short).show();
          return;
        }
        new thread()
        {
          @override
          public void run()
          {
            bluetoothhandler.getinstance().sendmessage(
                et.gettext().tostring());
          }
        }.start();
        break;
      case r.id.dis:
        bluetoothhandler.getinstance().closesocket();
        break;
    }
  }

  @override
  protected void ondestroy()
  {
    super.ondestroy();
    if (receiver != null)
    {
      // 注销广播
      unregisterreceiver(receiver);
    }
  }

  private void initlistview()
  {
    mdevices = new arraylist<bluetoothdevice>();
    mdeviceadapter = new com.example.se7en.testbluetooth.deviceadapter(this, mdevices);
    mlistview.setadapter(mdeviceadapter);
    mlistview.setonitemclicklistener(new adapterview.onitemclicklistener()
    {
      @override
      public void onitemclick(adapterview<?> parent, view view,
          int position, long id)
      {
        try
        {
          msocket = mdevices
              .get(position)
              .createrfcommsockettoservicerecord(
                  uuid.fromstring("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));
          msocket.connect();//阻塞
          toast.maketext(mainactivity.this, "连接成功",
              toast.length_short).show();
          bluetoothhandler.getinstance().setsocket(msocket);
        }
        catch (ioexception e)
        {
          e.printstacktrace();
        }

      }
    });
  }

  public class myreceiver extends broadcastreceiver
  {

    @override
    public void onreceive(context context, intent intent)
    {
      string action = intent.getaction();
      if (action.equals(bluetoothadapter.action_discovery_started))
      {
        log.i("info", "开始扫描");
      }
      else if (action.equals(bluetoothadapter.action_discovery_finished))
      {
        log.i("info", "扫描结束");
      }
      else if (action.equals(bluetoothdevice.action_found))
      {
        bluetoothdevice device = intent
            .getparcelableextra(bluetoothdevice.extra_device);
        log.i("info", device.getname() + ":" + device.getaddress());
        if (mdevices != null)
        {
          for (int i = 0; i < mdevices.size(); i++)
          {
            if (device.getaddress()
                .equals(mdevices.get(i).getaddress()))
            {
              return;
            }
          }
          mdevices.add(device);
          mdeviceadapter.notifydatasetchanged();
        }
      }
    }

  }
}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。