【问题标题】:How to get the data from a device to an android application using bluetooth?如何使用蓝牙将数据从设备获取到 Android 应用程序?
【发布时间】:2017-10-03 10:51:14
【问题描述】:

我希望设备上显示的数据使用Bluetooth 显示在我的android 应用程序上。 I have gone through this。但我不知道如何接收数据并将其显示在我的应用程序中。有人可以帮忙吗?

【问题讨论】:

    标签: java android bluetooth


    【解决方案1】:

    首先你必须找到设备使用 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();
        }
    }
    

    //发送数据到蓝牙

    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();
        }
    }
    

    【讨论】:

    • 设备A只发送数据,设备B只接收数据。现在在上面的代码中 public void beginListenForData() 是写在接收端对吗??
    • 不,你必须在同一个班级里写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多