The accepted answer is a working solution, however, I would like to add some points for the sake of completeness.
The best built-in way to detect a mock location (not just since Marshmallow, but since API 18+) is to use Location.isFromMockProvider(), as stated in other answers and comments.
I extensively experimented with mock locations on different devices and OS versions and came to the following conclusion:
The KEY_MOCK_LOCATION
extra bears the exact same information as .isFromMockProvider()
, i.e. .isFromMockProvider()
will return true
when the extra is present and false
when it isn't. In other words, it provides no added value and is just a more complicated way of finding out whether an individual location was labeled as a mock by its provider. See here for more info.
So I would definitely recommend using .isFromMockProvider()
.
Both the extra and the getter can sporadically return false negatives, i.e. the location in question is a mock but not labeled as such. This is obviously really bad for certain use cases. I have written a detailed blog post on this subject if you want to learn more.
After struggling with Android location (and the mock labeling problem) for quite some time I published the LocationAssistant, a utility class that will reliably reject mock locations on non-rooted devices with API 15+. It also unburdens you from most of the FusedLocationProvider boilerplate. Maybe you'll find it useful for your next location-aware app project.