如何使用蓝牙从设备获取数据到Android应用程序?

问题描述:

我想使用Bluetooth在我的android应用程序上显示设备上显示的数据。 I have gone through this。但我没有得到如何接收数据并将其显示在我的应用程序中。谁能帮忙?如何使用蓝牙从设备获取数据到Android应用程序?

首先,你必须找到使用 onCreate方法的设备 //打开蓝牙连接

openButton.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      pDialog = new ProgressDialog(Activity.this); 


      new AsyncTask<Void, Void, Void>() 
      { 
       @Override 
       protected Void doInBackground(Void... params) 
       { 
        try { 
         findBT(); 
         openBT(); 


        } catch (IOException ex) { 
         ex.printStackTrace(); 
        } 
        return null; 
       } 

       @Override 
       protected void onPostExecute(Void result) 
       { 

       } 
      }.execute(); 

     } 
    }); 

然后你就可以使用下面的方法将数据传递

public void findBT() { 

    try { 
     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

     if(mBluetoothAdapter == null) { 
      Toast.makeText(getApplicationContext(),"Bluetooth Not Found...!",Toast.LENGTH_LONG).show(); 
     } 

     if(!mBluetoothAdapter.isEnabled()) { 
      Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableBluetooth, 0); 
     } 

     Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); 

     if(pairedDevices.size() > 0) { 
      for (BluetoothDevice device : pairedDevices) { 
       Log.d("Devices","============>"+device.getName()); 
       // RPP300 is the name of the bluetooth device 
       // we got this name from the list of paired devices 
       //if (device.getName()=="NP100S28C9") { 
       mmDevice = device; 
       break; 

      } 

     } 


    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 
// tries to open a connection to the bluetooth device 
public void openBT() throws IOException { 

    try { 

     // Standard SerialPortService ID 
     UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); 

     if(mmDevice != null) { 
      mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); 
      mmSocket.connect(); 
      mmOutputStream = mmSocket.getOutputStream(); 
      mmInputStream = mmSocket.getInputStream(); 

      beginListenForData(); 

      btnPrint.setEnabled(true); 

     } 
     else{ 

      Toast.makeText(getApplicationContext(),"Paired Bluthooth not Found..!",Toast.LENGTH_SHORT).show(); 
     } 

    } catch (Exception e) { 
     pDialog.dismiss(); 
     e.printStackTrace(); 

    } 
} 


public void beginListenForData() { 
    try { 

     final Handler handler = new Handler(); 
     // this is the ASCII code for a newline character 
     final byte delimiter = 10; 

     stopWorker = false; 
     readBufferPosition = 0; 
     readBuffer = new byte[1024]; 

     workerThread = new Thread(new Runnable() { 
      public void run() { 

       while (!Thread.currentThread().isInterrupted() && !stopWorker) { 

        try { 

         int bytesAvailable = mmInputStream.available(); 

         if (bytesAvailable > 0) { 

          byte[] packetBytes = new byte[bytesAvailable]; 
          mmInputStream.read(packetBytes); 

          for (int i = 0; i < bytesAvailable; i++) { 

           byte b = packetBytes[i]; 
           if (b == delimiter) { 

            byte[] encodedBytes = new byte[readBufferPosition]; 
            System.arraycopy(
              readBuffer, 0, 
              encodedBytes, 0, 
              encodedBytes.length 
            ); 

            // specify US-ASCII encoding 
            final String data = new String(encodedBytes, "US-ASCII"); 
            readBufferPosition = 0; 

            // tell the user data were sent to bluetooth printer device 
            handler.post(new Runnable() { 
             public void run() { 
              myLabel.setText(data); 
             } 
            }); 

           } else { 
            readBuffer[readBufferPosition++] = b; 
           } 
          } 
         } 

        } catch (IOException ex) { 
         stopWorker = true; 
        } 

       } 
      } 
     }); 

     workerThread.start(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

//将数据发送到blutooth

public void sendData() throws IOException { 
    try { 

     // the text typed by the user 
     String data = "your data"; 
     String msg = data; 
     msg += "\n"; 
     mmOutputStream.write(msg.getBytes()); 

     // tell the user data were sent 
     Toast.makeText(getApplicationContext(),"Data send Successfully...!",Toast.LENGTH_SHORT).show(); 
     closeButton.setEnabled(true); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

谢谢..我会实施并检查它...... – AndroidNwB

+0

如果工作正常的话给我投票.. :) – Prashant

+0

设备A只会发送数据,设备B只会收到数据。现在在上面的代码中_public void beginListenForData()_将被写入接收端。 – AndroidNwB