如何以 xamarin 形式获取意图活动结果 [英] How to get intent activity result in xamarin forms

查看:34
本文介绍了如何以 xamarin 形式获取意图活动结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用依赖项服务来启动在我的 xamarin 表单应用程序中启用 BT 的意图.但是我发现很难将结果恢复为 xamarin 形式.是否有任何机制可以将活动结果通知返回到表单应用程序.在表单中,

I am trying to use dependency service to initiate intent for enabling BT in my xamarin forms app. But Iam finding difficulty in getting result back to xamarin forms. Is there any mechanism to get activityresult notification back to forms app. In forms,

DependencyService.Get<IBluetoothHandler>().EnableBluetooth();

在安卓中,

Activity activity = Forms.Context as Activity;
Intent intent = new Intent(BluetoothAdapter.ActionRequestEnable);
activity.StartActivityForResult(intent, 1);

我怎样才能将这个活动结果写入表格?

How can i get this activity result to forms?

谢谢

推荐答案

您可以在 android 项目的 MainActivity 中覆盖 OnActivityResult 方法.Xamarin.Forms 仅对整个应用程序使用一个活动(在幕后).所以就用这个吧.

You can override the OnActivityResult method in your MainActivity in your android project. Xamarin.Forms uses just one activity for the whole app (behind the scenes). So just use this one.

要通知您的页面(或只是您的 PCL/Forms 项目中的另一个类),请使用 消息中心 由 Xamarin.Forms 提供.

To inform your page (or just another class in your PCL/Forms project) use the messagingcenter provided by Xamarin.Forms.

这是一个例子:

您在 MainActicity(Android 项目)中的方法:

Your method in your MainActicity (android project):

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    // Send trough the messaging sender (maybe someone subscribes to it)
    MessagingCenter.Send(
        new ActivityResultMessage {RequestCode = requestCode, ResultCode = resultCode, Data = data}, ActivityResultMessage.Key);
}

然后是您的消息传递类:

Then your messaging class:

public class ActivityResultMessage
{
    public static string Key = "arm";

    public int RequestCode { get; set; }

    public object ResultCode { get; set; }

    public object Data { get; set; }
}

然后在类中使用如下代码处理结果:

And then use the following code in the class to handle the result:

// Subscribe to the onactivityresult-message
MessagingCenter.Subscribe<ActivityResultMessage>(this, ActivityResultMessage.Key, (sender) =>
{
    // do some magic =)
});

请阅读有关消息中心的内容(上面提供的链接),以了解背后的内容.

Please read the stuff about the messagincenter (link provided above), to understand the things behind.

这篇关于如何以 xamarin 形式获取意图活动结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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