ContentResolver contentResolver = getContext().getContentResolver();
// Find out what the settings say about which providers are enabled
int mode = Settings.Secure.getInt(
contentResolver, Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
if (mode == Settings.Secure.LOCATION_MODE_OFF) {
// Location is turned OFF!
} else {
// Location is turned ON!
}
fun Context.isLocationEnabled(): Boolean {
val locationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return LocationManagerCompat.isLocationEnabled(locationManager)
}
创建BroadcastReceiver:
class LocationBroadcastReceiver @Inject constructor(private val context: Context) : BroadcastReceiver() {
private val locationStateChange: BehaviorRelay<Boolean> = BehaviorRelay.createDefault(context.isLocationEnabled())
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action == LocationManager.PROVIDERS_CHANGED_ACTION) {
val state = context.isLocationEnabled()
locationStateChange.accept(state)
}
}
fun subscribeState(): Flowable<Boolean> {
return locationStateChange.toFlowable(BackpressureStrategy.LATEST)
}
/**
* Listen to subscribeState() to receive updates
*/
fun register() {
val filter = IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)
val receiverFlags = ContextCompat.RECEIVER_NOT_EXPORTED
ContextCompat.registerReceiver(context, this, filter, receiverFlags)
}
fun unregister() {
context.unregisterReceiver(this)
}
}
4条答案
按热度按时间yeotifhr1#
这对我很有效:
将接收方添加到清单文件:
检查接收器中的两个位置提供程序:
虽然由于明显的原因,这个接收器被调用了不止一次,但它会告诉你状态。
cx6n0qe32#
你可以用这种方法简单得多。在BroadcastReceiver的**onReceive()**方法中:
感谢这段代码:LocationManagerTest.java
ngynwnxp3#
您可以使用下面的代码来检查位置服务是否启用
cgyqldqp4#
2023:当用户在窗帘菜单中切换位置时,这个解决方案会监听并做出React。困难的部分是弄清楚要使用哪个“意图”过滤器标志(
LocationManager.PROVIDERS_CHANGED_ACTION
)。在我的示例中,我使用
@Inject constructor
(Hilt)。如果你不这样做,那么只需将context
作为参数发送给register()
和unregister()
:register(context: Context)
等Context上的扩展:
创建BroadcastReceiver:
现在您可以订阅
从viewModel或compose类中调用并执行必须执行的操作。