LocationListener не слушает GPS, когда он отключен.Есть идеи, что я делаю не так? - PullRequest
0 голосов
/ 06 февраля 2019

Я пытаюсь открыть окно сообщения, когда GPS отключен, но слушатель местоположения не отвечает, когда я включаю или отключаю.Я не понимаю, что я делаю не так.Кто-нибудь может мне помочь?Заранее спасибо!

Это мой код, в котором я использую 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 отключен, но слушатель местоположения не отвечаеткогда я включаю или отключаю.Я не понимаю, что я делаю не так.Кто-нибудь может мне помочь?Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 06 февраля 2019

Используйте широковещательный приемник, чтобы получать включенные или отключенные события 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 InternalLocationChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

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

Теперь скопируйте этот код в своей деятельности для регистрации приемников вещания.

 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);
}
}
0 голосов
/ 06 февраля 2019

Не используйте gps-провайдера, пожалуйста, используйте сервисы Fused location, я уже поделился кодом его использования и упомянул код для проверки запроса местоположения, просто нажмите на ссылку

 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 { }

https://stackoverflow.com/a/54551020/4754710

...