Java android bluetooth permission

Android 12 bluetooth permissions confusion

Targeting Android 12 my working solution is to declare the permissions in this way:

Like you said, BLUETOOTH_SCAN is not sufficient and you need BLUETOOTH_CONNECT (also if you decide, like me, to ask to the user to enable Bluetooth starting a new startActivityForResult with action BluetoothAdapter.ACTION_REQUEST_ENABLE)

If the BLUETOOTH_CONNECT permission needs to be requested at runtime what is the correct full way to do it? Meaning checking if it’s already granted then requesting it if it’s not. I have no Android 12 device so no way to test this code.

To improve @AndreasGobs answer, below the code to test if the connection with a device is viable or not based on current available permissions. In the manifest I’ve set that the COARSE and FINE location permissions must be limited to max API 30. Tested on Android 6, 8.1, 11 and 12 devices. I hope this will be useful.

/** * - API < S * - Check ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions * - API < O * - Check has GPS * - Check GPS enabled * - API >= S * - Check BLUETOOTH_SCAN permission * - Check BLUETOOTH_CONNECT permission * - Check Bluetooth enabled */ private boolean canConnect() < Timber.d("canConnect called"); ListdeniedPermissions = new ArrayList<>(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) < if (!checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) deniedPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION); if (!checkPermission(Manifest.permission.ACCESS_FINE_LOCATION)) deniedPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION); if(deniedPermissions.isEmpty())< if (!MmcDeviceCapabilities.hasLocationGps() //check if the device has GPS || Build.VERSION.SDK_INT < Build.VERSION_CODES.O || MmcDeviceCapabilities.isGpsEnabled())< //check if the GPS is enabled if(MmcDeviceCapabilities.bluetoothEnabled()) //check if bluetooth is enabled return true; else < requestEnableBluetooth(); //method to request enable bluetooth return false; >> else < Timber.d("Request enable GPS"); requestEnableGps(); //method to request enable GPS (improving devices scan) return false; >> else < Timber.d("Request GPS permissions"); requestRuntimePermissions( "Bluetooth GPS request", "GPS permissions request rationale", GPS_PERMISSIONS_CODE, deniedPermissions.toArray(new String[0])); return false; >> else < // Build.VERSION_CODES.S or later if(!checkPermission(Manifest.permission.BLUETOOTH_SCAN)) deniedPermissions.add(Manifest.permission.BLUETOOTH_SCAN); if(!checkPermission(Manifest.permission.BLUETOOTH_CONNECT)) deniedPermissions.add(Manifest.permission.BLUETOOTH_CONNECT); if(deniedPermissions.isEmpty()) if(MmcDeviceCapabilities.bluetoothEnabled()) //check if bluetooth is enabled return true; else < requestEnableBluetooth(); //method to request enable bluetooth return false; >else < Timber.d("Request bluetooth permissions"); requestRuntimePermissions( "Bluetooth permissions request", "Bluetooth permissions request rationale", CONNECT_PERMISSIONS_CODE, deniedPermissions.toArray(new String[0])); return false; >> > /** * This method checks if a runtime permission has been granted. * @param permission The permission to check. * @return TRUE if the permission has been granted, FALSE otherwise. */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean checkPermission(@NonNull String permission) < return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED; >private void requestRuntimePermissions(@NonNull String title, @NonNull String description, int requestCode, @NonNull String. permissions) < if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) < AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder .setTitle(title) .setMessage(description) .setCancelable(false) .setNegativeButton(android.R.string.no, (dialog, id) ->< //do nothing >) .setPositiveButton(android.R.string.ok, (dialog, id) -> ActivityCompat.requestPermissions(this, permissions, requestCode)); showDialog(builder); //method to show a dialog > else ActivityCompat.requestPermissions(this, permissions, requestCode); > 

Источник

I’m try to grant access to Enable and Disable Bluetooth on Android Studio using JAVA; but startActivityForResult has been Deprecated. What I can do? [duplicate]

I would like grant access to Enable and Disable Bluetooth from Android Studio. I also pretend to use other functionalities of Bluetooth as list of devices and connect to previous pared device and more. Since starActivityForResult has been Deprecated, I’m having trouble to lunch the pop up activity that ask the user for allowance. This is my manifest

package com.example.bluetoothexamples; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.Set; public class MainActivity extends AppCompatActivity implements View.OnClickListener < private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_DISCOVER_BT = 1; TextView mStatusBlueTv; TextView mPairedTv; ImageView mBlueIv; Button mOnBtn; Button mOffBtn; Button mDiscoverBtn; Button mPairedBtn; BluetoothAdapter mBlueAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStatusBlueTv = findViewById(R.id.statusBluetoothTv); mPairedTv = findViewById(R.id.pairedTv); mBlueIv = findViewById(R.id.bluetoothIv); mOnBtn = findViewById(R.id.onBtn); mOffBtn = findViewById(R.id.offBtn); mDiscoverBtn = findViewById(R.id.discoverableBtn); mPairedBtn = findViewById(R.id.pairedBtn); // Adapter mBlueAdapter = BluetoothAdapter.getDefaultAdapter(); //Check if bluetooth is available or not if (mBlueAdapter == null) < mStatusBlueTv.setText("Bluetooth is NOT Available"); >else < mStatusBlueTv.setText("Bluetooth is Available"); // Set image according to bluetooth status (on/off) if (mBlueAdapter.isEnabled()) < mBlueIv.setImageResource(R.drawable.ic_action_on); >else < mBlueIv.setImageResource(R.drawable.ic_action_off); >mOnBtn.setOnClickListener(this); // Turn on Bluetooth btn click mDiscoverBtn.setOnClickListener(this); // Discover bluetooth btn click mOffBtn.setOnClickListener(this); // Turn off Bluetooth btn click mPairedBtn.setOnClickListener(this); // Get Paired devices button click > > @Override public void onClick(View view) < switch (view.getId()) < // Turn on Bluetooth btn click case R.id.onBtn: if (!mBlueAdapter.isEnabled()) < // showToast("Turning On Bluetooth. "); // if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) < // >else < // requestPermissions(new String[],1); // > if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) < // TODO: Consider calling ActivityCompat.requestPermissions(MainActivity.this, new String[],1); // 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; > // Intent to On Bluetooth Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_ENABLE_BT); > else < showToast("Bluetooth is already on"); >break; // Discover bluetooth btn click case R.id.discoverableBtn: if (!mBlueAdapter.isDiscovering()) < showToast("Making Your Device Discoverable"); Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(intent ,REQUEST_DISCOVER_BT); >break; // Turn off Bluetooth btn click case R.id.offBtn: if (mBlueAdapter.isEnabled()) < mBlueAdapter.disable(); showToast("Turning Bluetooth Off"); mBlueIv.setImageResource(R.drawable.ic_action_off); >else < showToast("Bluetooth is already off"); >break; // Get Paired devices button click case R.id.pairedBtn: if (mBlueAdapter.isEnabled()) < mPairedTv.setText("Paired Devices"); Setdevices = mBlueAdapter.getBondedDevices(); for (BluetoothDevice device: devices) < mPairedTv.append("\nDevice: " + device.getName() + ", " + device); >> else < //bluetooth is off so can't get paired devices showToast("Turn ON Bluetooth to get paired devices"); >break; > > @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1)< if (grantResults[0] == PackageManager.PERMISSION_GRANTED)< showToast("Permission Granted"); >else < showToast("Permission Denied"); >> > @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) < switch (requestCode)< case REQUEST_ENABLE_BT: if (resultCode == RESULT_OK) < // Bluetooth is on mBlueIv.setImageResource(R.drawable.ic_action_on); showToast("Bluetooth is on"); >else < showToast("Failed to connect to bluetooth"); >break; > super.onActivityResult(requestCode, resultCode, data); > //Toast message function private void showToast (String msg) < Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); >> 

1 Answer 1

Currently the recommended approach is using a ActivityResultLauncher to get the results like so:

ActivityResultLauncher activityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> < if (result.getResultCode() == Activity.RESULT_OK) < Log.e("Activity result","OK"); // There are no request codes Intent data = result.getData(); >>); 
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); activityResultLauncher.launch(intent); 

and for your case assuming everything else is working fine ,you update to something like below:

package com.example.bluetoothexamples; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import android.app.Activity; import android.util.Log; import java.util.Set; public class MainActivity extends AppCompatActivity implements View.OnClickListener < private static final int REQUEST_ENABLE_BT = 0; private static final int REQUEST_DISCOVER_BT = 1; TextView mStatusBlueTv; TextView mPairedTv; ImageView mBlueIv; Button mOnBtn; Button mOffBtn; Button mDiscoverBtn; Button mPairedBtn; BluetoothAdapter mBlueAdapter; ActivityResultLauncheractivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> < if (result.getResultCode() == Activity.RESULT_OK) < Log.e("Activity result","OK"); // There are no request codes Intent data = result.getData(); >>); @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStatusBlueTv = findViewById(R.id.statusBluetoothTv); mPairedTv = findViewById(R.id.pairedTv); mBlueIv = findViewById(R.id.bluetoothIv); mOnBtn = findViewById(R.id.onBtn); mOffBtn = findViewById(R.id.offBtn); mDiscoverBtn = findViewById(R.id.discoverableBtn); mPairedBtn = findViewById(R.id.pairedBtn); // Adapter mBlueAdapter = BluetoothAdapter.getDefaultAdapter(); //Check if bluetooth is available or not if (mBlueAdapter == null) < mStatusBlueTv.setText("Bluetooth is NOT Available"); >else < mStatusBlueTv.setText("Bluetooth is Available"); // Set image according to bluetooth status (on/off) if (mBlueAdapter.isEnabled()) < mBlueIv.setImageResource(R.drawable.ic_action_on); >else < mBlueIv.setImageResource(R.drawable.ic_action_off); >mOnBtn.setOnClickListener(this); // Turn on Bluetooth btn click mDiscoverBtn.setOnClickListener(this); // Discover bluetooth btn click mOffBtn.setOnClickListener(this); // Turn off Bluetooth btn click mPairedBtn.setOnClickListener(this); // Get Paired devices button click > > @Override public void onClick(View view) < switch (view.getId()) < // Turn on Bluetooth btn click case R.id.onBtn: if (!mBlueAdapter.isEnabled()) < // showToast("Turning On Bluetooth. "); // if (getApplicationContext().checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) < // >else < // requestPermissions(new String[],1); // > if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) < // TODO: Consider calling ActivityCompat.requestPermissions(MainActivity.this, new String[],1); // 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; > // Intent to On Bluetooth Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivityForResult(intent, REQUEST_ENABLE_BT); activityResultLauncher.launch(intent); > else < showToast("Bluetooth is already on"); >break; // Discover bluetooth btn click case R.id.discoverableBtn: if (!mBlueAdapter.isDiscovering()) < showToast("Making Your Device Discoverable"); Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //startActivityForResult(intent ,REQUEST_DISCOVER_BT); activityResultLauncher.launch(intent); >break; // Turn off Bluetooth btn click case R.id.offBtn: if (mBlueAdapter.isEnabled()) < mBlueAdapter.disable(); showToast("Turning Bluetooth Off"); mBlueIv.setImageResource(R.drawable.ic_action_off); >else < showToast("Bluetooth is already off"); >break; // Get Paired devices button click case R.id.pairedBtn: if (mBlueAdapter.isEnabled()) < mPairedTv.setText("Paired Devices"); Setdevices = mBlueAdapter.getBondedDevices(); for (BluetoothDevice device: devices) < mPairedTv.append("\nDevice: " + device.getName() + ", " + device); >> else < //bluetooth is off so can't get paired devices showToast("Turn ON Bluetooth to get paired devices"); >break; > > @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1)< if (grantResults[0] == PackageManager.PERMISSION_GRANTED)< showToast("Permission Granted"); >else < showToast("Permission Denied"); >> > @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) < switch (requestCode)< case REQUEST_ENABLE_BT: if (resultCode == RESULT_OK) < // Bluetooth is on mBlueIv.setImageResource(R.drawable.ic_action_on); showToast("Bluetooth is on"); >else < showToast("Failed to connect to bluetooth"); >break; > super.onActivityResult(requestCode, resultCode, data); > //Toast message function private void showToast (String msg) < Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); >> 
 ActivityResultLauncher activityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback() < @Override public void onActivityResult(ActivityResult result) < if (result.getResultCode() == Activity.RESULT_OK) < Log.e("Activity result", "OK"); // There are no request codes Intent data = result.getData(); >> > ); 

