Search code examples
androidgpssplash-screen

How to turn on GPS programmatically


I'm creating an android application which uses google maps, so I need the GPS to turn on, I have an splash activity where im trying to check if GPS is on. The thing is that I can check if GPS is on or off, but I don't know how to create a dialog so the user can turn the GPS on. I saw in several apps that when you open it, it shows u a Dialog which askes the user if the GPS should be turned on, and if the user chose yes the GPS turned on automatically. And if the user chose no, the dialog closed and reopened again. This process repeats itself until the user choses yes. How can I achieve something like this?

Here is what I have this far.:

public class ActividadSplash extends AppCompatActivity {

    private static final long SPLASH_SCREEN_DELAY = 6000;
    private ProgressBar barra;
    private int progressStatus = 0;
    private Handler handler = new Handler();

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

        final LocationManager manager = (LocationManager)getApplicationContext().getSystemService    (Context.LOCATION_SERVICE );

        if(!manager.isProviderEnabled( LocationManager.GPS_PROVIDER)){ 
            CheckEnableGPS();
        }
        else{
            barra = (ProgressBar) findViewById(R.id.barraProgreso2);
            barra.setScaleY(3f);

            new Thread(new Runnable() {
                public void run() {
                    while (progressStatus < 100) {
                        progressStatus += 1;
                        //Update progress bar with completion of operation
                        handler.post(new Runnable() {
                            public void run() {
                                barra.setProgress(progressStatus);
                                if(progressStatus==100){
                                    finish();

                                    ParseUser usuario= ParseUser.getCurrentUser();
                                    if(usuario!=null){

                                        Intent intento = new Intent(getApplicationContext(), DrawerPrincipal.class);
                                        intento.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intento.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intento);

                                    }else{

                                        Intent intento = new Intent(getApplicationContext(), ActividadLogin.class);
                                        intento.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intento.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intento);
                                    }
                                }
                                //   textView.setText(progressStatus+"/"+progressBar.getMax());
                            }
                        });
                        try {
                            // Sleep for 200 milliseconds.
                            //Just to display the progress slowly
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }    
    }

    private void CheckEnableGPS() {
        String provider = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(!provider.equals("")){
            //GPS Enabled
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Enable GPS");  // GPS not found
            builder.setMessage("The app needs GPS to be enabled do you want to enable it in the settings? "); // Want to enable?
            builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            });
            builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            builder.setCancelable(false);
            builder.create().show();
            return;
        }
    }
}

Solution

  •  private void showGpsDialogAndGetLocation() {
            mGoogleApiClient = new GoogleApiClient.Builder(LoginActivity.this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
    
            //initialize the builder and add location request paramenter like HIGH Aurracy
            locationRequest = LocationRequest.create()
                    .setInterval(10 * 60 * 1000) // every 10 minutes
                    .setExpirationDuration(10 * 1000) // After 10 seconds
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);
    
            // set builder to always true (Shows the dialog after never operation too)
            builder.setAlwaysShow(true);
    
            // Then check whether current location settings are satisfied:
            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
    
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            // All location settings are satisfied. The client can initialize location
                            // requests here.
                            getLocationAndSaveInDatabase();
                            break;
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the user
                            // a dialog.
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(
                                        LoginActivity.this,
                                        REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have no way to fix the
                            // settings so we won't show the dialog.
                            break;
                    }
                }
            });
        }
    
    
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                insertLocationCoordinatesInDatabase(latitude, longitude);
    
            }
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    
        }
    
        @Override
        public void onProviderEnabled(String provider) {
    
        }
    
        @Override
        public void onProviderDisabled(String provider) {
    
        }
    
    
    
        @Override
        public void onConnected(@Nullable Bundle bundle) {
    
        }
    
        @Override
        public void onConnectionSuspended(int i) {
    
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    
        }
    
    
    
    **Implement These Interfaces in class**
    
    implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener