1

I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

 public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you

Fifou
  • 61
  • 3
  • 8

3 Answers3

1

I have just found the solution.

I had to take the context with

var context = Xamarin.Forms.Forms.Context;

instead of

var context = Android.App.Application.Context;

After that, cast works nicely

Thanks everybody

Fifou
  • 61
  • 3
  • 8
0

Try this

(YourActivityName)Forms.Context;

for example:

var activity = (YourActivityName)Forms.Context;
Muhammad Saad
  • 713
  • 1
  • 9
  • 31
-1

If you are in Activity.

You are casting Application context.

var context = Android.App.Application.Context; 

Replace it with below

var context = android.content.Context; 

If you are working in Service then you can ask for permission from where you are calling your service.

AmmY
  • 1,821
  • 1
  • 20
  • 31