简体   繁体   中英

Get Location Permission from User in Android App

I am implementing Access Location from user.Following is my Code. My problem is When I am clicking on Location permission it not getting the location.Bt when i am manually turn on the location from setting after that it giving me the location.My requirement is i Want compulsory check the Location permission from my App ie (it goes to setting and turn on location) .I gave all Permission in AndroidMeanifest file.And following is my SpashScreen.

package com.example.sbaapp;
public class SpashScreen extends AppCompatActivity {
    AlertDialog.Builder alertDialog;

    String[] perms = {"android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_SMS"};
    int permsRequestCode = 200;





    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spash_screen);
        alertDialog = new AlertDialog.Builder(SpashScreen.this, R.style.Theme_AppCompat_DayNight_DarkActionBar);

        FirebaseApp.initializeApp(getApplicationContext());

        //requestPermissions(perms, permsRequestCode);



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(!CheckPermissions()){
                requestPermissions(perms,permsRequestCode);
            }
        }


    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean CheckPermissions() {
        int LocationPermission=checkSelfPermission(perms[0]);
        int ReadSmsPermission=checkSelfPermission(perms[1]);

        Log.d("Inside Permission","");

        return LocationPermission== PackageManager.PERMISSION_GRANTED && ReadSmsPermission==PackageManager.PERMISSION_GRANTED;

    }


 @Override
    protected void onStart() {
        super.onStart();


        SubscribeToTopic();
        if (new SessionManager(getApplicationContext()).ISLOGIN()) {
            Intent intent = new Intent(SpashScreen.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        } else {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(SpashScreen.this, Activity_home.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                }
            }, 60000);
        }
    }
    private void SubscribeToTopic() {
        FirebaseMessaging.getInstance().subscribeToTopic("SBASURVEY")
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        String msg = "SuccessGeneralNot";
                        if (!task.isSuccessful()) {
                            msg = "Failed";
                        }
                        Log.d("TopicstatusForGeneral", msg);

                    }
                });

    }

   @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){

        switch(permsRequestCode){

            case 200:

                boolean locationAccepted = false;
                boolean smspermissionaccepted=false;

                if(grantResults.length>=2) {
                    locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    smspermissionaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                }else if(grantResults.length>=1){
                    if(permissions[0].equals("android.permission.ACCESS_FINE_LOCATION")){
                        locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                        smspermissionaccepted=true;
                    }else {
                        locationAccepted=true;
                        smspermissionaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    }
                }
                if(!(locationAccepted || smspermissionaccepted)){

                    new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept Both the permissions In Order to Smooth Working Of Application Functionality")
                            .setPositiveButton("Ok",new SpashScreen.OkListenerForBoth())
                            .setNegativeButton("Cancel",null)
                            .create()
                            .show();
                }else if(!locationAccepted){

                    new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept This Location Based permissions In Order to Smooth Working Of Application Functionality")
                            .setPositiveButton("Ok",new SpashScreen.OkListenerForLocation())
                            .setNegativeButton("Cancel",null)
                            .create()
                            .show();
                }

                else if(!smspermissionaccepted){

                    new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept This SMS Read permissions In Order to Smooth Working Of Application Functionality")
                            .setPositiveButton("Ok",new SpashScreen.OkListenerForSmS())
                            .setNegativeButton("Cancel",null)
                            .create()
                            .show();
                }

                break;

        }

    }
    public class OkListenerForBoth implements AlertDialog.OnClickListener{

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onClick(DialogInterface dialog, int which) {
            requestPermissions(perms,permsRequestCode);
        }
    }
    public class OkListenerForLocation implements AlertDialog.OnClickListener{

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onClick(DialogInterface dialog, int which) {
            requestPermissions(new String[]{perms[0]},permsRequestCode);
        }
    }

    public class OkListenerForSmS implements AlertDialog.OnClickListener{

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onClick(DialogInterface dialog, int which) {
            requestPermissions(new String[]{perms[1]},permsRequestCode);
        }
    }
}

Use the code below it will open a location request dialog and then you will be able to get the location.

if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();
        googleApiClient.connect();

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);  

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                          break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                        try {

                            status.startResolutionForResult(
                                    getActivity(), 1000);
                        } catch (IntentSender.SendIntentException e) {

                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        break;
                }
            }
        });
    }

Please do this way

add library in app from gradle

// Dexter runtime permissions
implementation 'com.karumi:dexter:5.0.0'

// add permissions in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />



// please call this method in your oncreate() method of splash.
requestPermission(); 



/**
 * Requesting multiple permissions (storage and location) at once
 * This uses multiple permission model from dexter
 * On permanent denial opens settings dialog
 */
private void requestPermission() {
    Dexter.withActivity(this)
            .withPermissions(             
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    // check if all permissions are granted
                    if (report.areAllPermissionsGranted()) {
                        Log.e(TAG, "All permissions are granted!");
                    }

                    // check for permanent denial of any permission
                    if (report.isAnyPermissionPermanentlyDenied()) {
                        // show alert dialog navigating to Settings
                        showSettingsDialog();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).
            withErrorListener(new PermissionRequestErrorListener() {
                @Override
                public void onError(DexterError error) {
                    Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
                }
            })
            .onSameThread()
            .check();
}

/**
 * Showing Alert Dialog with Settings option
 * Navigates user to app settings
 * NOTE: Keep proper title and message depending on your app
 */
private void showSettingsDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Need Permissions");
    builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
    builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            openSettings();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();

}

// navigating user to app settings
private void openSettings() {
    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivityForResult(intent, 101);
}

Hope it will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM