diff --git a/app/src/main/java/pt/epvc/lazzycofee/MainActivity.java b/app/src/main/java/pt/epvc/lazzycofee/MainActivity.java index 2ee966e..6e0cef8 100644 --- a/app/src/main/java/pt/epvc/lazzycofee/MainActivity.java +++ b/app/src/main/java/pt/epvc/lazzycofee/MainActivity.java @@ -35,21 +35,11 @@ import java.util.UUID; public class MainActivity extends AppCompatActivity { - private ImageButton cafeCurto; - private ImageButton cafeMédio; - private ImageButton cafeLongo; - private Switch conetar; private BluetoothAdapter mBTAdapter; - private Set mPairedDevices; - private ArrayAdapter mBTArrayAdapter; - private ListView mDevicesListView; - private Handler mHandler; // Our main handler that will receive callback notifications private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names - private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update - private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status @Override @@ -62,58 +52,7 @@ public class MainActivity extends AppCompatActivity { v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); - cafeCurto = (ImageButton) findViewById(R.id.cafeCurto); - cafeMédio = (ImageButton) findViewById(R.id.cafeMedio); - cafeLongo = (ImageButton) findViewById(R.id.cafeLongo); - - -// mBTArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1); mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio - - -// mHandler = new Handler() { -// public void handleMessage(android.os.Message msg) { -// if (msg.what == MESSAGE_READ) { -// String readMessage = null; -// try { -// readMessage = new String((byte[]) msg.obj, "UTF-8"); -// } catch (UnsupportedEncodingException e) { -// e.printStackTrace(); -// } -// //mReadBuffer.setText(readMessage); -// } -// -// if (msg.what == CONNECTING_STATUS) { -// if (msg.arg1 == 1) -// Toast.makeText(MainActivity.this, "Connected to Device: " + (String) (msg.obj), Toast.LENGTH_SHORT).show(); -// //mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj)); -// else -// Toast.makeText(MainActivity.this, "Connection Failed", Toast.LENGTH_SHORT).show(); -// //mBluetoothStatus.setText("Connection Failed"); -// } -// } -// }; - -// if (mBTArrayAdapter == null) { -// // Device does not support Bluetooth -// //mBluetoothStatus.setText("Status: Bluetooth not found"); -// Toast.makeText(MainActivity.this, "Bluetooth device not found!", Toast.LENGTH_SHORT).show(); -// } else { -// conetar = (Switch) findViewById(R.id.conetar); -// conetar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { -// @Override -// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { -// if (conetar.isChecked()) { -// Toast.makeText(MainActivity.this, "Conetado", Toast.LENGTH_SHORT).show(); -// ligarBluetooth(); -// } else { -// Toast.makeText(MainActivity.this, "Desconetado", Toast.LENGTH_SHORT).show(); -// desligarBluetooth(); -// } -// } -// }); -// -// } getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); ligarBluetooth(); } @@ -148,7 +87,6 @@ public class MainActivity extends AppCompatActivity { if (!mBTAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); - //mBluetoothStatus.setText("Bluetooth enabled"); Toast.makeText(MainActivity.this, "Bluetooth turned on", Toast.LENGTH_SHORT).show(); } else { @@ -168,16 +106,9 @@ public class MainActivity extends AppCompatActivity { fail = true; Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); } - // Establish the Bluetooth socket connection. try { if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. + return; } mBTSocket.connect(); @@ -185,19 +116,13 @@ public class MainActivity extends AppCompatActivity { try { fail = true; mBTSocket.close(); - mHandler.obtainMessage(CONNECTING_STATUS, -1, -1) - .sendToTarget(); } catch (IOException e2) { - //insert code to deal with this Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); } } if (fail == false) { mConnectedThread = new ConnectedThread(mBTSocket); mConnectedThread.start(); - - mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "ASD") - .sendToTarget(); } } }.start(); @@ -210,142 +135,33 @@ public class MainActivity extends AppCompatActivity { if (requestCode == REQUEST_ENABLE_BT) { // Make sure the request was successful if (resultCode == RESULT_OK) { - // The user picked a contact. - // The Intent's data Uri identifies which contact was selected. - //mBluetoothStatus.setText("Enabled"); Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show(); } else Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show(); - //mBluetoothStatus.setText("Disabled"); } } -// public void desligarBluetooth() { -// //mBTAdapter.disable(); // turn off -// //mBluetoothStatus.setText("Bluetooth disabled"); -// Toast.makeText(MainActivity.this, "Bluetooth turned Off", Toast.LENGTH_SHORT).show(); -// } -// private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() { -// public void onItemClick(AdapterView av, View v, int arg2, long arg3) { -// -// if (!mBTAdapter.isEnabled()) { -// Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show(); -// return; -// } -// Toast.makeText(MainActivity.this, "Connecting...", Toast.LENGTH_SHORT).show(); -// //mBluetoothStatus.setText("Connecting..."); -// // Get the device MAC address, which is the last 17 chars in the View -// String info = ((TextView) v).getText().toString(); -// final String address = info.substring(info.length() - 17); -// final String name = info.substring(0, info.length() - 17); -// -// // Spawn a new thread to avoid blocking the GUI one -// new Thread() { -// public void run() { -// boolean fail = false; -// -// BluetoothDevice device = mBTAdapter.getRemoteDevice(address); -// -// try { -// mBTSocket = createBluetoothSocket(device); -// } catch (IOException e) { -// fail = true; -// Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); -// } -// // Establish the Bluetooth socket connection. -// try { -// if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { -// // TODO: Consider calling -// // ActivityCompat#requestPermissions -// // here to request the missing permissions, and then overriding -// // public void onRequestPermissionsResult(int requestCode, String[] permissions, -// // int[] grantResults) -// // to handle the case where the user grants the permission. See the documentation -// // for ActivityCompat#requestPermissions for more details. -// return; -// } -// mBTSocket.connect(); -// } catch (IOException e) { -// try { -// fail = true; -// mBTSocket.close(); -// mHandler.obtainMessage(CONNECTING_STATUS, -1, -1) -// .sendToTarget(); -// } catch (IOException e2) { -// //insert code to deal with this -// Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show(); -// } -// } -// if (fail == false) { -// mConnectedThread = new ConnectedThread(mBTSocket); -// mConnectedThread.start(); -// -// mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name) -// .sendToTarget(); -// } -// } -// }.start(); -// } -// }; + private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. } return device.createRfcommSocketToServiceRecord(BTMODULEUUID); - //creates secure outgoing connection with BT device using UUID } private class ConnectedThread extends Thread { - private final BluetoothSocket mmSocket; - private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { - mmSocket = socket; - InputStream tmpIn = null; OutputStream tmpOut = null; - - // Get the input and output streams, using temp objects because - // member streams are final try { - tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } - mmInStream = tmpIn; mmOutStream = tmpOut; } - public void run() { - byte[] buffer = new byte[1024]; // buffer store for the stream - int bytes; // bytes returned from read() - // Keep listening to the InputStream until an exception occurs - while (true) { - try { - // Read from the InputStream - bytes = mmInStream.available(); - if (bytes != 0) { - SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed. - bytes = mmInStream.available(); // how many bytes are ready to be read? - bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read - mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) - .sendToTarget(); // Send the obtained bytes to the UI activity - } - } catch (IOException e) { - e.printStackTrace(); - - break; - } - } - } public void enviarComando(String input){ byte[] bytes = input.getBytes(); //converts entered String into bytes try { @@ -353,4 +169,21 @@ public class MainActivity extends AppCompatActivity { } catch (IOException e) { } } } + private void desligarBluetooth() { + try { + mBTSocket.close(); + } catch (IOException e) {} + } + + @Override + protected void onPause() { + super.onPause(); + desligarBluetooth(); + } + + @Override + protected void onResume() { + super.onResume(); + ligarBluetooth(); + } } \ No newline at end of file