Источник

Читайте также:  Через блютуз опаздывает звук

How to set permissions for Android Bluetooth

I’m new to Android development. I’m trying to get a simple HelloWorld app going on my (rooted) phone — and the app is trying to enable Bluetooth. I’ve set the Bluetooth permissions in my manifest is as follows, but I’m getting a Permission Denial exception when I try to run the application on my phone via Eclipse:

3 Answers 3

The answer about what to include in your manifest.xml for bluetooth activity includes

The first three are of greater priority and as I’m sure you’re aware there are different cases when each dependency may be required. Hope it helps with your setup!

I’m not quite sure what the problem was here.

All I can say is that I reinstalled Eclipse and its plugins and now everything is working fine. Thanks for your help Mayra — I’ll up-mark your answer because of your helpful and friendly approach.

Next time try to do «everything» logical and then reinstall, therefore your computer techniques will strengthen.

The element types in the manifest are ordered. I think the uses-permission needs to be first under the tag.

Thanks for the quick response Mayra. I’ve tried moving the uses-permission tag around in the file and it doesn’t seem to fix the problem — and the example manifest files I’ve seen often seem to include the uses-permission tags at the bottom of the file — so I don’t think that the location of the tag is critical.

Ok, I think you are right. I had a problem with permissions before that I thought was solved by order, but I see other places in the documentation where things are out of order. What is the exact error message that you are seeing?

Читайте также:  Передаче файлов iphone bluetooth

Down voted, because in SO, we vote-up for quality of answer. Unfortunately, in spite of best intentions, the answer is incorrect.

Источник

Оцените статью
Adblock
detector