Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.28 KB | None | 0 0
  1. public class MainActivity extends Activity {
  2.   private static final String TAG = "bluetooth1";
  3.  
  4.   Button btnOn, btnOff;
  5.  
  6.   private BluetoothAdapter btAdapter = null;
  7.   private BluetoothSocket btSocket = null;
  8.   private OutputStream outStream = null;
  9.  
  10.   // SPP UUID service
  11.   private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  12.  
  13.   // MAC-address of Bluetooth module (you must edit this line)
  14.   private static String address = "00:15:FF:F2:19:5F";
  15.  
  16.   /** Called when the activity is first created. */
  17.   @Override
  18.   public void onCreate(Bundle savedInstanceState) {
  19.     super.onCreate(savedInstanceState);
  20.  
  21.     setContentView(R.layout.activity_main);
  22.  
  23.     btnOn = (Button) findViewById(R.id.btnOn);
  24.     btnOff = (Button) findViewById(R.id.btnOff);
  25.  
  26.     btAdapter = BluetoothAdapter.getDefaultAdapter();
  27.     checkBTState();
  28.  
  29.     btnOn.setOnClickListener(new OnClickListener() {
  30.       public void onClick(View v) {
  31.         sendData("1");
  32.         Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
  33.       }
  34.     });
  35.  
  36.     btnOff.setOnClickListener(new OnClickListener() {
  37.       public void onClick(View v) {
  38.         sendData("0");
  39.         Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
  40.       }
  41.     });
  42.   }
  43.  
  44.   private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  45.       if(Build.VERSION.SDK_INT >= 10){
  46.           try {
  47.               final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
  48.               return (BluetoothSocket) m.invoke(device, MY_UUID);
  49.           } catch (Exception e) {
  50.               Log.e(TAG, "Could not create Insecure RFComm Connection",e);
  51.           }
  52.       }
  53.       return  device.createRfcommSocketToServiceRecord(MY_UUID);
  54.   }
  55.  
  56.   @Override
  57.   public void onResume() {
  58.     super.onResume();
  59.  
  60.     Log.d(TAG, "...onResume - try connect...");
  61.  
  62.     // Set up a pointer to the remote node using it's address.
  63.     BluetoothDevice device = btAdapter.getRemoteDevice(address);
  64.  
  65.     // Two things are needed to make a connection:
  66.     //   A MAC address, which we got above.
  67.     //   A Service ID or UUID.  In this case we are using the
  68.     //     UUID for SPP.
  69.  
  70.     try {
  71.         btSocket = createBluetoothSocket(device);
  72.     } catch (IOException e1) {
  73.         errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
  74.     }
  75.  
  76.     // Discovery is resource intensive.  Make sure it isn't going on
  77.     // when you attempt to connect and pass your message.
  78.     btAdapter.cancelDiscovery();
  79.  
  80.     // Establish the connection.  This will block until it connects.
  81.     Log.d(TAG, "...Connecting...");
  82.     try {
  83.       btSocket.connect();
  84.       Log.d(TAG, "...Connection ok...");
  85.     } catch (IOException e) {
  86.       try {
  87.         btSocket.close();
  88.       } catch (IOException e2) {
  89.         errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  90.       }
  91.     }
  92.  
  93.     // Create a data stream so we can talk to server.
  94.     Log.d(TAG, "...Create Socket...");
  95.  
  96.     try {
  97.       outStream = btSocket.getOutputStream();
  98.     } catch (IOException e) {
  99.       errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
  100.     }
  101.   }
  102.  
  103.   @Override
  104.   public void onPause() {
  105.     super.onPause();
  106.  
  107.     Log.d(TAG, "...In onPause()...");
  108.  
  109.     if (outStream != null) {
  110.       try {
  111.         outStream.flush();
  112.       } catch (IOException e) {
  113.         errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
  114.       }
  115.     }
  116.  
  117.     try     {
  118.       btSocket.close();
  119.     } catch (IOException e2) {
  120.       errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
  121.     }
  122.   }
  123.  
  124.   private void checkBTState() {
  125.     // Check for Bluetooth support and then check to make sure it is turned on
  126.     // Emulator doesn't support Bluetooth and will return null
  127.     if(btAdapter==null) {
  128.       errorExit("Fatal Error", "Bluetooth not support");
  129.     } else {
  130.       if (btAdapter.isEnabled()) {
  131.         Log.d(TAG, "...Bluetooth ON...");
  132.       } else {
  133.         //Prompt user to turn on Bluetooth
  134.         Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  135.         startActivityForResult(enableBtIntent, 1);
  136.       }
  137.     }
  138.   }
  139.  
  140.   private void errorExit(String title, String message){
  141.     Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
  142.     finish();
  143.   }
  144.  
  145.   private void sendData(String message) {
  146.     byte[] msgBuffer = message.getBytes();
  147.  
  148.     Log.d(TAG, "...Send data: " + message + "...");
  149.  
  150.     try {
  151.       outStream.write(msgBuffer);
  152.     } catch (IOException e) {
  153.       String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
  154.       if (address.equals("00:00:00:00:00:00"))
  155.         msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
  156.         msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
  157.  
  158.         errorExit("Fatal Error", msg);
  159.     }
  160.   }
  161. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement