Получить разрешение от пользователя в приложении Android - PullRequest
0 голосов
/ 01 февраля 2020

Я использую Access Location от пользователя. Следующий код - мой код. Моя проблема заключается в том, что, когда я нажимаю на Разрешение местоположения, оно не получает местоположение. Но когда я вручную включаю местоположение из настроек, после этого оно дает мне местоположение. Моё требование: я хочу, чтобы я обязательно проверял разрешение на местоположение из моего приложения, т. Е. ( он переходит к настройке и включению местоположения). Я дал все разрешения в файле AndroidMeanifest. И вот мой 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);
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 01 февраля 2020

Пожалуйста, сделайте так

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

Надеюсь, это поможет

0 голосов
/ 01 февраля 2020

Используйте приведенный ниже код, откроется диалоговое окно запроса местоположения, а затем вы сможете получить местоположение.

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;
                }
            }
        });
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...