无法将上下文转换为活动 Xamarin [英] Can not cast context into activity Xamarin

查看:34
本文介绍了无法将上下文转换为活动 Xamarin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 xamarin 中遇到问题,我需要一些帮助,请

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

xamarin 教程中,我希望通过 DependencyService 启动电话.

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

这里是Android部分的服务实现:

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

android.permission.CALL_PHONE

.我确切地说我已经在 manifest 中给予了许可.我已经读到我需要在运行时注册权限.这就是我正在尝试的

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

但我需要当前的 Activity 作为参数,我无法将当前的 Context 转换为 Activity.

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.

谢谢

推荐答案

我刚刚找到了解决方案.

I have just found the solution.

我必须结合上下文

var context = Xamarin.Forms.Forms.Context;

var context = Xamarin.Forms.Forms.Context;

代替

var context = Android.App.Application.Context;

var context = Android.App.Application.Context;

在那之后,演员工作得很好

After that, cast works nicely

谢谢大家

这篇关于无法将上下文转换为活动 Xamarin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