我需要使用广播接收器更新 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/