Otimização da gestão da ligação do bluetooth do dispositivo

dev 1.0
João Miranda 2025-11-05 10:19:14 +00:00
parent 66e5b5e30b
commit 23a662099a
1 changed files with 40 additions and 37 deletions

View File

@ -42,6 +42,7 @@ public class MainActivity extends AppCompatActivity {
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 boolean bluetoothDenied = false;
@Override
@ -66,8 +67,6 @@ public class MainActivity extends AppCompatActivity {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN},
2);
} else {
ligarBluetooth();
}
}
@ -107,12 +106,9 @@ public class MainActivity extends AppCompatActivity {
if (!mBTAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(MainActivity.this, "Bluetooth turned on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
else{
final String address = "98:D3:21:FC:7F:DF";
new Thread() {
public void run() {
@ -149,6 +145,9 @@ public class MainActivity extends AppCompatActivity {
}.start();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
// Check which request we're responding to
@ -156,9 +155,13 @@ public class MainActivity extends AppCompatActivity {
if (requestCode == REQUEST_ENABLE_BT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
ligarBluetooth();
Toast.makeText(this, "Bluetooth Ligado", Toast.LENGTH_SHORT).show();
} else {
bluetoothDenied = true;
Toast.makeText(this, "A App Precisa de Bluetooth para Funcionar", Toast.LENGTH_SHORT).show();
finish();
}
}
}
@ -216,7 +219,7 @@ public class MainActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
if (mBTSocket == null || !mBTSocket.isConnected()) {
if ((mBTSocket == null || !mBTSocket.isConnected()) && !bluetoothDenied) {
ligarBluetooth();
}
}