Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.lang.reflect.Method;
  5. import java.util.UUID;
  6.  
  7.  
  8. import android.app.Activity;
  9. import android.bluetooth.BluetoothAdapter;
  10. import android.bluetooth.BluetoothDevice;
  11. import android.bluetooth.BluetoothSocket;
  12. import android.content.Intent;
  13. import android.os.Build;
  14. import android.os.Bundle;
  15. import android.os.Handler;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.view.View.OnClickListener;
  19. import android.widget.Button;
  20. import android.widget.TextView;
  21. import android.widget.Toast;
  22.  
  23. public class MainActivity extends Activity {
  24.   private static final String TAG = "bluetooth2";
  25.    
  26.   Button btnOn, btnOff;
  27.   TextView txtArduino, txtTemperature;
  28.   Handler h;
  29.  
  30.  
  31.   final int RECIEVE_MESSAGE = 1;    
  32.   private BluetoothAdapter btAdapter = null;
  33.   private BluetoothSocket btSocket = null;
  34.   private StringBuilder sb = new StringBuilder();
  35.    
  36.   private ConnectedThread mConnectedThread;
  37.    
  38.   // SPP UUID service
  39.   private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  40.  
  41.   // MAC-address of Bluetooth module (you must edit this line)
  42.   private static String address = "20:13:05:07:02:07";
  43.    
  44.  
  45.   @Override
  46.   public void onCreate(Bundle savedInstanceState) {
  47.     super.onCreate(savedInstanceState);
  48.  
  49.     setContentView(R.layout.activity_main);
  50.  
  51.     btnOn = (Button) findViewById(R.id.button2);                  // button LED ON
  52.     btnOff = (Button) findViewById(R.id.button3);                // button LED OFF
  53.     txtArduino = (TextView) findViewById(R.id.textView2);
  54.     txtTemperature = (TextView) findViewById(R.id.textView3);
  55.    
  56.     h = new Handler() {
  57.         public void handleMessage(android.os.Message msg) {
  58.             switch (msg.what) {
  59.             case RECIEVE_MESSAGE:                                                   // if receive massage
  60.                 byte[] readBuf = (byte[]) msg.obj;
  61.                 String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
  62.                 sb.append(strIncom);                                                // append string
  63.                 int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
  64.                 if (endOfLineIndex > 0) {                                            // if end-of-line,
  65.                     String sbprint = sb.substring(0, endOfLineIndex);               // extract string
  66.                     sb.delete(0, sb.length());                                      // and clear
  67.                     if (sbprint.toCharArray()[0] == '*')
  68.                     {
  69.                         txtTemperature.setText("Teplota z čidla DHT11 je " +  sbprint.substring(1, sbprint.length()                                                                                                                                                                                                                                                                               ) + "°C");
  70.                     }
  71.                     else
  72.                     {
  73.                         txtArduino.setText(sbprint + "\n" +  txtArduino.getText());            // update TextView  
  74.                     }
  75.                 }
  76.                
  77.                 break;
  78.             }
  79.         };
  80.     };
  81.    
  82.     btAdapter = BluetoothAdapter.getDefaultAdapter();
  83.    
  84.    
  85.    
  86.     checkBTState();
  87.    
  88.  
  89.     // tlačítko ON
  90.     btnOn.setOnClickListener(new OnClickListener() {
  91.       public void onClick(View v) {
  92.        
  93.         mConnectedThread.write("1");    // Send "1" via Bluetooth
  94.         //Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
  95.       }
  96.     });
  97.  
  98.     btnOff.setOnClickListener(new OnClickListener() {
  99.       public void onClick(View v) {
  100.          
  101.         mConnectedThread.write("0");    // Send "0" via Bluetooth
  102.         //Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
  103.       }
  104.     });
  105.   }
  106.    
  107.   private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  108.       if(Build.VERSION.SDK_INT >= 10){
  109.           try {
  110.               final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
  111.               return (BluetoothSocket) m.invoke(device, MY_UUID);
  112.           } catch (Exception e) {
  113.               Log.e(TAG, "Could not create Insecure RFComm Connection",e);
  114.           }
  115.       }
  116.       return  device.createRfcommSocketToServiceRecord(MY_UUID);
  117.   }
  118.    
  119.   @Override
  120.   public void onResume() {
  121.     super.onResume();
  122.     BluetoothDevice device = btAdapter.getRemoteDevice(address);
  123.          
  124.     try {
  125.         btSocket = createBluetoothSocket(device);
  126.     } catch (IOException e) {
  127.         errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  128.     }
  129.    
  130.     // Discovery is resource intensive.  Make sure it isn't going on
  131.     // when you attempt to connect and pass your message.
  132.     btAdapter.cancelDiscovery();
  133.    
  134.     // Establish the connection.  This will block until it connects.
  135.     Log.d(TAG, "...Connecting...");
  136.     try {
  137.       btSocket.connect();
  138.       Log.d(TAG, "....Connection ok...");
  139.     } catch (IOException e) {
  140.       try {
  141.         btSocket.close();
  142.       } catch (IOException e2) {
  143.         errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  144.       }
  145.     }
  146.      
  147.     // Create a data stream so we can talk to server.
  148.     Log.d(TAG, "...Create Socket...");
  149.    
  150.    
  151.     mConnectedThread = new ConnectedThread(btSocket);
  152.     mConnectedThread.start();
  153.   }
  154.  
  155.   @Override
  156.   public void onPause() {
  157.     super.onPause();
  158.  
  159.     Log.d(TAG, "...In onPause()...");
  160.    
  161.     try     {
  162.       btSocket.close();
  163.     } catch (IOException e2) {
  164.       errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
  165.     }
  166.   }
  167.    
  168.   private void checkBTState() {
  169.     if(btAdapter==null) {
  170.       Log.d(TAG, "Zařízení nepodporuje Bluetooth");
  171.      
  172.     } else {
  173.       if (btAdapter.isEnabled()) {
  174.         Log.d(TAG, "...Bluetooth ON...");
  175.         } else {
  176.         //Prompt user to turn on Bluetooth
  177.         Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  178.         startActivityForResult(enableBtIntent, 1);
  179.        
  180.       }
  181.     }
  182.   }
  183.  
  184.   @Override
  185.   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  186.  // TODO Auto-generated method stub
  187.  if(requestCode == 884){
  188.  if (resultCode == RESULT_OK){
  189.  Toast.makeText(getApplicationContext(), "BlueTooth is now Enabled", Toast.LENGTH_LONG).show();
  190.  Log.d(TAG, "Zapnuté bluetooth...");
  191.  }
  192.   if(resultCode == RESULT_CANCELED){
  193.  Toast.makeText(getApplicationContext(), "Error occured while enabling.Leaving the application..", Toast.LENGTH_LONG).show();
  194.  Log.d(TAG, "Vypnuté bluetooth...");
  195.   ///finish();
  196.   }
  197.   }
  198.   }//onActivityResult
  199.  
  200.   private void errorExit(String title, String message){
  201.     Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
  202.     finish();
  203.   }
  204.  
  205.   private class ConnectedThread extends Thread {
  206.         private final InputStream mmInStream;
  207.         private final OutputStream mmOutStream;
  208.      
  209.         public ConnectedThread(BluetoothSocket socket) {
  210.             InputStream tmpIn = null;
  211.             OutputStream tmpOut = null;
  212.      
  213.             // Get the input and output streams, using temp objects because
  214.             // member streams are final
  215.             try {
  216.                 tmpIn = socket.getInputStream();
  217.                 tmpOut = socket.getOutputStream();
  218.             } catch (IOException e) { }
  219.      
  220.             mmInStream = tmpIn;
  221.             mmOutStream = tmpOut;
  222.         }
  223.      
  224.         public void run() {
  225.             byte[] buffer = new byte[256];  // buffer store for the stream
  226.             int bytes; // bytes returned from read()
  227.  
  228.             // Keep listening to the InputStream until an exception occurs
  229.             while (true) {
  230.                 try {
  231.                     // Read from the InputStream
  232.                     bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
  233.                     h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
  234.                 } catch (IOException e) {
  235.                     break;
  236.                 }
  237.             }
  238.         }
  239.      
  240.         /* Call this from the main activity to send data to the remote device */
  241.         public void write(String message) {
  242.             Log.d(TAG, "...Data to send: " + message + "...");
  243.             byte[] msgBuffer = message.getBytes();
  244.             try {
  245.                 mmOutStream.write(msgBuffer);
  246.             } catch (IOException e) {
  247.                 Log.d(TAG, "...Error data send: " + e.getMessage() + "...");    
  248.               }
  249.         }
  250.     }
  251. }