LocationListener 在禁用时不监听 gps。知道我做错了什么吗?

LocationListener doesnt listen for gps when it is disabled. Any idea what am i doing wrong?

我试图在禁用 gps 时弹出一条 window 消息,但在我启用或禁用时位置侦听器没有响应。我不明白我做错了什么。任何人都可以帮我解决这个问题吗?提前致谢!

这是我使用 locationlistener 的代码:

public class MapsActivityy extends AppCompatActivity {

    private LocationManager locationManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        //locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Initialize location manager.
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Check if user has granted permissions.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // We do not have permissions.
            return;
        }

        // Check if we did find a location provider.
        if (locationManager == null) {
            // No gps provider was found. Inform user.
            return;
        }
        // Initialize location manager and register location listener.
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                2000,
                10, locationListenerGPS);


        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            openGpsWindow();
        }else{
            updateLocationUI();
        }



    }




    //Location listener that listens for location state changes.
    LocationListener locationListenerGPS = new LocationListener() {
        @Override
        public void onLocationChanged(android.location.Location location) {
            // Called when the location has changed.
                    }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // Called when the provider status changes.
                    }

        @Override
        public void onProviderEnabled(String provider) {
                    }

        @Override
        public void onProviderDisabled(String provider) {
            // Called when the provider is disabled by the user.
            openGpsWindow();
        }
    };

    //Pops up a window in order to open GPS
    public void openGpsWindow() {
        Intent intent = new Intent(this, EnableGpsWindow.class);
        startActivity(intent);
    }
}

我试图在禁用 gps 时弹出一条 window 消息,但在我启用或禁用时位置侦听器没有响应。我不明白我做错了什么。任何人都可以帮我解决这个问题吗?提前致谢!

Don't use the gps provider , Kindly use the Fused location services , i have shared a code of using it already and mention the code to check the location request, just tap on link

 var locationRequest = LocationRequest()
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        locationRequest.setInterval(5000)
        locationRequest.setFastestInterval(1000)
        locationRequest.setSmallestDisplacement(2f)
// Create LocationSettingsRequest object using location request
        val builder = LocationSettingsRequest.Builder()
        builder.addLocationRequest(locationRequest)
        val locationSettingsRequest = builder.build()

        // Check whether location settings are satisfied
        // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
        val settingsClient = LocationServices.getSettingsClient(this)
        settingsClient.checkLocationSettings(locationSettingsRequest)
                .addOnFailureListener {

                    AppUtils.showToast(this,getString(R.string.enable_high_accuracy_mode),Toast.LENGTH_LONG).hashCode()
                    val callGPSSettingIntent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                   this@BusDriverDashboardActivity.startActivityForResult(callGPSSettingIntent,1)
                }.addOnSuccessListener { }

使用广播接收器获取启用或禁用 gps 的事件,然后使用内部广播接收器在您的应用程序中广播该事件。

这是您的广播接收器,它将侦听 gps 事件。

public class LocationStateChangeBroadcastReceiver extends BroadcastReceiver 
{

public static final String GPS_CHANGE_ACTION = "com.android.broadcast_listeners.LocationChangeReceiver";

@Override
public void onReceive(Context context, Intent intent) {


    if (intent.getAction() != null && intent.getAction().equals(context.getString(R.string.location_change_receiver))) {
        if (!isGpsEnabled(context)) {
            sendInternalBroadcast(context, "Gps Disabled");
        }
    }
}

private void sendInternalBroadcast(Context context, String status) {
    try {
        Intent intent = new Intent();
        intent.putExtra("Gps_state", status);
        intent.setAction(GPS_CHANGE_ACTION);
        context.sendBroadcast(intent);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static boolean isGpsEnabled(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
}

创建内部广播接收器class 以接收事件。

class InternalLocationChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

//        this method will be called on gps disabled
//        call openGpsWindow  here
    }
}

现在将此代码复制到您的 activity 中以注册广播接收器。

 public class MainActivity extends AppCompatActivity {

InternalLocationChangeReceiver internalLocationChangeReceiver = new
        InternalLocationChangeReceiver();

LocationStateChangeBroadcastReceiver locationStateChangeBroadcastReceiver = new LocationStateChangeBroadcastReceiver();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        registerReceiver(locationStateChangeBroadcastReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationStateChangeBroadcastReceiver.GPS_CHANGE_ACTION);
        registerReceiver(internalLocationChangeReceiver, intentFilter);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(locationStateChangeBroadcastReceiver);
    unregisterReceiver(internalLocationChangeReceiver);
}
}