如何以编程方式打开GPS

时间:2016-02-11 13:35:54

标签: android gps splash

我正在创建一个使用谷歌地图的Android应用程序,所以我需要打开GPS,我有一个飞溅活动,我试图检查GPS是否打开。问题是我可以检查GPS是打开还是关闭,但我不知道如何创建对话框,以便用户可以打开GPS。我在几个应用程序中看到,当你打开它时,它会显示一个Dialog,如果GPS应该打开,它会询问用户,如果用户选择是,GPS会自动打开。如果用户选择“否”,则关闭对话框并再次重新打开。这个过程重复进行,直到用户选择是。我怎样才能实现这样的目标呢?

这是我迄今为止所拥有的。:

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

1 个答案:

答案 0 :(得分:3)

 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