Android 12 not showing correct permissions request screen - android

My app requires precise user location because it requires the user to be at specific locations to perform tasks. I have followed the documentation for the proper way to request both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION together.
class LocationChooserFragment : BottomSheetDialogFragment() {
// only relevant parts shown
/**
* A utility class that holds all the code for requesting location updates,
* so that we can re-use it in multiple fragments.
*/
private var locationTracker: LocationTracker? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// all the other initialization for viewbinding
tryToGetLocationUpdates()
}
private fun tryToGetLocationUpdates() {
val request = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
if (permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true && permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true) {
requestLocationUpdates()
}
}
when {
ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED -> {
Timber.i("Already have required permissions")
requestLocationUpdates()
}
shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION) ||
shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION) -> {
Timber.i("Showing permission rationale dialog")
// A wrapper to show a dialog that explains what we need permissions for
alertDialog(
title = getString(R.string.permissions),
msg = getString(R.string.why_we_need_location),
onClick = { yes ->
if (yes) {
request.launch(arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
))
}
}
)
}
else -> {
Timber.i("Prompting for location permissions")
request.launch(arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
))
}
}
}
private fun requestLocationUpdates() {
if (locationProvider == null) {
locationProvider = LocationProvider(requireContext())
}
locationProvider?.requestLocationUpdates()
}
}
The problem I have is that my users are not getting prompted to allow precise location.
I expect to see the prompt in Figure 3 from the documentation:
Figure 3. System permissions dialog that appears when your app requests both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION in a single runtime request.
Instead, I see the prompt in Figure 2 from the documentation:
Figure 2. System permissions dialog that appears when your app requests ACCESS_COARSE_LOCATION only.
Additionally, I expect that when I already have COARSE permission and I request FINE and COARSE permission again, I should see the "Upgrade to Precise permission" dialog, but I don't see any prompt at all.
I have tested this on Pixel 3a (physical device and emulator) as well as received reports from other users on various Pixel and Samsung Galaxy devices that are running Android 12.
The problem was not present when we used compileSdk 30 and targetSdkVersion 30 in build.gradle, but we need to be able to support new features and new versions of Android (and to be able to upgrade to dependencies that only support building with newer SDK versions.
Why is the permission dialog not showing properly?

Comparing my AndroidManifest.xml to the generated file in the built app (using the "Analyze APK" feature in Android Studio), I discovered that the generated APK file had the following entry:
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="30" />
Clearly, the maxSdkVersion is preventing the OS from giving me the permission I need.
Using grep on the app\build directory, I found app\build\intermediates\manifest_merge_blame_file\appnameDebug\manifest-merger-blame-appname-debug-report.txt, which included these lines:
17 <uses-permission
17-->C:\path\to\my\appname\app\src\main\AndroidManifest.xml:12:2-76
18 android:name="android.permission.ACCESS_FINE_LOCATION"
18-->C:\path\to\my\appname\app\src\main\AndroidManifest.xml:12:19-73
19 android:maxSdkVersion="30" />
19-->[com.github.50ButtonsEach:flic2lib-android:1.3.1] C:\Users\moshe\.gradle\caches\transforms-3\dced3886509296f1029e8245af379a07\transformed\jetified-flic2lib-android-1.3.1\AndroidManifest.xml:17:9-35
It turns out the developers of this library originally used ACCESS_FINE_LOCATION for connecting to nearby Bluetooth devices, and since Android 12 has separate permissions for that, they don't need it anymore so they added a max SDK version.
I added the tools:remove="android:maxSdkVersion" property to the ACCESS_FINE_LOCATION <uses-permission /> element, and now my permissions work properly.

Related

How to request permissions on Android

I am very new to Android programming and I am having trouble requesting storage permission. The idea is to have the phone generate a small label that will print from a mobile printer via Bluetooth, but as proof of concept I was going to have the phone just save a PDF or something for now.
I added this line to the AndroidManifest.xml:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:remove="android:maxSDKVersion" />
and from the MainActivity.kt:
class MainActivity : AppCompatActivity() {
private val REQUEST_STORAGE = 101
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
println("Permissions Denied")
requestStoragePermission()
println("Passed Command")
} else {
println("PERMISSIONS GRANTED")
}
private fun requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
permission.WRITE_EXTERNAL_STORAGE
)
) {
requestPermissions(this, arrayOf(permission.WRITE_EXTERNAL_STORAGE), REQUEST_STORAGE)
} else {
// Eh, prompt anyway
requestPermissions(this, arrayOf(permission.WRITE_EXTERNAL_STORAGE), REQUEST_STORAGE)
}
}
}
No matter what iteration of the requestPermissions command I try, the dialog box never shows and attempting to save any file results in a failure. I know this question has been asked a lot, but none of the solutions that work for other people are working here and I'm not sure why.
I have tried:
\\this is latest iteration
requestPermissions(this, arrayOf(permission.WRITE_EXTERNAL_STORAGE), REQUEST_STORAGE)
\\this was first iteration
ActivityCompact.requestPermissions(
this#MainActivity,
arrayOf(permission.WRITE_EXTERNAL_SOTRAGE),
REQUEST_STORAGE
)
\\this one also caused an error so I abandoned the idea of moving this out of the main class
ActivityCompact.requestPermissions(
MainActivity(),
arrayOf(permission.WRITE_EXTERNAL_SOTRAGE),
REQUEST_STORAGE
)
I need the user to be able to give storage access, at least while it's still in development to convince my boss to buy a mobile printer I can use to print the actual label.
I have started default google sample project related to request runtime permissions topic. By default it uses camera permission. When I had changed Camera permission to WRITE_EXTERNAL_STORAGE permission it stops showing permission dialog too. It means nothing is wrong with your code, the issue has some different cause.
Likely it is related to changes in behaviour related to new Android API.
I haven't found root cause yet, but this links shows changes in behaviour on Android 9, 10, 11:
Different use cases
No need in permission since API 19
Variety of changes among different APIs
UPDATE
Code above doesn't show dialog for MANAGE_EXTERNAL_STORAGE permission, but you have asked for WRITE_EXTERNAL_STORAGE permission. Default google sample is able to show this permission dialog on Android API 30. Here is relevant code:
if (shouldShowRequestPermissionRationaleCompat(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// Display a SnackBar with a button to request the missing permission.
layout.showSnackbar(R.string.camera_access_required,
Snackbar.LENGTH_INDEFINITE, R.string.ok) {
requestPermissionsCompat(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_REQUEST_CAMERA)
}
} else {
layout.showSnackbar(R.string.camera_permission_not_available, Snackbar.LENGTH_SHORT)
// Request the permission. The result will be received in onRequestPermissionResult().
requestPermissionsCompat(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_REQUEST_CAMERA)
}
fun AppCompatActivity.requestPermissionsCompat(permissionsArray: Array<String>,
requestCode: Int) {
ActivityCompat.requestPermissions(this, permissionsArray, requestCode)
}

How do I request push notification permissions for android 13?

I've looked through this guide for android 13 push notifications
https://developer.android.com/about/versions/13/changes/notification-permission#user-choice
And I've looked at the guide for requesting permissions
https://developer.android.com/training/permissions/requesting#java
I've updated my compile and target to api 32.
Here is my code so far (in progress). Right now I'm just trying to get the notification prompt to show up.
if (Build.VERSION.SDK_INT >= 32) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY) == PackageManager.PERMISSION_GRANTED)
return;
ActivityResultLauncher<String> launcher = registerForActivityResult(
new ActivityResultContracts.RequestPermission(), isGranted -> {
}
);
launcher.launch(Manifest.permission.POST_NOTIFICATIONS);
}
The problem I have is I get an error cannot find symbol variable POST_NOTIFICATIONS.
What is the proper manifest permission for push notifications?
Maybe I'm a bit late to the party, I know... But I hope this can help others at least. You need to use compileSdkVersion 33 in your gradle file at the Module level. Then you'll be allowed to use the POST_NOTIFICATIONS permission without any issue.
Android 13 (API level 33) and higher supports a runtime permission for sending non-exempt (including Foreground Services (FGS)) notifications from an app: POST_NOTIFICATIONS. This change helps users focus on the notifications that are most important to them.
reference here
So you need to add this permission to AndroidManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
You need to follow few steps, add post notifications permission in manifest
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
then in your controller as for run time permission like generally we ask:
if (Build.VERSION.SDK_INT >= 33) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.POST_NOTIFICATIONS},101);
}
else {
createChannel();
}
}
Then Need to handle permission result as usual
How to add run time permission for notification permission in android studio,
Apps targeting Android 13 will now need to request notification permission from the user before posting notifications,”
Behavior changes: Apps targeting Android 13 or higher
https://developer.android.com/about/versions/13/behavior-changes-13
Add on manifest: uses-permission android: name="android.permission.POST_NOTIFICATIONS
and
Add in MainActivity after onCreate:
if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[]{POST_NOTIFICATIONS}, 1);
}

Cannot request Bluetooth permission on Wear OS Samsung Galaxy Watch 4

I've created a sample Wear OS app, which should discover BLE devices, but my code requires Bluetooth permission. When I put these lines in manifest:
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
corresponding permission is not displayed in settings/apps/permissions and every permission request does nothing. By the way, my BLE-devices (a speaker and a esp-32) is not shown in settings/Bluetooth also.
How can I grant Bluetooth permissions for my app or how can I connect BLE device to my watch?
upd:
I tried these:
if (checkSelfPermission(Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf<String>(Manifest.permission.BLUETOOTH), 1001)
}
if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf<String>(Manifest.permission.BLUETOOTH_CONNECT), 1001)
}
if (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf<String>(Manifest.permission.BLUETOOTH_SCAN), 1001)
}
if (checkSelfPermission(Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf<String>(Manifest.permission.BLUETOOTH_ADMIN), 1001)
}
But dialogs windows still are not displayed
According documentation, you need particular permissions in based of the target Android API version.
If your app targets Android 11 (API level 30) or lower, declare the following permissions in your app's manifest file:
BLUETOOTH is necessary to perform any Bluetooth classic or BLE communication, such as requesting a connection, accepting a connection, and transferring data.
ACCESS_FINE_LOCATION is necessary because, on Android 11 and lower, a Bluetooth scan could potentially be used to gather information about the location of the user.
If your app targets Android 9 (API level 28) or lower, you can declare the ACCESS_COARSE_LOCATION permission instead of the ACCESS_FINE_LOCATION permission.
In order to perform a scan to discover BLE devices the app must require explicitaly to the user the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission also to be declared in the AndroidManifest.xml.
In my project (WearOS API version 28) I used this code in the onCreate function of MainActivity class
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this,new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
1);
}
And I overrided the onRequestPermissionsResult function
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case 1:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Logger.d("MainActivity","Permission approved");
} else {
Logger.d("MainActivity","Error getting permission");
}
return;
}
}
This works for me, I hope would help you
there are some permissions like camera, bluetooth which need to be asked first and then manually provided. use this in the activity that loads first in your app.
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf<String>(Manifest.permission.CAMERA), 1001);
} //ask camera permissions
make sure to do required changes.

