Android get bluetooth data

How to get the data from a Bluetooth Socket in Android?

I’m new at coding in Android. I’ve been following the book «Professional Android 4 App Development» I am basically trying to figure out a way to receive a bunch of strings over Bluetooth sent by any device. This is what I have so far

public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Set up the window layout setContentView(R.layout.data); ListView myData = (ListView)findViewById(R.id.list); final ArrayListmData = new ArrayList(); final ArrayAdapter aa; aa = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mData); //Bind Array to List View myData.setAdapter(aa); startDiscovery(); String add = BluetoothDevice.EXTRA_DEVICE; BluetoothDevice device = mAdapter.getRemoteDevice(add); connectToServerSocket(device, MY_UUID); mData.add(0, incoming); aa.notifyDataSetChanged(); > 
private ArrayList deviceList = new ArrayList(); private void startDiscovery() < registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND)); if (mAdapter.isEnabled() && !mAdapter.isDiscovering()) deviceList.clear(); mAdapter.startDiscovery(); >BroadcastReceiver discoveryResult = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); deviceList.add(remoteDevice); Log.d(TAG, "Discovered" + remoteDeviceName); >>; 
private void connectToServerSocket(BluetoothDevice device, UUID uuid)< try< BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid); clientSocket.connect(); StringBuilder incoming = new StringBuilder(); listenforData(clientSocket, incoming); transferSocket = clientSocket; >catch(IOException e) < Log.e("BLUETOOTH","Bluetooth client I/O Exception", e); >> 
private void listenforData(BluetoothSocket socket, StringBuilder incoming) < int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; try< InputStream instream = socket.getInputStream(); int bytesRead = -1; while(true)< bytesRead = instream.read(buffer); if (bytesRead != -1)< String result = ""; while((bytesRead == bufferSize)&&(buffer[bufferSize-1]!=0))< result = result + new String(buffer,0,bytesRead-1); bytesRead= instream.read(buffer); >result = result + new String(buffer, 0, bytesRead -1); incoming.append(result); > socket.close(); > >catch (IOException e) < Log.e(TAG, "Message received failed.", e); >finally < >>> 

What I am missing is how to retrieve the strings from the socket listener and place them on the ListView. I need some guidance. Am I even doing this correctly?

Источник

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 . I have gone through this. But I am not getting how to receive the data and display it in my app. Could anyone help?

1 Answer 1

First you have to find the device using OnCreate method // open bluetooth connection

openButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < pDialog = new ProgressDialog(Activity.this); new AsyncTask() < @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 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(); >> 

Источник

Читайте также:  От чего зависит версия bluetooth

How to receive serial data using android bluetooth

I am new to android. I am designing an android application that receives serial data from a hardware device through bluetooth. I am working on Htc desire S. I used the sample Bluetooth chat code to receive data. But the data received is incorrect. It misses some values. Can anyone please provide me any other sample code to receive large amount of data through bluetooth and save it in a file.

5 Answers 5

package Android.Arduino.Bluetooth; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.TextView; import android.widget.EditText; import android.widget.Button; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.UUID; public class MainActivity extends Activity < TextView myLabel; EditText myTextbox; BluetoothAdapter mBluetoothAdapter; BluetoothSocket mmSocket; BluetoothDevice mmDevice; OutputStream mmOutputStream; InputStream mmInputStream; Thread workerThread; byte[] readBuffer; int readBufferPosition; int counter; volatile boolean stopWorker; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); Button openButton = (Button)findViewById(R.id.open); Button sendButton = (Button)findViewById(R.id.send); Button closeButton = (Button)findViewById(R.id.close); myLabel = (TextView)findViewById(R.id.label); myTextbox = (EditText)findViewById(R.id.entry); //Open Button openButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < try < findBT(); openBT(); >catch (IOException ex) < >> >); //Send Button sendButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < try < sendData(); >catch (IOException ex) < >> >); //Close button closeButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < try < closeBT(); >catch (IOException ex) < >> >); > void findBT() < mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null) < myLabel.setText("No bluetooth adapter available"); >if(!mBluetoothAdapter.isEnabled()) < Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); >Set pairedDevices = mBluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) < for(BluetoothDevice device : pairedDevices) < if(device.getName().equals("MattsBlueTooth")) < mmDevice = device; break; >> > myLabel.setText("Bluetooth Device Found"); > void openBT() throws IOException < UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); mmSocket.connect(); mmOutputStream = mmSocket.getOutputStream(); mmInputStream = mmSocket.getInputStream(); beginListenForData(); myLabel.setText("Bluetooth Opened"); >void beginListenForData() < final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character 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>); > else < readBuffer[readBufferPosition++] = b; >> > > catch (IOException ex) < stopWorker = true; >> > >); workerThread.start(); > void sendData() throws IOException < String msg = myTextbox.getText().toString(); msg += "\n"; mmOutputStream.write(msg.getBytes()); myLabel.setText("Data Sent"); >void closeBT() throws IOException < stopWorker = true; mmOutputStream.close(); mmInputStream.close(); mmSocket.close(); myLabel.setText("Bluetooth Closed"); >> 

