How use Bluetooth GPS modul in app?

2019-03-11 18:01发布

问题:

I'm working on app, which uses GPS data. I have an external bluetooth GPS device, but I can't find how to use the external GPS Bluetooth module. I added the bluetooth permission into my AndroidManifest file, but I dont know how to continue...

Please help.

回答1:

You should create a connection to the device as described in tutorial Peter pointed.

  1. Discover devices and present a list to the user to select one. I assume, you have done this and you now have BluetoothDevice device variable set to your device.
  2. Connect as client:

    // This is the default UUID you set for connection - it should work
    private static final UUID DEFAULT_SPP_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB"); 
    
    // ....
    
    BluetoothSocket bluetoothSocket = device
             .createRfcommSocketToServiceRecord(DEFAULT_SPP_UUID);
    
    // ....
    
    bluetoothSocket.connect(); // Do this when you want to start data retrieval
    
  3. Retrieve information. You can now open an InputStream, from which NMEA messages come in plain text. So you can use BufferedReader for convenience and read messages line by line. Something like this:

    // After successful connect you can open InputStream
    InputStream in = bluetoothSocket.getInputStream();
    InputStreamReader isr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(isr);
    
    while (true) {
        String nmeaMessage = br.readLine();
        Log.d("NMEA", nmeaMessage);
        // parse NMEA messages
    }
    
    // !!!CLOSE Streams!!!
    

REMEMBER: this code is very simplified. In real application every connection to network, device or filesystem resource should be closed when not needed, errors (Exceptions) properly handled and displayed to user in a readable and understandable format.



回答2:

Android only supports Bluetooth RFCOMM (serial emulation) protocol. Make sure your GPS supports this protocol.

Then start with the provided bluetooth tutorial.