简体   繁体   中英

android call runtime permission with dialog

I have app that requests runtime permission for call on app start with dialog, but somehow my code doesn't request any permission or work. I need that when the app starts; ask the user for permission to call and in case the user refused, ask again for permission and move to in permissions settings.

Here's my code:

public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private AdView mAdView;

private Button button_id;
private Button button_mobily;
private Button button_stc;
private Button button_zain;
private Button button_share;
private Button button_exit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dash);
    NativeExpressAdView adView = (NativeExpressAdView)findViewById(R.id.adView);

    AdRequest request = new AdRequest.Builder().build();
    adView.loadAd(request);

    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    Bundle bundle = new Bundle();
    bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "main");
    bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "opened");
    bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
    mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

    isPermissionGranted();



    button_exit = (Button) findViewById(R.id.exit_buton_id);
    button_share = (Button) findViewById(R.id.Share_buton);
    button_id = (Button) findViewById(R.id.edit_id);
    button_mobily = (Button) findViewById(R.id.mobily_buton);
    button_stc = (Button) findViewById(R.id.stc_buton);
    button_zain = (Button) findViewById(R.id.zain_buton);


    button_id.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, NationalId.class);
            MainActivity.this.startActivity(myIntent);

        }
    });


    button_share.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "test");
                String sAux = "\n download my app\n\n";
                sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "share on"));
            } catch (Exception e) {
                //e.toString();
            }

        }
    });

    button_exit.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {

            close();
        }
    });

    button_mobily.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorMobily.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

    button_stc.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorSTC.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

    button_zain.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorZain.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

}

public boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG", "Permission is granted");
            return true;
        } else {

            Log.v("TAG", "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG", "Permission is granted");
        return true;
    }
}

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

        case 1: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


public void close() {
    // TODO Auto-generated method stub
    finish();
    System.exit(0);
}


}

You don't need to check the Android version, Android is smart enough to know what the OS version is on the user's device.

Also if you're trying to get the ability to Call you need to change how the permission is called.

public boolean isPermissionGranted() {
Intent callOfficeIntent = new Intent(Intent.ACTION_CALL);
callOfficeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callOfficeIntent.setData(Uri.parse("tel:" + mNumberToCall));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CALL_PHONE},
                        10);
                return;
            } else {
                try {
                    startActivity(callOfficeIntent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(getApplicationContext(), "No number to call", Toast.LENGTH_SHORT).show();
                }
            }
}

If you just want to get the permission but not make the call right away place this inside your method. This just asks for permission as a DialogBox.

if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
                   if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_PHONE_STATE)){
                       //Show Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                       builder.setTitle("Need Permission");
                       builder.setMessage("This app needs phone permission.");
                       builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_CALLBACK_CONSTANT);
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else if (permissionStatus.getBoolean(Manifest.permission.READ_PHONE_STATE,false)) {
                       //Previously Permission Request was cancelled with 'Dont Ask Again',
                       // Redirect to Settings after showing Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                       builder.setTitle("Need Permission");
                       builder.setMessage("This app needs storage permission.");
                       builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               sentToSettings = true;
                               Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                               Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                               intent.setData(uri);
                               startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                               Toast.makeText(getActivity(), "Go to Permissions to Grant Phone", Toast.LENGTH_LONG).show();
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   }  else {
                       //just request the permission
                       requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_CALLBACK_CONSTANT);
                   }
                   txtPermissions.setText("Permissions Required");


                   SharedPreferences.Editor editor = permissionStatus.edit();
                   editor.putBoolean(Manifest.permission.READ_PHONE_STATE,true);
                   editor.commit();
               } else {
                   //You already have the permission, just go ahead.
                   proceedAfterPermission();
               }
           }
       });
   }

private void proceedAfterPermission() {
       txtPermissions.setText("We've got the permission");
       Toast.makeText(getActivity(), "We got All Permissions", Toast.LENGTH_LONG).show();
   }

Don't have to use the last method, just change the textView to a toast.

I found a simple Github library developed by "Nabin Bhandari". It is easy to implement and can be customized directly. Github library link...

Please add this dependency to add this library to your code.

implementation 'com.nabinbhandari.android:permissions:3.8'

This allow you to request single permission, multiple permission and do customize your own dialog.

Furthermore,

  • You can also override other methods like onDenied, onJustBlocked, etc if you want to change the default behaviour.
  • Dialogue messages and texts can be modified by building the options parameter.
  • See documentation in the source code for more customizations.

Use this code to ask multiple permissions samuntanely.

 String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() { @Override public void onGranted() { // do your task. } });

Use this code if you want to Customized permissions request:

 String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION}; String rationale = "Please provide location permission so that you can ..."; Permissions.Options options = new Permissions.Options() .setRationaleDialogTitle("Info") .setSettingsDialogTitle("Warning"); Permissions.check(this/*context*/, permissions, rationale, options, new PermissionHandler() { @Override public void onGranted() { // do your task. } @Override public void onDenied(Context context, ArrayList<String> deniedPermissions) { // permission denied, block the feature. } });

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