android studio 中的 GPS 状态 - API 级别 29

问题描述

我正在用面向 API 29 设备的 java 中的 android studio 编写一个 android 应用程序。我已经编写了一个 GPSReceiver(它扩展了 broadcastReceiver),我需要知道 GPS 状态是否已经改变(即添加一个位置侦听器)。

在早期版本的 Android 中,我知道这可以通过

ContentResolver contentResolver = context.getContentResolver();
int state = Settings.Secure.getInt(contentResolver,Settings.Secure.LOCATION_MODE);
Log.i(TAG,"GPS status changed,new state = " + state);

if (state == Settings.Secure.LOCATION_MODE_OFF)
  do_smth;
else
  do_smth_else;

在 Android 11(API 级别 30)中,下一个代码段似乎适合我。

boolean state = intent.getIntExtra(LocationManager.EXTRA_LOCATION_ENABLED,-1);

if (state)
  do_smth;
else
  do_smth_else;

但是,我不知道如何在 API 29 中获得这种确切的行为。

解决方法

你可以试试这个代码,它对我有用

public boolean isGPSOn() {
    boolean check = false;
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        check = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }
    return check;
}