简体   繁体   English

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

[英]How to get the data from a device to an android application using bluetooth?

I want the data displayed on the device to be displayed on my android application using Bluetooth . 我希望使用Bluetooth在设备上显示的数据显示在我的android应用程序上。 I have gone through this . 我经历了这个 But I am not getting how to receive the data and display it in my app. 但是我没有得到如何接收数据并将其显示在我的应用程序中的信息。 Could anyone help? 有人可以帮忙吗?

First you have to find the device using OnCreate method // open bluetooth connection 首先,您必须使用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();

        }
    });

Then you can pass data by using following method 然后您可以使用以下方法传递数据

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

//Sending data to 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM