Bluetooth LE Scan fails in the background - permissions

后端 未结 4 1253
攒了一身酷
攒了一身酷 2020-12-09 16:08

The following code works great on my Nexus 9 running Android 5.1.1 (Build LMY48M), but won\'t work on a Nexus 9 running Android 6.0 (Build MPA44l)

List

        
4条回答
  •  隐瞒了意图╮
    2020-12-09 16:42

    I had a similar problem with an app connecting to bluetooth. Not LE ScanFilter, but it was a permissions issue just like the OP had.

    Root cause is that starting with SDK 23, you need to prompt the user for permissions at runtime using Activity's requestPermissions() method.

    Here's what worked for me:

    1. Add one of the following two lines to AndroidManifest.xml, inside the root node:

      
      
      
    2. In your Activity, before attempting to connect to bluetooth, call Activity's requestPermissions() method, which opens a system dialog to prompt the user for the permission. The permissions dialog opens in a different thread, so be sure to wait for the result before trying to connect to bluetooth.

    3. Override Activity's onRequestPermissionsResult() to handle the result. This method will really only need to do something if the user refused to grant the permission, to tell the user that the app can't do the bluetooth activity.

    This blog post has some example code that uses AlertDialogs to tell the user what's going on. It is a good starting point but has some shortcomings:

    • It doesn't handle waiting for the requestPermissions() thread to finish
    • The AlertDialog wrapping the call to requestPermissions() seems extraneous to me. A bare call to requestPermissions() is sufficient.

提交回复
热议问题