Bluetooth not disable programmatically in android API 31 or higher version - java

I'm trying to disable Bluetooth on the button click but it not work
hear, What I Do
if (SDK_INT >= Build.VERSION_CODES.S) {
if (checkPermission(Manifest.permission.BLUETOOTH_CONNECT) && checkPermission(Manifest.permission.BLUETOOTH_SCAN)) {
BluetoothAdapter adapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
if (adapter != null) {
if (adapter.getState() == BluetoothAdapter.STATE_ON) {
Log.e("BT", "disable");
adapter.disable();
} else if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
if (!adapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Log.e("BT", "enable");
} else {
Log.e("BT", "Else");
}
} else {
Toast.makeText(UltimateHomeLauncherActivity.this, "Bluetooth is not supported on your hardware", Toast.LENGTH_SHORT).show();
}
} else {
List<String> deniedPermissions = new ArrayList<>();
deniedPermissions.add(Manifest.permission.BLUETOOTH_CONNECT);
deniedPermissions.add(Manifest.permission.BLUETOOTH_SCAN);
requestRuntimePermissions(1011, deniedPermissions.toArray(new String[0]));
}
}
I'm add Bluetooth permission in Manifest also.
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>

android.permission.BLUETOOTH_CONNECT is a runtime permission and requires the consent of the user.
However, with next API level 33 enable()/disable() of the BluetoothAdapter will be deprecated and are not longer allowed. Therefore, it is probably best for such a function to navigate the user to the Bluetooth system dialog and ask him to turn the function on or off there.

Related

Storage Permission Issue In android 10+ devices

i am trying to create a video player ,So I am trying to add the videos to the list
Storage permission is required to fetch the videos, so I took the permission with the below code.
But playstore was reject My app for this MANAGE EXTERNAL STORAGE permission.
But without this permission, I can't get storage permission on Android 10+ device.
To change the name of the video, delete the video and download the video permission is required , so please help me , please tell me how to get storage permission (/storage/Media/Videos , /storage/Download/)
My storage permission code :-
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
android:requestLegacyExternalStorage="true"
Main activity code :-
private boolean checkPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
} else {
int result = ContextCompat.checkSelfPermission(PermissionActivity.this, READ_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(PermissionActivity.this, WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
}
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
}
} else {
//below android 11
ActivityCompat.requestPermissions(PermissionActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2296) {
if (SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
// perform action when allow permission success
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
boolean READ_EXTERNAL_STORAGE = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean WRITE_EXTERNAL_STORAGE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
// perform action when allow permission success
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
So please tell me how to take storage permission in Android10+ Devices and also below Android 10 devices with out using MANAGE EXTERNAL STORAGE permission , Please Help Me
Permissions have changed in Android 10+:
External storage access scoped to app files and media
By default, apps targeting Android 10 and higher are given scoped access into external storage, or scoped storage. Such apps can see the following types of files within an external storage device without needing to request any storage-related user permissions [..]
Source: Privacy changes in Android 10
On devices that run Android 10 or higher, you don't need any storage-related permissions to access and modify media files that your app owns, including files in the MediaStore.Downloads collection
Source: Storage Permissions
If you have
android:requestLegacyExternalStorage="true"
in application tag in manifest file then you are done for an Android Q/10 device.
It will behave as it behaved on before 10.
I do not understand why you would have any problem on Android 10.
On Android 11+ you should be able to see media files in the usual public directories.

How to verify if my app have ALL_FILES_ACCESS_PERMISSION?

I give all files access by this method :
if (!hasPermissionToManageFiles(myContext)){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uriFiles = Uri.fromParts("package", myContext.getPackageName(), null);
intentFiles.setData(uriFiles);
myContext.startActivity(intentFiles);
}
catch (Exception e){
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
myContext.startActivity(intentFiles);
}
}
}
This line in my manifest :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
I tried to create method to verify this kind of permission but it's not working. I don't have any error, when my app has the permission to access the intent still appears.
here is my method :
public static boolean hasPermissionToManageFiles(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.MANAGE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
return true;
}
According to the docs you should use Environment.isExternalStorageManager method instead of the checkSelfPermission.

startActivityForResult is deprecated and, unable to request for bluetooth connection with new code

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
I was requesting to start Bluetooth using above source code. But, startActivityForResult is deprecated. So, I was searching for new code how to deal with that. Here's the solution I found.
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
doSomeOperations();
}
}
});
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
someActivityResultLauncher.launch(intent);
}
I added it to my source code.
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
// doSomeOperations();
}
}
});
someActivityResultLauncher.launch(enableBtIntent);
But, Android is requesting for bluetooth permission automatically for old source code (I didn't have to add onActivityResult function. Cause, it was earlier written in background). But, when I am using ActivityResultLauncher I must add onActivityResult function(I can work without onActivityResult also But, startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); I had sent an integer value also REQUEST_ENABLE_BT=1). How can I request for bluetooth permission with new code?
100% working solution
manifest code:
<!--BLUETOOTH PERMISSION-->
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- Needed only if your app looks for Bluetooth devices.
If your app doesn't use Bluetooth scan results to derive physical
location information, you can strongly assert that your app
doesn't derive physical location. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<!-- Needed only if your app makes the device discoverable to Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<!-- Needed only if your app communicates with already-paired Bluetooth
devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!--bibo01 : hardware option-->
<uses-feature android:name="android.hardware.bluetooth" android:required="false"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
Kotlin code:
//check android12+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
requestMultiplePermissions.launch(arrayOf(
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT))
}
else{
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
requestBluetooth.launch(enableBtIntent)
}
....................................................
private var requestBluetooth = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
//granted
}else{
//deny
}
}
private val requestMultiplePermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
permissions.entries.forEach {
Log.d("test006", "${it.key} = ${it.value}")
}
}
Read more:
https://developer.android.com/guide/topics/connectivity/bluetooth/permissions

