Android Studio asking for bluetooth permission check even though it's already present

455 Views Asked by At

See lines 94-95 in mainactivity file.

**bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
           bluetoothSocket.connect();**
           inputStream = bluetoothSocket.getInputStream();

Am receiving this error:

"Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException."

I tried adding the onRequestPermissionsResult method and preceding if-statement, but I am still receiving the error. What more is needed?

Am using HC-05 module to transmit serial data from arduino to android device. Thanks.

Manifest attached as well

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

\<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"\>

    <!--Before Android 12 (but still needed location, even if not requested)-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
    <!--From Android 12-->
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    
    
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StrikeTec"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

MainActivity.java

`

package com.example.striketec;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_BLUETOOTH_PERMISSIONS = 1;
private static final String\[\] BLUETOOTH_PERMISSIONS = {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
};
private static final String MAC_ADDRESS = "00:11:22:33:44:55"; // Replace with your device's MAC address
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID

private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private BufferedReader reader;

private TextView fastestTextView;
private TextView slowestTextView;
private TextView averageTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

       fastestTextView = findViewById(R.id.fastest_text_view);
       slowestTextView = findViewById(R.id.slowest_text_view);
       averageTextView = findViewById(R.id.average_text_view);
    
       // Check if the app has the required permissions
       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
               || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
           // Request the permissions if they are not granted
           ActivityCompat.requestPermissions(this, BLUETOOTH_PERMISSIONS, REQUEST_BLUETOOTH_PERMISSIONS);
       } else {
           // Initialize Bluetooth if the permissions are already granted
           initBluetooth();
       }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String\[\] permissions, @NonNull int\[\] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_BLUETOOTH_PERMISSIONS) {
if (grantResults.length \> 0 && grantResults\[0\] == PackageManager.PERMISSION_GRANTED
&& grantResults\[1\] == PackageManager.PERMISSION_GRANTED) {
// Initialize Bluetooth if the permissions are granted
initBluetooth();
} else {
Toast.makeText(this, "Bluetooth permissions are required", Toast.LENGTH_SHORT).show();
finish();
}
}
}

private void initBluetooth() {
// Initialize Bluetooth here
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device", Toast.LENGTH_SHORT).show();
finish();
return;
}

       if (!bluetoothAdapter.isEnabled()) {
           Toast.makeText(this, "Please enable Bluetooth", Toast.LENGTH_SHORT).show();
           finish();
           return;
       }
    
       bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC_ADDRESS);
       try {
           **bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
           bluetoothSocket.connect();**
           inputStream = bluetoothSocket.getInputStream();
           reader = new BufferedReader(new InputStreamReader(inputStream));
           new Thread(new Runnable() {
               @Override
               public void run() {
                   while (true) {
                       try {
                           final String data = reader.readLine();
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   // Update the UI with the data received
                                   fastestTextView.setText(data);
                                   slowestTextView.setText(data);
                                   averageTextView.setText(data);
                                   }
                               });
                           } catch (IOException e) {
                               e.printStackTrace();
                           }
                       }
                   }
               }).start();
           } catch (IOException e) {
           e.printStackTrace();
           }
       }

}\`

I tried adding the onRequestPermissionsResult method and preceding if-statement, but I am still receiving the error. What more is needed? Expected this to suffice and the error to disappear.

0

There are 0 best solutions below