android蓝牙使用方法

来源:互联网 发布:剑桥儿童英语启蒙软件 编辑:程序博客网 时间:2024/05/21 02:21

    public BroadcastReceivermBTReceiver;

    publicstatic BluetoothSocketmBTSocket;

    public BluetoothAdaptermBTAdapter;

    private ButtonbtnSearchDevices;

    private ToggleButtontBtnBTSwitch;

    privateBluetoothDevice mBTDevice;

    privateArrayAdapter<String>adtDvcs;

    private List<String>lstDvcsStr = newArrayList<String>(); 

    private ListViewlvDevicesList;

 

 

//初始化蓝牙适配器     

 mBTAdapter = BluetoothAdapter.getDefaultAdapter();//获取本地蓝牙适配器,即蓝牙设备.如果打开本地蓝牙设备不成功,提示信息,结束程序

       

        if (mBTAdapter ==null){

            Toast.makeText(BTConnectActivity.this," No devices supporting Bluetooth! ", Toast.LENGTH_SHORT).show();

            this.finish();

        }//是否有蓝牙

 

//打开蓝牙

if(!mBTAdapter.isEnabled()){

 Intent enabler = newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

                        startActivityForResult(enabler,REQUEST_ENABLE_BT);

 

//注册广播接收器

        // Set up BroadCast Receiver

        mBTReceiver =new BroadcastReceiver(){

            publicvoid onReceive(Contextcontext,Intent intent){

               Stringact = intent.getAction();

               // To see whether the action is that already founddevices

               if(act.equals(BluetoothDevice.ACTION_FOUND)){

                   // If found one device, get the device object

                   BluetoothDevicetmpDvc = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                   // Put the name & address into a string

                   StringtmpDvcStr = tmpDvc.getName()+"|"+tmpDvc.getAddress();

                   if (lstDvcsStr.indexOf(tmpDvcStr)==-1){

                      // Avoid duplicate add devices

                      lstDvcsStr.add(tmpDvcStr);

                      adtDvcs.notifyDataSetChanged();

                      Toast.makeText(BTConnectActivity.this,"Find a new device!",Toast.LENGTH_SHORT).show();

                   }

               }

               if(act.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){

                   Toast.makeText(BTConnectActivity.this," Searching Complete!",Toast.LENGTH_SHORT).show();

               }

          

               if (act.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)){

                 Toast.makeText(BTConnectActivity.this,"Begin Searching Devices", Toast.LENGTH_SHORT).show();

               }

            }

        };

       

        //Register the broadcastReceiver

        IntentFilter filter = newIntentFilter(BluetoothDevice.ACTION_FOUND);

        registerReceiver(mBTReceiver,filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

        registerReceiver(mBTReceiver,filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        registerReceiver(mBTReceiver,filter);

 

//搜索蓝牙设备

               if (mBTAdapter.isDiscovering()){

                   Toast.makeText(BTConnectActivity.this,"Already Searching",Toast.LENGTH_SHORT).show();

               }

              else{

                 lstDvcsStr.clear();

                 adtDvcs.notifyDataSetChanged();

                 mBTDevice = null;

                 mBTAdapter.startDiscovery();

               }

 

//连接蓝牙

// Create Click listener for theitems on devices list

        lvDevicesList.setOnItemClickListener(newAdapterView.OnItemClickListener(){

            @Override

            publicvoidonItemClick(AdapterView<?> arg0, View arg1,int arg2,

                 long arg3){

               if (mBTAdapter ==null)

                   Toast.makeText(BTConnectActivity.this,"No devices support BlueTooth", Toast.LENGTH_SHORT).show();

               else{

                   // stop searching

                   mBTAdapter.cancelDiscovery();

                   // Get address of remote device

                   Stringstr = lstDvcsStr.get(arg2);

                   String[]dvcValues = str.split("\\|");

                   StringdvcAddr = dvcValues[1];

                   //UUID dvcUUID = UUID.randomUUID();

                   //00001101-0000-1000-8000-00805F9B34FB SPP protocal

                   UUIDdvcUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

                   // Set BT device

                   mBTDevice = mBTAdapter.getRemoteDevice(dvcAddr);

                   // Connect Device

                   try{

                      mBTSocket =mBTDevice.createRfcommSocketToServiceRecord(dvcUUID);

                     mBTSocket.connect();

                   }

                   catch(IOException e){

                      e.printStackTrace();

                   }

               }             

            }

        });   

 

 

//返回消息

   publicvoidonActivityResult(intRequestCode,intResultCode,Intent data){

       switch(RequestCode){

       caseREQUEST_ENABLE_BT:

          if(ResultCode ==RESULT_OK){

              Toast.makeText(this.getApplicationContext(),"BT Launched!", Toast.LENGTH_SHORT).show();

          }

          else

              if(ResultCode ==RESULT_CANCELED){

                   Toast.makeText(this.getApplicationContext(),"Launched BT cancled!", Toast.LENGTH_SHORT).show();             

              }

          break;

       }

}

 

 

//接收数据
privateBTReadThreadmReadThread= newBTReadThread(50);

 

           if(BTConnectActivity.mBTSocket.getInputStream()!=null)

           {

              enRead =true;

              mReadThread.start();

           }

 

//接收进程

    class BTReadThreadextends Thread{

       privateintwait = 50;// Time to wait

       public BTReadThread(int wait){

           this.wait = wait;

       }

      

       publicvoid run(){

           while(enRead){

              try{

if (BTConnectActivity.mBTSocket.getInputStream()!=null)

{

byte[] bffer =newbyte[1024];

int len = BTConnectActivity.mBTSocket.getInputStream().read(tmp);//读入数据read三个参数的时候,分别是bufferoffsetmaxlength。返回值是接收到的数据的个数)

Stringstr = newString(bffer,0,len);//源、起始位置、结束位置.接收到的字符存放在str中。

 

//发送数据

OutputStream os = _socket.getOutputStream();  //蓝牙连接输出流

          byte[] bos =edit0.getText().toString().getBytes();

          os.write(bos_new);  


1 0