android - 如何使用广播接收器更新 UI?

标签 android xamarin xamarin.android

我需要使用广播接收器更新 UI。我编写了这段代码,但在调试时没有看到 UI 的任何更新。

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionTimeTick })]
private class broadcastReceiver : BroadcastReceiver
{
    private _MyActivityact;
    public void broadCastReceiver(_MyActivity act)
    {
        this.act = act;
    }

    public override void OnReceive(Context context, Intent intent)
    {
        _MyActivity.RunOnUiThread(() => {
                     updateUI(intent);   
        });                     
    }

    private void updateUI(Intent intent)
    {
        float mstartx = _MyActivity.getmStartX();
        TextView startx = _MyActivity.FindViewById<TextView>(Resource.Id.startx);
        startx.SetText(Convert.ToChar(mstartx));                 
    }
}

最佳答案

问题是您无法订阅ActionTimeTick你的方式。来自文档:

Broadcast Action: The current time has changed. Sent every minute. You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

在 Xamarin 中,IntentFilter monodroid.exe 在生成 AndroidManifest.xml 文件中的 intent-filter 元素时使用该属性,因此该属性将不起作用。

您需要做的是删除 IntentFilter 属性并在您的 MainActivity 中以编程方式注册接收器(例如)。

protected override void OnResume()
{
    base.OnResume();
    RegisterReceiver(yourReceiver, new IntentFilter(Intent. ActionTimeTick));
}

protected override void OnPause()
{
    base.OnPause();
    UnregisterReceiver(yourReceiver);
}

关于android - 如何使用广播接收器更新 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42805120/

相关文章:

android - Xamarin Android 应用程序在使用 r8 收缩编译时崩溃

android - 如何获得有关 wifi 信号强度变化的通知?

xamarin - 如何在完成之前取消计时器

c# - 如何在 Xamarin.Forms 上调用 HTTP2

Xamarin.Android 版本号似乎不一致

linux - Linux 版 monogame 支持 Android 解决方案吗?当我尝试创建解决方案时出现错误

android - textview 下面的 textview linearlayout

android - 具有 1 个值的数组的自定义 X 标签上的时间戳

android - 在小米的 miui (Poco x3) 中启动广播接收器不工作

xamarin - 导航页面 + 轮播页面 : weird scroll error