Bluetooth start discovery not giving results

This is my first app in Android. I am very new to Android and Java. I am kind of expert in iOS/ObjC though. I am learning by doing. So I jumped straight into making an app to connect to a bluetooth device. First step is of course to get a list of the bluetooth device available in range.
Here is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest...>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application ...
Here is my Activity code:
private BluetoothAdapter btAdapter;
#Override
public void onDestroy() {
super.onDestroy();
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
/*------------- ON CREATE ------------------------------*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
System.out.println ("Bluetooth non support");
} else {
System.out.println ("Bluetooth initialized");
}
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
IntentFilter filterDevice = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filterDevice);
if (btAdapter.isEnabled()) {
String mydeviceaddress = btAdapter.getAddress();
String mydevicename = btAdapter.getName();
String status = mydevicename + " : " + mydeviceaddress;
System.out.println(status);
System.out.println ("Start discover");
btAdapter.startDiscovery();
} else {
System.out.println ("Not enabled");
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, 1);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
System.out.println("1");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
System.out.println("2");
break;
case BluetoothAdapter.STATE_ON:
System.out.println("3");
// SCAN HERE
btAdapter.startDiscovery();
break;
case BluetoothAdapter.STATE_TURNING_ON:
System.out.println("4");
break;
}
}
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName() + "\n" + device.getAddress());
} else {
System.out.println("What de fuq");
}
}
};
I turned on bluetooth on my android phone, and then running the app shows that log:
Bluetooth initialized
Start discover
And thats all. Other logs are not printing out. Any idea why? My code seems perfect idk.
EDIT: Screenshot of the Bluetooth module HC-05 being detected by Android.
The other devices may not be in discoverable mode. Make sure they are discoverable.
If your other device is a bluetooth module, in your case Arduino, right?
If so, check this tutorial describing connection between Android device and HC05 module.
bthc-05 to android tutorial
Also, based on this official sample: google sample - bluetooth chat
Alternatively, you could also have the following method that makes your device discoverable. And install it on two phones. Then you should be able to discover the phones on each other atleast.
protected void makeDiscoverable(){
// Make local device discoverable
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
Maybe these help!

Oreo problem in creating a directory onto the external storage

I try to create folder in android external storage. I try many example but it all isn't worked. I set run-time permissions for reading and writing to external storage. It is work on Android API 6, 7. but not work on Android Oreo.
File f = new File(Environment.getExternalStorageDirectory(), "MyDir");
if (!f.exists()) {
try {
boolean is_seccess = f.mkdirs();
if (is_seccess) {
Toast.makeText(this, "create", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not create", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
I Checked if external storage is available for read and write, it return true.
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
I give below permissions, I also give run-time permission and allow it.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Just Android Oreo isn't work other device is working perfect. What is problem in my code?
The app requests READ_EXTERNAL_STORAGE and the user grants it. If the app targets API level 25 or lower, the system also grants WRITE_EXTERNAL_STORAGE at the same time, because it belongs to the same STORAGE permission group and is also registered in the manifest. If the app targets Android 8.0 (API level 26), the system grants only READ_EXTERNAL_STORAGE at that time; however, if the app later requests WRITE_EXTERNAL_STORAGE
Ask run time permission like below:
private boolean checkAndRequestPermissions() {
int permissionReadStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
int permissionCamera = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
int permissionWriteStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (permissionReadStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (permissionWriteStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions((Activity) this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}

Categories

Resources