mazenrashed / Printooth

A well documented, high-level Android interface that makes printing via bluetooth printers easier
Mozilla Public License 2.0
399 stars 113 forks source link

Permissions error on Android 12, 13 #102

Open hernando-montoya opened 2 years ago

hernando-montoya commented 2 years ago

The scanning activity crash.

java.lang.SecurityException: Need android.permission.BLUETOOTH_SCAN permission for android.content.AttributionSource@d39f7202: Starting discovery.

But the permission is already present in the manifest.

Dumankrg2019 commented 2 years ago

tv_device_selected, Maybe you need use permission on run time.

` private fun hasConnectBluetooth() = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED private fun hasScanBluetooth() = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED

private fun requestPermissions() {
    var permissionsToReques = mutableListOf<String>()
    if(!hasScanBluetooth()) {
        permissionsToReques.add(Manifest.permission.BLUETOOTH_SCAN)
    }
    if(!hasConnectBluetooth()) {
        permissionsToReques.add(Manifest.permission.BLUETOOTH_CONNECT)
    }
    if(permissionsToReques.isNotEmpty()) {
        ActivityCompat.requestPermissions(this, permissionsToReques.toTypedArray(), 0)
    }
}
override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)

    if(requestCode == 0 && grantResults.isNotEmpty()) {
        for(i in grantResults.indices) {
            if(grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                Log.e("permission is:", " ${permissions[i]} разрешено")
                initView()
            }
        }
    }
}`

and use requestPermissions fun in your activity or fragment

tspoke commented 2 years ago

Since android 12 you need to add two extras permissions, depending on your need but in my case I do this using Dexter to request permissions :

final List<String> permissions = new ArrayList<>();
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.BLUETOOTH);
permissions.add(Manifest.permission.BLUETOOTH_ADMIN);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    permissions.add(Manifest.permission.BLUETOOTH_CONNECT);
    permissions.add(Manifest.permission.BLUETOOTH_SCAN);
}

Dexter.withContext(requireActivity())
                .withPermissions(permissions)
                ....
salihinalfarizi commented 9 months ago

hi guys @hernando-montoya @tspoke @Dumankrg2019 , i get this issue too, so which solution need to implement for this issue?