как получать оповещения о MapActivity, когда пользователь отключает GPS - PullRequest
0 голосов
/ 08 октября 2019

я делаю приложение на андроиде, используя java, который показывает текущий адрес на карте и выдает предупреждение при отключении gps.

public class LocationManagerCheck {

    LocationManager locationManager;
    Boolean locationServiceBoolean = false;
    int providerType = 0;
    static AlertDialog alert;

    public LocationManagerCheck(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        boolean gpsIsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean networkIsEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (networkIsEnabled == true && gpsIsEnabled == true) {
            locationServiceBoolean = true;
            providerType = 1;

        } else if (networkIsEnabled != true && gpsIsEnabled == true) {
            locationServiceBoolean = true;
            providerType = 2;

        } else if (networkIsEnabled == true && gpsIsEnabled != true) {
            locationServiceBoolean = true;
            providerType = 1;
        }

    }

    public Boolean isLocationServiceAvailable() {
        return locationServiceBoolean;
    }

    public int getProviderType() {
        return providerType;
    }

    public void createLocationServiceError(final Activity activity) {

        // show alert dialog if Internet is not connected
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.setMessage(
                "You need to activate location service to use this feature. Please turn on network or GPS mode in location settings")
                .setTitle("LostyFound")
                .setCancelable(false)
                .setPositiveButton("Settings",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent intent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                activity.startActivity(intent);
                                dialog.dismiss();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        });
        alert = builder.create();
        alert.show();
    }

Я использую этот код, который показывает предупреждение только при запуске Mapactivityно не во время activity. Я просто хочу, он показывает мне предупреждение, когда gps выключен или отключен пользователем, когда MapActivity открыта, помогите мне найти правильный код, спасибо заранее.

Ответы [ 2 ]

0 голосов
/ 08 октября 2019

Для этого вам нужно использовать Приемник вещания

Сначала необходимо зарегистрировать вещание

  private var receiverRegistered: Boolean = false

     override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                registerBroadcast()
        }

     private fun registerBroadcast() {
            val filter = IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)
            filter.addAction(Intent.ACTION_PROVIDER_CHANGED)
            this.registerReceiver(broadCastReceiver, filter)
            receiverRegistered = true
        }

private val broadCastReceiver = object : BroadcastReceiver() {
        override fun onReceive(contxt: Context?, intent: Intent?) {
            if (LocationManager.PROVIDERS_CHANGED_ACTION == intent?.action) {
                val locationManager = contxt?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                if (!isGpsEnabled) {
                    // call your alert here
                } 
            }
        }
    }

И самое главное - отменить регистрацию приемника вещания

override fun onDestroy() {
        if (receiverRegistered) {
            this.unregisterReceiver(broadCastReceiver)
        }
        super.onDestroy()
    }

Каждый раз, когда пользователь отключает GPS, он будет показывать предупреждение.

0 голосов
/ 08 октября 2019

Вы, вероятно, хотите знать, включает ли пользователь включение / выключение GPS. Этот вопрос может помочь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...