Окно alertDialog не работает, чтобы включить GPS, когда он отключен - PullRequest
0 голосов
/ 08 октября 2019

Я не могу понять, почему окно alertDialog не появляется, когда я вхожу в свое приложение, и GPS отключен ... Может кто-нибудь проверить мой код и сказать мне, что исправить, чтобы всплывающее окно alertDialog всплывало, когда GPSвыключен? У меня есть код внизу, «включение GPS при отключении», но диалоговое окно все равно не открывается. Заранее спасибо.

public class CoPilotMapActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final int REQUEST_CHECK_SETTINGS = 0x1;
    private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
    private static final int REQUEST_FINE_LOCATION = 1;
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
    private static final long FASTEST_INTERVAL = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    private static final String TAG = "";
    private static final long MIN_TIME_BW_UPDATES = 1;
    private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
    private boolean mRequestingLocationUpdates;
    private static final int REQUEST_LOCATION = 1;

    GoogleMap mMap;
    private GeoFire mGeoFire;
    private LocationRequest locationRequest;
    private LocationCallback locationCallback;
    private Marker currentUser;
    private DatabaseReference myLocationRef;
    private GeoFire geoFire;

    private LocationSettingsRequest mLocationSettingsRequest;
    private SettingsClient mSettingsClient;
    private FusedLocationProviderClient mFusedLocationClient;

    private Button mStartUpdatesButton;
    private Button mLogout;
    Button mRequest;

    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private TextView mLastUpdateTimeTextView;

    private String mLatitudeLabel;
    private String mLongitudeLabel;
    private String mLastUpdateTimeLabel;

    private String mLastUpdateTime;
    private LocationCallback mLocationCallback;
    private Location mCurrentLocation;
    private LatLng mPickupLocationLatLng;
    LocationManager mLocationManager;
    final CoPilotMapActivity mContext = this;

    Location mLastLocation;
    LocationRequest mLocationRequest;

    Location location; // location
    String latitude; // latitude
    String longitude; // longitude
    private LocationManager locationManager;
    private double mLatitude;
    private double Longitude;
    private boolean isGPSEnabled;
    private boolean isNetworkEnabled;
    private boolean canGetLocation;
    private Object markerDestination;
    private LatLng pickupLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_co_pilot_map);

        //Add Permission
        ActivityCompat.requestPermissions(this, new String[]
                {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        //Signout from firebase after declaring button up top
        mLogout = (Button) findViewById(R.id.logout);
        //Call an uber driver
        mRequest = (Button) findViewById(R.id.request);
        mLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(CoPilotMapActivity.this, "Sign out successful", Toast.LENGTH_SHORT).show();
                FirebaseAuth.getInstance().signOut();
                //To take you to a different page you create an intent
                Intent intent = new Intent(CoPilotMapActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        });

        //requesting a driver
        //WORK ON THIS PART NULL POINTER EXCEPTION COMING UP ON GETLATITUDE FUNCTION
        mRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                    //check if gps is enabled or not AND TURN IT ON IF IT'S NOT
                    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        //Write Function to enable the gps
                        OnGPS();
                    } else {
                        //If GPS IS ALREADY ON then ...
                        getLocation();
                    }

                    String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
                    //send request and pinpoint exact location from where customer
                    //will be picked up from
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("customerRequest");
                    GeoFire geoFire = new GeoFire(ref);
                        geoFire.setLocation(userId, new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));

                        //create pickup location
                        mPickupLocationLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                        mMap.addMarker((new MarkerOptions()
                                .position(mPickupLocationLatLng)
                                .title("Pickup Here")));

                        //FIGURE OUT HOW TO GET THIS REQUEST CAR BUTTON TO WORK IT'S NOT CHANGING TEXT!!!!!!!!!!!!!!!!!!!!!!!!!

                        //change text of request button when it is pressed to request driver
                        mRequest.setText("Getting your driver...");
                    }
                }

        });
    }
    /**
     * enabling gps if it's turned off when accessing application
     */
    private void OnGPS() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }




    /**
     * MAYBE I'LL GET RID OF THIS ENABLE GPS METHOD AND FUNCTION WHICH ISN'T WORKING
     */
    private void turnGPSOn(){
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(!provider.contains("gps")){ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }




    private void turnGPSOff(){
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(provider.contains("gps")){ //if gps is enabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }
...