Here for Manifest: add to Application

// permission must be enabled complete    

Источник

Читайте также:  Connecting bluetooth audio device

Android: Bluetooth — How to read incoming data

I have successfully paired and connected with a Bluetooth device. I am now interested in receiving all data being transferred between the 2 and seeing whats what. I am getting the input stream from the socket and attempting to read it. I return this and just log it. The only way I know of doing this from what I have read is just do read with a byte buffer to return an int. However I should have loads of data coming through. How can I continually read out data being transferred, and also format as bytes rather than an int. Thanks. Full code below:

public class ConnectThread < private BluetoothSocketWrapper bluetoothSocket; private BluetoothDevice device; private boolean secure; private BluetoothAdapter adapter; private ListuuidCandidates; private int candidate; /** * @param device the device * @param secure if connection should be done via a secure socket * @param adapter the Android BT adapter * @param uuidCandidates a list of UUIDs. if null or empty, the Serial PP id is used */ public ConnectThread(BluetoothDevice device, boolean secure, BluetoothAdapter adapter, List uuidCandidates) < this.device = device; this.secure = secure; this.adapter = adapter; this.uuidCandidates = uuidCandidates; if (this.uuidCandidates == null || this.uuidCandidates.isEmpty()) < this.uuidCandidates = new ArrayList(); this.uuidCandidates.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); > > public BluetoothSocketWrapper connect() throws IOException < boolean success = false; while (selectSocket()) < adapter.cancelDiscovery(); try < bluetoothSocket.connect(); success = true; break; >catch (IOException e) < //try the fallback try < bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket()); Thread.sleep(500); bluetoothSocket.connect(); success = true; break; >catch (FallbackException e1) < Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e); >catch (InterruptedException e1) < Log.w("BT", e1.getMessage(), e1); >catch (IOException e1) < Log.w("BT", "Fallback failed. Cancelling.", e1); >> > if (!success) < throw new IOException("Could not connect to device: "+ device.getAddress()); >receiveData(bluetoothSocket); return bluetoothSocket; > private boolean selectSocket() throws IOException < if (candidate >= uuidCandidates.size()) < return false; >BluetoothSocket tmp; UUID uuid = uuidCandidates.get(candidate++); Log.i("BT", "Attempting to connect to Protocol: "+ uuid); if (secure) < tmp = device.createRfcommSocketToServiceRecord(uuid); >else < tmp = device.createInsecureRfcommSocketToServiceRecord(uuid); >bluetoothSocket = new NativeBluetoothSocket(tmp); return true; > public static interface BluetoothSocketWrapper < InputStream getInputStream() throws IOException; OutputStream getOutputStream() throws IOException; String getRemoteDeviceName(); void connect() throws IOException; String getRemoteDeviceAddress(); void close() throws IOException; BluetoothSocket getUnderlyingSocket(); >public static class NativeBluetoothSocket implements BluetoothSocketWrapper < private BluetoothSocket socket; public NativeBluetoothSocket(BluetoothSocket tmp) < this.socket = tmp; >@Override public InputStream getInputStream() throws IOException < return socket.getInputStream(); >@Override public OutputStream getOutputStream() throws IOException < return socket.getOutputStream(); >@Override public String getRemoteDeviceName() < return socket.getRemoteDevice().getName(); >@Override public void connect() throws IOException < socket.connect(); >@Override public String getRemoteDeviceAddress() < return socket.getRemoteDevice().getAddress(); >@Override public void close() throws IOException < socket.close(); >@Override public BluetoothSocket getUnderlyingSocket() < return socket; >> public class FallbackBluetoothSocket extends NativeBluetoothSocket < private BluetoothSocket fallbackSocket; public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException < super(tmp); try < Classclazz = tmp.getRemoteDevice().getClass(); Class[] paramTypes = new Class[] ; Method m = clazz.getMethod("createRfcommSocket", paramTypes); Object[] params = new Object[] ; fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params); > catch (Exception e) < throw new FallbackException(e); >> @Override public InputStream getInputStream() throws IOException < return fallbackSocket.getInputStream(); >@Override public OutputStream getOutputStream() throws IOException < return fallbackSocket.getOutputStream(); >@Override public void connect() throws IOException < fallbackSocket.connect(); >@Override public void close() throws IOException < fallbackSocket.close(); >> public static class FallbackException extends Exception < /** * */ private static final long serialVersionUID = 1L; public FallbackException(Exception e) < super(e); >> public void sendData(BluetoothSocketWrapper socket, int data) throws IOException < ByteArrayOutputStream output = new ByteArrayOutputStream(4); output.write(data); OutputStream outputStream = socket.getOutputStream(); outputStream.write(output.toByteArray()); >public int receiveData(BluetoothSocketWrapper socket) throws IOException < byte[] buffer = new byte[256]; ByteArrayInputStream input = new ByteArrayInputStream(buffer); InputStream inputStream = socket.getInputStream(); inputStream.read(buffer); return input.read(); >> 

Источник

Оцените статью
Adblock
detector