Advertisement
Guest User

bluetooth connection

a guest
Aug 12th, 2014
1,391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.74 KB | None | 0 0
  1. package com.example.blauzahn;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.lang.reflect.Method;
  7. import java.util.ArrayList;
  8. import java.util.Set;
  9. import java.util.UUID;
  10.  
  11. import android.os.Build;
  12. import android.os.Bundle;
  13. import android.os.Handler;
  14. import android.preference.PreferenceManager;
  15. import android.annotation.SuppressLint;
  16. import android.app.Activity;
  17. import android.bluetooth.BluetoothAdapter;
  18. import android.bluetooth.BluetoothDevice;
  19. import android.bluetooth.BluetoothSocket;
  20. import android.content.BroadcastReceiver;
  21. import android.content.Context;
  22. import android.content.Intent;
  23. import android.content.IntentFilter;
  24. import android.content.SharedPreferences;
  25. import android.content.res.Configuration;
  26. import android.util.Log;
  27. import android.view.Menu;
  28. import android.view.MenuItem;
  29. import android.view.View;
  30. import android.view.View.OnClickListener;
  31. import android.widget.Button;
  32. import android.widget.TextView;
  33. import android.widget.Toast;
  34.  
  35. public class MainActivity extends Activity
  36. {
  37.     private static final int RESULT_SETTINGS = 1;
  38.     private static String logtag = "bluetooth";                 //for use as the tag when logging
  39.    
  40.     private String moduleName;
  41.     private String moduleAddress;
  42.    
  43.     Button buttonStart, buttonStop, connectButton, buttonProgram;
  44.     TextView txtArduino, status;
  45.     Handler h;
  46.  
  47.     private Set<BluetoothDevice> pairedDevices;
  48.     private ArrayList<String> mArrayAdapterName = new ArrayList<String>();
  49.     private ArrayList<String> mArrayAdapterAddress = new ArrayList<String>();
  50.        
  51.     final int RECIEVE_MESSAGE = 1;                                  // Status  for Handler
  52.     private BluetoothAdapter btAdapter = null;
  53.     private BluetoothSocket btSocket = null;
  54.     private StringBuilder sb = new StringBuilder();
  55.        
  56.     private ConnectedThread mConnectedThread;
  57.     private boolean isConnected;
  58.        
  59.     // SPP UUID service
  60.     private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  61.    
  62.     @SuppressLint("HandlerLeak")
  63.     @Override
  64.     protected void onCreate(Bundle savedInstanceState)
  65.     {
  66.         super.onCreate(savedInstanceState);
  67.         setContentView(R.layout.activity_main);
  68.        
  69.         readModuleName();
  70.        
  71.         buttonProgram = (Button)findViewById(R.id.buttonProgram);
  72.         buttonStart = (Button)findViewById(R.id.buttonStart);        
  73.         buttonStop = (Button)findViewById(R.id.buttonStop);        
  74.         connectButton = (Button)findViewById(R.id.connectButton);        
  75.         connectButton.setOnClickListener(connectListener);          // Register the onClick listener with the implementation above
  76.         txtArduino = (TextView) findViewById(R.id.txtArduino);      // for display the received data from the device
  77.        
  78.         // Disable buttons
  79.         buttonStop.setEnabled(false);
  80.         buttonStart.setEnabled(false);
  81.         buttonProgram.setEnabled(false);
  82.        
  83.         h = new Handler() {
  84.             public void handleMessage(android.os.Message msg)
  85.             {
  86.                 switch (msg.what)
  87.                 {
  88.                 case RECIEVE_MESSAGE:                               // if receive massage
  89.                     byte[] readBuf = (byte[]) msg.obj;
  90.                     if (msg.arg1 > 0)
  91.                     {  
  92.                         String answer = bytesToHexString(readBuf);
  93.                         answer = answer.substring(0, msg.arg1 * 2);
  94.                         txtArduino.setText(answer);                 // update TextView
  95.                         buttonStop.setEnabled(true);
  96.                         buttonStart.setEnabled(true);
  97.                         buttonProgram.setEnabled(true);
  98.                     }
  99.                     Log.d(logtag, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
  100.                     break;
  101.                 }
  102.             };
  103.         };
  104.        
  105.         btAdapter = BluetoothAdapter.getDefaultAdapter();           // get Bluetooth adapter
  106.         checkBTState();
  107.        
  108.         buttonProgram.setOnClickListener(new OnClickListener()
  109.         {
  110.             public void onClick(View v)
  111.             {      
  112.                 buttonProgram.setEnabled(false);
  113.                 Log.d(logtag,"onClick() called - start button");
  114.                
  115.                 byte[] program = hexStringToByteArray("8A0501A001FF005F");     
  116.                 mConnectedThread.writeBytes(program);
  117.                
  118.                 Log.d(logtag,"onClick() ended - start button");
  119.             }
  120.         });
  121.        
  122.         buttonStart.setOnClickListener(new OnClickListener()
  123.         {
  124.             public void onClick(View v)
  125.             {
  126.                 buttonStart.setEnabled(false);
  127.                
  128.                 Log.d(logtag,"onClick() called - start button");
  129.  
  130.                 byte[] startVib = hexStringToByteArray("8a010808");
  131.                 mConnectedThread.writeBytes(startVib);
  132.                 Log.d(logtag,"onClick() ended - start button");
  133.             }
  134.         });
  135.        
  136.         buttonStop.setOnClickListener(new OnClickListener()
  137.         {
  138.             public void onClick(View v)
  139.             {
  140.                 buttonStop.setEnabled(false);
  141.                
  142.                 Log.d(logtag,"onClick() called - stop button");
  143.                
  144.                 byte[] stopVib = hexStringToByteArray("8a010707");
  145.                 mConnectedThread.writeBytes(stopVib);
  146.                 Log.d(logtag,"onClick() ended - stop button");
  147.             }
  148.         });
  149.     }
  150.    
  151.    
  152.     @Override
  153.     public void onConfigurationChanged(Configuration newConfig)
  154.     {
  155.       super.onConfigurationChanged(newConfig);
  156.       setContentView(R.layout.activity_main);
  157.     }
  158.    
  159.     // Establish the connection
  160.     private OnClickListener connectListener = new OnClickListener()
  161.     {
  162.         public void onClick(View v)
  163.         {
  164.             Log.d(logtag,"onClick() called - connect Button");
  165.            
  166.             if (btAdapter != null && btAdapter.isEnabled())
  167.             {
  168.                 pairedDevices = btAdapter.getBondedDevices();
  169.                
  170.                 // If there are paired devices
  171.                 if (pairedDevices.size() > 0)
  172.                 {
  173.                     // Loop through paired devices
  174.                     for (BluetoothDevice device : pairedDevices)
  175.                     {
  176.                         // Add the name and address to an array adapter to show in a ListView
  177.                         mArrayAdapterName.add(device.getName());
  178.                         mArrayAdapterAddress.add(device.getAddress());
  179.                     }
  180.                 }
  181.                
  182.                 if (!mArrayAdapterName.contains(moduleName))
  183.                 {
  184.                     if (btAdapter.isDiscovering())
  185.                     {
  186.                         btAdapter.cancelDiscovery();
  187.                     }
  188.                     btAdapter.startDiscovery();
  189.                    
  190.                     // Register the BroadcastReceiver
  191.                     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  192.                     registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
  193.                 }
  194.                 else
  195.                 {
  196.                     int index = mArrayAdapterName.indexOf(moduleName);
  197.                     moduleAddress = mArrayAdapterAddress.get(index);
  198.                     connectToModule();
  199.                 }
  200.                
  201.             }
  202.             Log.d(logtag,"onClick() ended - connect Button");
  203.         }
  204.     };
  205.    
  206.    
  207.     public static byte[] hexStringToByteArray(String s)
  208.     {
  209.         int len = s.length();
  210.         byte[] data = new byte[len / 2];
  211.         for (int i = 0; i < len; i += 2)
  212.         {
  213.             data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
  214.                                  + Character.digit(s.charAt(i+1), 16));
  215.         }
  216.         return data;
  217.     }
  218.    
  219.     private void checkBTState()
  220.     {
  221.         // Check for Bluetooth support and then check to make sure it is turned on
  222.         // Emulator doesn't support Bluetooth and will return null
  223.         if(btAdapter == null)
  224.         {
  225.             errorExit("Fatal Error", "Bluetooth not support");
  226.         }
  227.         else
  228.         {
  229.             if (btAdapter.isEnabled())
  230.             {
  231.                 Log.d(logtag, "...Bluetooth ON...");
  232.             }
  233.             else
  234.             {
  235.                 //Prompt user to turn on Bluetooth
  236.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  237.                 startActivityForResult(enableBtIntent, 1);
  238.             }
  239.         }
  240.     }
  241.    
  242.    
  243.    
  244.     private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
  245.     {
  246.         if(Build.VERSION.SDK_INT >= 10)
  247.         {
  248.             try
  249.             {
  250.                 final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
  251.                 return (BluetoothSocket) m.invoke(device, MY_UUID);
  252.             }
  253.             catch (Throwable e)
  254.             {
  255.                 Log.e(logtag, "Could not create Insecure RFComm Connection",e);
  256.             }
  257.         }
  258.         return  device.createRfcommSocketToServiceRecord(MY_UUID);
  259.     }
  260.    
  261.    
  262.    
  263.    
  264.     private void errorExit(String title, String message)
  265.     {
  266.         Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
  267.         finish();
  268.     }
  269.    
  270.     private void readModuleName()
  271.     {
  272.         SharedPreferences sharedPrefs = PreferenceManager
  273.                 .getDefaultSharedPreferences(this);
  274.         moduleName = sharedPrefs.getString("moduleID", "1337");
  275.     }
  276.      
  277.    
  278.    
  279.     public static String bytesToHexString(byte[] bytes)
  280.     {
  281.         StringBuilder sb = new StringBuilder();
  282.         for(byte b : bytes)
  283.         {
  284.             sb.append(String.format("%02x", b&0xff));
  285.         }
  286.         return sb.toString();
  287.     }
  288.    
  289.    
  290.    
  291.    
  292.    
  293.    
  294.     protected void connectToModule()
  295.     {        
  296.         Log.d(logtag, "...onResume - try connect...");
  297.        
  298.         // Set up a pointer to the remote node using it's address.
  299.         BluetoothDevice device = btAdapter.getRemoteDevice(moduleAddress);
  300.        
  301.         // Two things are needed to make a connection:
  302.         //   A MAC address, which we got above.
  303.         //   A Service ID or UUID.  In this case we are using the
  304.         //     UUID for SPP.
  305.          
  306.         try
  307.         {
  308.             btSocket = createBluetoothSocket(device);
  309.         } catch (Throwable e)
  310.         {
  311.             errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  312.         }
  313.        
  314.         // Discovery is resource intensive.  Make sure it isn't going on
  315.         // when you attempt to connect and pass your message.
  316.         btAdapter.cancelDiscovery();
  317.        
  318.         // Establish the connection.  This will block until it connects.
  319.         Log.d(logtag, "...Connecting...");
  320.         try
  321.         {
  322.             btSocket.connect();
  323.             Log.d(logtag, "....Connection ok...");
  324.         } catch (Throwable e)
  325.         {
  326.             try
  327.             {
  328.                 btSocket.close();
  329.             } catch (Throwable e2)
  330.             {
  331.                 errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  332.             }
  333.         }
  334.          
  335.         // Create a data stream so we can talk to server.
  336.         Log.d(logtag, "...Create Socket...");
  337.        
  338.         mConnectedThread = new ConnectedThread(btSocket);
  339.         mConnectedThread.start();
  340.        
  341.         //buttons geƤndert
  342.         if (btSocket != null)
  343.         {
  344.             isConnected = true;
  345.             // Enable Buttons
  346.             buttonStop.setEnabled(true);
  347.             buttonStart.setEnabled(true);
  348.             buttonProgram.setEnabled(true);
  349.             // Disable connect Button
  350.             connectButton.setEnabled(false);
  351.             status = (TextView) findViewById(R.id.status);
  352.             status.setText(moduleAddress);
  353.         }
  354.     }
  355.    
  356.    
  357.  // Create a BroadcastReceiver for ACTION_FOUND
  358.     private final BroadcastReceiver mReceiver = new BroadcastReceiver()
  359.     {
  360.         public void onReceive(Context context, Intent intent)
  361.         {
  362.             String action = intent.getAction();
  363.             // When discovery finds a device
  364.             if (BluetoothDevice.ACTION_FOUND.equals(action))
  365.             {
  366.                 // Get the BluetoothDevice object from the Intent
  367.                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  368.                 // Add the name and address to an array adapter to show in a ListView
  369.                
  370.                 if (device.getName().equals(moduleName))
  371.                 {
  372.                     moduleAddress = device.getAddress();
  373.                     btAdapter.cancelDiscovery();
  374.                     connectToModule();
  375.                 }
  376.                
  377.             }
  378.         }
  379.     };
  380.    
  381.    
  382.    
  383.     private class ConnectedThread extends Thread {
  384.         private final InputStream mmInStream;
  385.         private final OutputStream mmOutStream;
  386.      
  387.         public ConnectedThread(BluetoothSocket socket) {
  388.             InputStream tmpIn = null;
  389.             OutputStream tmpOut = null;
  390.      
  391.             // Get the input and output streams, using temp objects because
  392.             // member streams are final
  393.             try
  394.             {
  395.                 tmpIn = socket.getInputStream();
  396.                 tmpOut = socket.getOutputStream();
  397.             } catch (Throwable e) { }
  398.      
  399.             mmInStream = tmpIn;
  400.             mmOutStream = tmpOut;
  401.         }
  402.      
  403.         public void run() {
  404.             byte[] buffer = new byte[256];      // buffer store for the stream
  405.             int bytes;                          // bytes returned from read()
  406.  
  407.             // Keep listening to the InputStream until an exception occurs
  408.             while (true)
  409.             {
  410.                 try
  411.                 {
  412.                     // Read from the InputStream
  413.                     bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
  414.                     h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
  415.                 } catch (Throwable e)
  416.                 {
  417.                     break;
  418.                 }
  419.             }
  420.         }
  421.      
  422.         /* Call this from the main activity to send data to the remote device */
  423.         public void writeBytes(byte[] message)
  424.         {
  425.             Log.d(logtag, "...Data to send: " + message + "...");
  426.             try
  427.             {
  428.                 mmOutStream.write(message);
  429.             } catch (Throwable e)           //IOException e
  430.             {
  431.                 Log.d(logtag, "...Error data send: " + e.getMessage() + "...");    
  432.             }
  433.         }
  434.     }
  435.    
  436.    
  437.    
  438.     @Override
  439.     public boolean onCreateOptionsMenu(Menu menu)
  440.     {
  441.         // Inflate the menu; this adds items to the action bar if it is present.
  442.         getMenuInflater().inflate(R.menu.settings, menu);
  443.         return true;
  444.     }
  445.    
  446.     @Override
  447.     public boolean onOptionsItemSelected(MenuItem item)
  448.     {
  449.         switch (item.getItemId())
  450.         {
  451.             case R.id.menu_settings:
  452.                 Intent i = new Intent(this, SettingsActivity.class);
  453.                 startActivityForResult(i, RESULT_SETTINGS);
  454.                 break;
  455.         }
  456.  
  457.         return true;
  458.     }
  459.  
  460.     @Override
  461.     protected void onActivityResult(int requestCode, int resultCode, Intent data)
  462.     {
  463.         super.onActivityResult(requestCode, resultCode, data);
  464.  
  465.         switch (requestCode)
  466.         {
  467.             case RESULT_SETTINGS:
  468.                 readModuleName();
  469.                 break;
  470.         }
  471.     }
  472.    
  473.    
  474.    
  475.      
  476.      
  477.     @Override
  478.     protected void onStart() //activity is started and visible to the user
  479.     {
  480.         Log.d(logtag,"onStart() called");
  481.         super.onStart();  
  482.     }
  483.    
  484.     @Override
  485.     protected void onResume() //activity was resumed and is visible again
  486.     {
  487.         Log.d(logtag,"onResume() called");
  488.        
  489.         if (isConnected) // RECONNECT ON RESUME
  490.         {
  491.             // Set up a pointer to the remote node using it's address.
  492.             BluetoothDevice device = btAdapter.getRemoteDevice(moduleAddress);
  493.            
  494.             // Two things are needed to make a connection:
  495.             //   A MAC address, which we got above.
  496.             //   A Service ID or UUID.  In this case we are using the
  497.             //     UUID for SPP.
  498.              
  499.             try
  500.             {
  501.                 btSocket = createBluetoothSocket(device);
  502.             }
  503.             catch (Throwable e)
  504.             {
  505.                 errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  506.             }
  507.            
  508.             // Discovery is resource intensive.  Make sure it isn't going on
  509.             // when you attempt to connect and pass your message.
  510.             btAdapter.cancelDiscovery();
  511.            
  512.             // Establish the connection.  This will block until it connects.
  513.             Log.d(logtag, "...Connecting...");
  514.             try
  515.             {
  516.                 btSocket.connect();
  517.                 Log.d(logtag, "....Connection ok...");
  518.             }
  519.             catch (Throwable e)
  520.             {
  521.                 try
  522.                 {
  523.                     btSocket.close();
  524.                 }
  525.                 catch (Throwable e2)
  526.                 {
  527.                     errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  528.                 }
  529.             }
  530.              
  531.             // Create a data stream so we can talk to server.
  532.             Log.d(logtag, "...Create Socket...");
  533.            
  534.             mConnectedThread = new ConnectedThread(btSocket);
  535.             mConnectedThread.start();
  536.            
  537.             // Enable Buttons
  538.             buttonStop.setEnabled(true);
  539.             buttonStart.setEnabled(true);
  540.             buttonProgram.setEnabled(true);
  541.         }
  542.         super.onResume();
  543.     }
  544.    
  545.     @Override
  546.     protected void onPause() //device goes to sleep or another activity appears
  547.     {
  548.         Log.d(logtag,"onPause() called");//another activity is currently running (or user has pressed Home)
  549.         if (btAdapter != null)
  550.         {
  551.             if (btAdapter.isDiscovering())
  552.             {
  553.                 unregisterReceiver(mReceiver);
  554.                 btAdapter.cancelDiscovery();
  555.             }
  556.         }
  557.        
  558.         try
  559.         {
  560.             if (btSocket != null)
  561.             {
  562.                 btSocket.close();
  563.             }
  564.         } catch (Throwable t)
  565.         {
  566.             errorExit("Fatal Error", "In onPause() and failed to close socket." + t.getMessage() + ".");
  567.         }
  568.         super.onPause();
  569.     }
  570.      
  571.     @Override
  572.     protected void onStop() //the activity is not visible anymore
  573.     {
  574.         Log.d(logtag,"onStop() called");
  575.         if (btAdapter != null)
  576.         {
  577.             if (btAdapter.isDiscovering())
  578.             {
  579.                 unregisterReceiver(mReceiver);
  580.                 btAdapter.cancelDiscovery();
  581.             }
  582.         }
  583.         super.onStop();
  584.      }
  585.      
  586.     @Override
  587.     protected void onDestroy() //android has killed this activity
  588.     {
  589.         Log.d(logtag,"onDestroy() called");
  590.         if (btAdapter != null)
  591.         {
  592.             if (btAdapter.isDiscovering())
  593.             {
  594.                 unregisterReceiver(mReceiver);
  595.                 btAdapter.cancelDiscovery();
  596.             }
  597.         }
  598.         super.onDestroy();
  599.     }    
  600. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement