Advertisement
Guest User

Bluetooth-Android

a guest
Jul 10th, 2015
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.37 KB | None | 0 0
  1. package com.example.lilardi.bluetoothsample;
  2.  
  3. import android.app.Activity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothSocket;
  7. import android.content.Intent;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.view.View;
  11. import android.widget.TextView;
  12. import android.widget.EditText;
  13. import android.widget.Button;
  14.  
  15. import org.json.JSONException;
  16. import org.json.JSONObject;
  17.  
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.util.Set;
  22. import java.util.UUID;
  23.  
  24. public class BluetoothTest extends Activity
  25. {
  26.     TextView myLabel;
  27.     TextView temperatureData;
  28.     EditText myTextbox;
  29.     BluetoothAdapter mBluetoothAdapter;
  30.     BluetoothSocket mmSocket;
  31.     BluetoothDevice mmDevice;
  32.     OutputStream mmOutputStream;
  33.     InputStream mmInputStream;
  34.     Thread workerThread;
  35.     byte[] readBuffer;
  36.     int readBufferPosition;
  37.     int counter;
  38.     volatile boolean stopWorker;
  39.     String selectedBt;
  40.  
  41.     @Override
  42.     public void onCreate(Bundle savedInstanceState)
  43.     {
  44.         super.onCreate(savedInstanceState);
  45.         setContentView(R.layout.activity_bluetooth_test);
  46.  
  47.         selectedBt = getIntent().getStringExtra("btName");
  48.  
  49.         Button openButton = (Button)findViewById(R.id.open);
  50.         Button sendButton = (Button)findViewById(R.id.send);
  51.         Button closeButton = (Button)findViewById(R.id.close);
  52.         myLabel = (TextView)findViewById(R.id.label);
  53.         temperatureData = (TextView)findViewById(R.id.tempSensorDataLabel);
  54.         myTextbox = (EditText)findViewById(R.id.entry);
  55.  
  56.         try
  57.         {
  58.             findBT();
  59.             openBT();
  60.         }
  61.         catch (IOException ex) { }
  62.  
  63.         //Open Button
  64.         openButton.setOnClickListener(new View.OnClickListener()
  65.         {
  66.             public void onClick(View v)
  67.             {
  68.                 try
  69.                 {
  70.                     findBT();
  71.                     openBT();
  72.                 }
  73.                 catch (IOException ex) { }
  74.             }
  75.         });
  76.  
  77.         //Send Button
  78.         sendButton.setOnClickListener(new View.OnClickListener()
  79.         {
  80.             public void onClick(View v)
  81.             {
  82.                 try
  83.                 {
  84.                     sendData();
  85.                 }
  86.                 catch (IOException ex) { }
  87.             }
  88.         });
  89.  
  90.         //Close button
  91.         closeButton.setOnClickListener(new View.OnClickListener() {
  92.             public void onClick(View v) {
  93.                 try {
  94.                     closeBT();
  95.                 } catch (IOException ex) {
  96.                 }
  97.             }
  98.         });
  99.     }
  100.  
  101.     void findBT()
  102.     {
  103.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  104.         if(mBluetoothAdapter == null)
  105.         {
  106.             myLabel.setText("No bluetooth adapter available");
  107.         }
  108.  
  109.         if(!mBluetoothAdapter.isEnabled())
  110.         {
  111.             Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  112.             startActivityForResult(enableBluetooth, 0);
  113.         }
  114.  
  115.         Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  116.         if(pairedDevices.size() > 0)
  117.         {
  118.             for(BluetoothDevice device : pairedDevices)
  119.             {
  120.                 if(device.getName().equals(selectedBt))
  121.                 {
  122.                     mmDevice = device;
  123.                     break;
  124.                 }
  125.             }
  126.         }
  127.         myLabel.setText("Bluetooth Device Found");
  128.     }
  129.  
  130.     void openBT() throws IOException
  131.     {
  132.         UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
  133.         mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
  134.         mmSocket.connect();
  135.         mmOutputStream = mmSocket.getOutputStream();
  136.         mmInputStream = mmSocket.getInputStream();
  137.  
  138.         beginListenForData();
  139.  
  140.         myLabel.setText("Bluetooth Opened");
  141.     }
  142.  
  143.     void beginListenForData()
  144.     {
  145.         final Handler handler = new Handler();
  146.         final byte delimiter = 10; //This is the ASCII code for a newline character
  147.  
  148.         stopWorker = false;
  149.         readBufferPosition = 0;
  150.         readBuffer = new byte[1024];
  151.         workerThread = new Thread(new Runnable()
  152.         {
  153.             public void run()
  154.             {
  155.                 while(!Thread.currentThread().isInterrupted() && !stopWorker)
  156.                 {
  157.                     try
  158.                     {
  159.                         int bytesAvailable = mmInputStream.available();
  160.                         if(bytesAvailable > 0)
  161.                         {
  162.                             byte[] packetBytes = new byte[bytesAvailable];
  163.                             mmInputStream.read(packetBytes);
  164.                             for(int i=0;i<bytesAvailable;i++)
  165.                             {
  166.                                 byte b = packetBytes[i];
  167.                                 if(b == delimiter)
  168.                                 {
  169.                                     byte[] encodedBytes = new byte[readBufferPosition];
  170.                                     System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
  171.                                     final String data = new String(encodedBytes, "US-ASCII");
  172.                                     try {
  173.                                         final JSONObject dataObj = new JSONObject(data);
  174.  
  175.                                         readBufferPosition = 0;
  176.  
  177.                                         handler.post(new Runnable()
  178.                                         {
  179.                                             public void run()
  180.                                             {
  181.                                                 //myLabel.setText(data);
  182.                                                 //temperatureData.setText(data);
  183.                                                 try {
  184.                                                     temperatureData.append("\n Temperature: "+dataObj.getString("temperature"));
  185.                                                 } catch (JSONException e) {
  186.                                                     e.printStackTrace();
  187.                                                 }
  188.                                             }
  189.                                         });
  190.                                     } catch (JSONException e){}
  191.  
  192.                                 }
  193.                                 else
  194.                                 {
  195.                                     readBuffer[readBufferPosition++] = b;
  196.                                 }
  197.                             }
  198.                         }
  199.                     }
  200.                     catch (IOException ex)
  201.                     {
  202.                         stopWorker = true;
  203.                     }
  204.                 }
  205.             }
  206.         });
  207.  
  208.         workerThread.start();
  209.     }
  210.  
  211.     void sendData() throws IOException
  212.     {
  213.         String msg = myTextbox.getText().toString();
  214.         msg += "\n";
  215.         mmOutputStream.write(msg.getBytes());
  216.         myLabel.setText("Data Sent");
  217.     }
  218.  
  219.     void closeBT() throws IOException
  220.     {
  221.         stopWorker = true;
  222.         mmOutputStream.close();
  223.         mmInputStream.close();
  224.         mmSocket.close();
  225.         myLabel.setText("Bluetooth Closed");
  226.     }
  227. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement