I have this error "ContextCompat does not exist in the current context" and a "PackageManager does not contain PERMISSION_GRANTED definition"

3.7k views Asked by At

when I create the method output error "ContextCompat does not exist in the current context" and a "PackageManager does not contain definition PERMISSION_GRANTED" .. know if I should add any special directive. Thank you

METHOD

private void CheckSMSStatePermission()
{

int PermissionCheck = ContextCompat.CheckSelfPermission(this, Manifest.Permission.SendSms);
if (PermissionCheck != PackageManager.PERMISSION_GRANTED)
{
    Toast.MakeText(Activity,  "No se tiene permiso para enviar SMS.", ToastLength.Short).Show();
    ActivityCompat.requestPermissions(this, new String[] { Manifest.Permission.SendSms }, 1);
}
else
{
    Toast.MakeText(Activity, "Se tiene permiso para enviar SMS!", ToastLength.Short).Show();
}
}

Error 1

   Severity Code Description Project Project category Path File Line Column 
   Category Source Status deleted Tool
   Error CS1503 Argument 1: can not be converted from                      
 'LoginSystem.Authorization' to 'Android.Content.Context' LoginSystem 1 C: \ 
  Users \ Lenovo \ documents \ visual studio 2017 \ Projects \ LoginSystem \ 
   Documents \ visual studio 2017 \ Projects \ LoginSystem \ LoginSystem \ 
   Authorization.cs 229 70 Active Compiler IntelliSense Compiler

Error 2

   Severity Code Description Project Project category Path File Line Column 
   Category Source Status deleted Tool
   CS0117   'PackageManager' no contiene una definición para 
 'PERMISSION_GRANTED'   LoginSystem 1   C:\Users\Lenovo\documents\visual 
  studio 2017\Projects\LoginSystem\LoginSystem  
  C:\Users\Lenovo\documents\visual studio 
  2017\Projects\LoginSystem\LoginSystem\Autorizacion.cs 230 51  Compiler    
  IntelliSense  Activo  Compilador
2

There are 2 answers

3
AskNilesh On BEST ANSWER

change this

int PermissionCheck = ContextCompat.CheckSelfPermission(this, Manifest.Permission.SendSms);

to this

int PermissionCheck = ContextCompat.CheckSelfPermission(this, Manifest.permission.SEND_SMS;);

or try this

 String permission = android.Manifest.permission.SEND_SMS;
 if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
     != PackageManager.PERMISSION_GRANTED){
      ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
                    {permission}, 1);

 }

add this permission in manifest file

<uses-permission android:name="android.permission.SEND_SMS"/>
0
SushiHangover On

If you are trying to use ContextCompat.XXXX your Activity subclass needs to be from an AppCompatActivity (Not Activity...).

AppCompatActivity is available in the nuget package: Xamarin.Android.Support.v4:

<package id="Xamarin.Android.Support.v4" version="25.4.0.2" targetFramework="monoandroid71" />

Add that package and change your Activity to a AppCompatActivity