Advertisement
Guest User

ArduinoBluetoothAndroid

a guest
Mar 31st, 2013
14,253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.28 KB | None | 0 0
  1. package com.example.myApp;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.util.UUID;
  7.  
  8. import android.app.Activity;
  9. import android.bluetooth.BluetoothAdapter;
  10. import android.bluetooth.BluetoothDevice;
  11. import android.bluetooth.BluetoothSocket;
  12. import android.os.Bundle;
  13. import android.os.Handler;
  14. import android.util.Log;
  15. import android.view.View;
  16. import android.view.View.OnClickListener;
  17. import android.widget.Button;
  18. import android.widget.TextView;
  19. import android.widget.Toast;
  20. import android.widget.ToggleButton;
  21.  
  22. public class Main extends Activity implements OnClickListener {
  23.  
  24.     Button Connect;
  25.     ToggleButton OnOff;
  26.     TextView Result;
  27.     private String dataToSend;
  28.    
  29.     private static final String TAG = "Jon";
  30.     private BluetoothAdapter mBluetoothAdapter = null;
  31.     private BluetoothSocket btSocket = null;
  32.     private OutputStream outStream = null;
  33.     private static String address = "XX:XX:XX:XX:XX:XX";
  34.     private static final UUID MY_UUID = UUID
  35.             .fromString("00001101-0000-1000-8000-00805F9B34FB");
  36.     private InputStream inStream = null;
  37.     Handler handler = new Handler();
  38.     byte delimiter = 10;
  39.     boolean stopWorker = false;
  40.     int readBufferPosition = 0;
  41.     byte[] readBuffer = new byte[1024];
  42.  
  43.     @Override
  44.     protected void onCreate(Bundle savedInstanceState) {
  45.         super.onCreate(savedInstanceState);
  46.         setContentView(R.layout.activity_main);
  47.  
  48.         Connect = (Button) findViewById(R.id.connect);
  49.         OnOff = (ToggleButton) findViewById(R.id.tgOnOff);
  50.         Result = (TextView) findViewById(R.id.msgJonduino);
  51.  
  52.         Connect.setOnClickListener(this);
  53.         OnOff.setOnClickListener(this);
  54.  
  55.         CheckBt();
  56.         BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  57.         Log.e("Jon", device.toString());
  58.  
  59.     }
  60.  
  61.     @Override
  62.     public void onClick(View control) {
  63.         switch (control.getId()) {
  64.         case R.id.connect:
  65.                 Connect();
  66.             break;
  67.         case R.id.tgOnOff:
  68.             if (OnOff.isChecked()) {
  69.                 dataToSend = "1";
  70.                 writeData(dataToSend);
  71.             } else if (!OnOff.isChecked()) {
  72.                 dataToSend = "0";
  73.                 writeData(dataToSend);
  74.             }
  75.             break;
  76.         }
  77.     }
  78.  
  79.     private void CheckBt() {
  80.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  81.  
  82.         if (!mBluetoothAdapter.isEnabled()) {
  83.             Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
  84.                     Toast.LENGTH_SHORT).show();
  85.         }
  86.  
  87.         if (mBluetoothAdapter == null) {
  88.             Toast.makeText(getApplicationContext(),
  89.                     "Bluetooth null !", Toast.LENGTH_SHORT)
  90.                     .show();
  91.         }
  92.     }
  93.    
  94.         public void Connect() {
  95.             Log.d(TAG, address);
  96.             BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  97.             Log.d(TAG, "Connecting to ... " + device);
  98.             mBluetoothAdapter.cancelDiscovery();
  99.             try {
  100.                 btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  101.                 btSocket.connect();
  102.                 Log.d(TAG, "Connection made.");
  103.             } catch (IOException e) {
  104.                 try {
  105.                     btSocket.close();
  106.                 } catch (IOException e2) {
  107.                     Log.d(TAG, "Unable to end the connection");
  108.                 }
  109.                 Log.d(TAG, "Socket creation failed");
  110.             }
  111.            
  112.             beginListenForData();
  113.         }
  114.    
  115.     private void writeData(String data) {
  116.         try {
  117.             outStream = btSocket.getOutputStream();
  118.         } catch (IOException e) {
  119.             Log.d(TAG, "Bug BEFORE Sending stuff", e);
  120.         }
  121.  
  122.         String message = data;
  123.         byte[] msgBuffer = message.getBytes();
  124.  
  125.         try {
  126.             outStream.write(msgBuffer);
  127.         } catch (IOException e) {
  128.             Log.d(TAG, "Bug while sending stuff", e);
  129.         }
  130.     }
  131.  
  132.     @Override
  133.     protected void onDestroy() {
  134.         super.onDestroy();
  135.    
  136.             try {
  137.                 btSocket.close();
  138.             } catch (IOException e) {
  139.             }
  140.     }
  141.    
  142.     public void beginListenForData()   {
  143.          try {
  144.                 inStream = btSocket.getInputStream();
  145.             } catch (IOException e) {
  146.             }
  147.          
  148.             Thread workerThread = new Thread(new Runnable()
  149.             {
  150.                 public void run()
  151.                 {                
  152.                    while(!Thread.currentThread().isInterrupted() && !stopWorker)
  153.                    {
  154.                         try
  155.                         {
  156.                             int bytesAvailable = inStream.available();                        
  157.                             if(bytesAvailable > 0)
  158.                             {
  159.                                 byte[] packetBytes = new byte[bytesAvailable];
  160.                                 inStream.read(packetBytes);
  161.                                 for(int i=0;i<bytesAvailable;i++)
  162.                                 {
  163.                                     byte b = packetBytes[i];
  164.                                     if(b == delimiter)
  165.                                     {
  166.                                         byte[] encodedBytes = new byte[readBufferPosition];
  167.                                         System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
  168.                                         final String data = new String(encodedBytes, "US-ASCII");
  169.                                         readBufferPosition = 0;
  170.                                         handler.post(new Runnable()
  171.                                         {
  172.                                             public void run()
  173.                                             {
  174.                                                
  175.                                                 if(Result.getText().toString().equals("..")) {
  176.                                                     Result.setText(data);
  177.                                                 } else {
  178.                                                     Result.append("\n"+data);
  179.                                                 }
  180.                                                
  181.                                                 /* You also can use Result.setText(data); it won't display multilines
  182.                                                 */
  183.                                                
  184.                                             }
  185.                                         });
  186.                                     }
  187.                                     else
  188.                                     {
  189.                                         readBuffer[readBufferPosition++] = b;
  190.                                     }
  191.                                 }
  192.                             }
  193.                         }
  194.                         catch (IOException ex)
  195.                         {
  196.                             stopWorker = true;
  197.                         }
  198.                    }
  199.                 }
  200.             });
  201.  
  202.             workerThread.start();
  203.         }
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement