Altbeacon Library Background Service
Solution 1:
Starting with Android 6.0 Marshmallow, apps that scan for Bluetooth LE devices (including beacons) must obtain dynamic location permissions before they are allowed to do so. For legacy purposes, apps running on that target older Android SDKs (before API 23) are still allowed to scan for Bluetooth LE devices, but only in the foreground. This is the reason your app works if you target SDK 21, but not SDK 23.
To fix this when targeting SDK 23, you simply need to add the dynamic permissions request.
privatestaticfinalintPERMISSION_REQUEST_COARSE_LOCATION=1;
...
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect beacons.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(newDialogInterface.OnDismissListener() {
@Override?
publicvoidonDismiss(DialogInterface dialog) {
requestPermissions(newString[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);?
}
});
builder.show();
}
}
}
@OverridepublicvoidonRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(newDialogInterface.OnDismissListener() {
@OverridepublicvoidonDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
Detailed instructions on how to do this are available here: https://altbeacon.github.io/android-beacon-library/requesting_permission.html
I wrote a blog post about this topic here: http://developer.radiusnetworks.com/2015/09/29/is-your-beacon-app-ready-for-android-6.html
EDIT: As @Near1999 noted in a comment below, some Android 5+ builds also will not detect BLE devices unless Location Services are turned on in settings. Apparently, this restriction also only applies if targeting SDK 23+. See here for more info: https://github.com/AltBeacon/android-beacon-library/issues/301
Post a Comment for "Altbeacon Library Background Service"