Search code examples
androidandroid-permissionsandroid-location

Is it possible to get logs for when an app is trying to access location while in the background?


Google keeps telling me my app is accessing the location in the background. I'm targeting SDK 29, and I do not have the ACCESS_BACKGROUND_LOCATION permission. I do have ACCESS_FINE_LOCATION.

I'm starting to think that maybe an ad network is doing it in the background, but I would like to confirm this by looking at logs. Is there a way to do that?

Edit: The answer below about AppOps has been very useful however I've submitted an update fixing every issue found that way and I'm still having a problem with the Play Store rejecting the update due to background location. So is there some other way to figure this out? maybe something on older versions of Android?


Solution

  • If you have access to an Android 11 device, there are new data access APIs available that you can tap into to find out what in your app is using dangerous permissions like this.

    In this sample project (profiled in this book), I have some code to record stack traces from all dangerous permission uses:

        getSystemService(AppOpsManager::class.java)
          ?.setOnOpNotedCallback(executor, object : AppOpsManager.OnOpNotedCallback() {
            override fun onNoted(op: SyncNotedAppOp) {
              Log.d(TAG, "onNoted: ${op.toDebugString()}")
              RuntimeException().printStackTrace(System.out)
            }
    
            override fun onSelfNoted(op: SyncNotedAppOp) {
              Log.d(TAG, "onSelfNoted: ${op.toDebugString()}")
              RuntimeException().printStackTrace(System.out)
            }
    
            override fun onAsyncNoted(op: AsyncNotedAppOp) {
              Log.d(TAG, "onAsyncNoted: ${op.toDebugString()}")
              RuntimeException().printStackTrace(System.out)
            }
          })
    

    (as part of other code in a custom Application subclass)

    In the context of that sample, it will record the fact that the app is obtaining the location from its viewmodel. But, that's just based on the sample — in a larger app, it would record the permission uses from anything, including your ad network library.