Android: App is rejected by Google because of background location

I have issues with my app recently, when it is out of nowhere rejected by Google Play because they found that I'm using background location. But in fact I'm not using this feature. I have only ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions and I'm using FusedLocationProviderClient to get location in my app. This location is requested only by user action inside app, so if its in background, this is never called. I checked merged manifest feature and I tried to find if some of my imported libs are using background location permission, but I didn't find anything. Also I preventively added <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" tools:node="remove"/> to my manifest to block any background location permission requests. I dont have any background services which are working with location at all. The only background service is FirebaseMessagingService for push notifications.
Anyone have this problem recently?
UPDATE:
I checked merged manifest in my app and I couldn't find ACCESS_BACKGROUND_LOCATION permission there. But I found some services which could trigger background location but I'm not sure. They are part of Firebase Crashlytics and they are probably used to send data to Firebase and they could work in a background. But I don't think they are sending any location. Also they are part of firebase plugin which is from Google.
<service
android:name="com.google.android.datatransport.runtime.scheduling.jobscheduling.JobInfoSchedulerService"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" >
</service>
<receiver
android:name="com.google.android.datatransport.runtime.scheduling.jobscheduling.AlarmManagerSchedulerBroadcastReceiver"
android:exported="false" />
UPDATE #2:
This is code I'm using to get location.
MainActivity:
/**
* Updating location every second/1 meter
*/
var currLocation: GpsLocation? = null
private var locationManager : LocationManager? = null
private fun initLocationManager() {
if (app.hasLocationPermission){
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
changeLocationUpdaters(true)
}
private fun changeLocationUpdaters(isEnabled: Boolean){
if (ActivityCompat.checkSelfPermission(
this#MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(
this#MainActivity,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager?.apply{
if (isEnabled && app.hasLocationPermission){
requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_TIME_INTERVAL, LOCATION_UPDATE_DIST_INTERVAL, this#MainActivity)
requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_TIME_INTERVAL, LOCATION_UPDATE_DIST_INTERVAL, this#MainActivity)
} else {
removeUpdates(this#MainActivity)
}
}
} else {
return
}
}
Then removing location updaters when app is in background:
override fun onPause() {
super.onPause()
changeLocationUpdaters(false)
}
override fun onResume() {
super.onResume()
changeLocationUpdaters(true)
}
Then I use FusedLocationProvider inside Fragment to get more accurate location. Its used only by calling function so its not automated like previous one. Its used in GoogleMap classes and also in some onClick events inside app to return current location. There is no service or updater calling it.
private inner class LocationCb(val lp: FusedLocationProviderClient,
val onFailure: (()->Unit)? = null,
val onSuccess: (GpsLocation)->Unit)
: LocationCallback() {
init {
val lr = LocationRequest.create().apply {
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
interval = 200
}
val lsr = LocationSettingsRequest.Builder().run {
addLocationRequest(lr)
build()
}
val check = LocationServices.getSettingsClient(activity!!).checkLocationSettings(lsr)
check.addOnCompleteListener {
try {
check.getResult(ApiException::class.java)
val task = lp.requestLocationUpdates(lr, this, Looper.getMainLooper())
task.addOnFailureListener {
onFailure?.invoke()
}
} catch (e: ApiException) {
when (e.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED-> if(!locationResolutionAsked){
// Location settings are not satisfied. But could be fixed by showing the user a dialog.
try {
// Cast to a resolvable exception.
val re = e as ResolvableApiException
// Show the dialog by calling startResolutionForResult(), and check the result in onActivityResult().
re.startResolutionForResult(mainActivity, MainActivity.REQUEST_LOCATION_SETTINGS)
locationResolutionAsked = true
} catch (e: Exception) {
e.printStackTrace()
}
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE->{
App.warn("Location is not available")
onFailure?.invoke()
}
}
}
}
}
fun cancel(){
lp.removeLocationUpdates(this)
currLocCb = null
}
override fun onLocationResult(lr: LocationResult) {
cancel()
val ll = lr.lastLocation
onSuccess(GpsLocation(ll.longitude, ll.latitude))
}
}
This location provider is cancelled after result is returned so its one-time use only. But Ive added similar cancellation method inside onPause and onStop for Fragment than it is in MainActivity to make sure that its inactive when app is in background.
override fun onStop() {
super.onStop()
currLocCb?.cancel()
}
override fun onPause() {
super.onPause()
currLocCb?.cancel()
}
Merged manifest may not contain all permissions
Unfortunately, not all libraries publish a manifest that contains all necessary <uses-permission> elements. That means, that simply checking your merged AndroidManifest.xml won't help much - you will have to check documentation for each library to find out which permissions it really needs, or just add necessary permissions to your own AndroidManifest.xml preemptively.
Background permission limitation for API 29
You also mentioned that your target SDK is 29. So, according to the official documentation here, you have to set the permission in your AndroidManifest.xml explicitly, if it's needed. Previously, it was granted automatically, if the app had foreground location access (basically, ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION).
On Android 10 (API level 29) and higher, you must declare the
ACCESS_BACKGROUND_LOCATION permission in your app's manifest in order
to request background location access at runtime. On earlier versions
of Android, when your app receives foreground location access, it
automatically receives background location access as well.
So, for older versions, your app was granted ACCESS_BACKGROUND_LOCATION automatically, because it was granted ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION beforehand.
Requesting location in background requires ACCESS_BACKGROUND_LOCATION
Additionally, even if you or any of your libraries do not set ACCESS_BACKGROUND_LOCATION anywhere, the system will still consider that your app is using background location for any situation except:
An activity that belongs to your app is visible.
Your app is running a
foreground service. When a foreground service is running, the system
raises user awareness by showing a persistent notification. Your app
retains access when it's placed in the background, such as when the
user presses the Home button on their device or turns their device's
display off.
Conclusion
What the latter means is that may have a library or libraries that need ACCESS_BACKGROUND_LOCATION, but it's not present in their AndroidManifest.xml for whatever reason. It used to work for API < 29 because your app was granted the permission automatically (due to foreground location permission).
Also, now, the system considers any usage of current location a background location if it's done outside of your visible Activity or not in a Foreground Service. So, make sure that you're not doing so in any part of your app.
Update
Based on your updated question, you are requesting a current location within OnCompleteListener by calling lp.requestLocationUpdates:
...
check.addOnCompleteListener {
try {
check.getResult(ApiException::class.java)
val task = lp.requestLocationUpdates(lr, this, Looper.getMainLooper())
task.addOnFailureListener {
onFailure?.invoke()
}
...
This can be a problem (I cannot be sure because you don't show how the class is used within your app) because the app may go to the background before OnCompleteListener completes, and so the location will be requested in the background.
As stated in the previous section, by doing so the system considers that you need a background location permissions to do so. So, you must unsubscribe your callback OnCompleteListener if your app goes to background.
You could use another version of addOnCompleteListener that also accept your Activity instance as shown here
public Task addOnCompleteListener (Activity activity, OnCompleteListener listener)
In this case, the listener will be automatically removed during Activity.onStop().
First of all, remove completely words ACCESS_BACKGROUND_LOCATION from your manifest. Even with tools:node="remove".
The second: if you haven't added ACCESS_BACKGROUND_LOCATION manually it doesn't mean it is not there - some libraries may have added it for you. Instead of checking your project manifest file - check merged manifest - the usual path to it is: (it may be different in your case if you have flavors)
/project/module/build/intermediates/manifests/full/debug/AndroidManifest.xml.
Check if there is ACCESS_BACKGROUND_LOCATION permission there - if there is - this means that some library added it there. Manually check all the manifests of all the libraries to find out which one has added it there. When you find it - delete it.
If your project heavily depends on the target library - you have another solution - write a disclosure in the app and play store console about why do you need to use background location and show it before the location permission dialog with message that looks like:
We need access to your location in the background to ensure our app can function correctly.
Keep in mind that this message may be not enough descriptive - but testers from google will notify you if it is.
Either way, disclosure is the last chance solution...
If you have no ACCESS_BACKGROUND_LOCATION and you do not use location in foreground service but only inside the app while it is running - write a letter to google support with all your arguments and ask them what exactly causes the rejection issue. Be polite and well-tempered - and it will be resolved. I have had similar issues in the past and contact with their release support always helped.

Android 6.0 bug ? Have permission but getScanResults() still return empty list in Android 6.0

I have request the permission in android version 6.0 - Marshmallow,But it still return empty list when using getScanResults().
private boolean checkPermission() {
List<String> permissionsList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (permissionsList.size() > 0) {
ActivityCompat.requestPermissions((Activity) mContext, permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
After request permission, then in the onRequestPermissionsResult method,I have get the permission of ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION, But I still can not the scan result
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
if (permissions.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
(permissions.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED)){
List<ScanResult> scanResults = mWifi.getScanResults();
//list is still empty
}
else {
// Permission Denied
Toast.makeText(mContext, getString(R.string.permission_deny), Toast.LENGTH_LONG).show();
}
break;
}
}
Is this a bug of android M?
You still need to enable WIFI after you request the permission. So in short, you have to do this in sequence for scanning the perimeter:
Request the necessary permissions (ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, ACCESS_COARSE_LOCATION). Additionally, on MM you need to request this at run-time, as you stated.
Enable WIFI with WifiManager#setWifiEnabled(true);
You don't have to enable location access programatically that I know off. But read the note below.
You have to register a BrodcastReceiver for SCAN_RESULTS_AVAILABLE_ACTION. This is where you get the signal that the scans are ready. Doesn't matter if you register through AndroidManifest or dynamically at run-time, as long as it's done before the next step.
You have to WifiManager#startScan() in order to request exactly ONE update for network scans. If you want more, set up a timer/timertask (recommended) or reschedule when you receive the previous one (which might never come)
Only on the BroadcastReceiver onReceive will you be able to call WifiManager#getScanResults() with plausible results.
Note: On some phones (Moto X 2014), I noticed you need basic location enabled to get any results, which only the user (system UI) seems to be able to do trigger on/off. If the user has location completely off, I can't seem to get a non-empty result list, even though the system UI can. This is likely due to Marshmallow needs to have location for Bluetooth and WiFi scans in user apps, and a bad implementation by Motorola, or a defect already fixed in latest Marshmallow bug tracker but not in Motorola's latest OTA, because this doesn't happen in a Nexus 5 or a Galaxy S6.
on nexus 5, with M update, it appears to me I also need to have GPS location turned on to get this working.
Maybe it cause by android M's runtime permission management,you can set targetSdkVersion 19(less than 21 or 23) to try again. It works for me
In Android Marshmallow 6.0.1 go to Settings > Connections and hold down Location. There click on Location method and you will see three options:
High accuracy: uses GPS, Wi-Fi and mobile networks.
Battery saving: uses Wi-Fi and mobile networks.
Device only: uses GPS.
Select Battery saving in order to get Wi-Fi scan results without enabling GPS.
The permission is requested when needed at run-time. Note that it is NOT:
Settings -> Location
It is checking:
Settings -> Applications -> (YOUR APP) -> Permissions
That is where the more granular run-time permission must be set. It must be set for each application as of version 6.

Categories

Resources