TickEvent
收到自定义消息时,我正在尝试启动BroadcastReceiver
。
例如,当intent.Action == Intent.ActionTimeTick
(而不是GRID_STARTED
)时,它可以正常工作。我注释掉了工作代码,因此您可以轻松进行实验。
似乎我正在丢失有关动作的重要事项。您能帮我一下吗?
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace TestApp
{
[Activity(Label = "BroadcastUpdateFormExample", MainLauncher = true)]
public class MainActivity : Activity
{
int count = 1;
TextView txtNote;
BroadcastMessageCatcher catcher;
static readonly string TAG = "MainActivity";
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
txtNote = FindViewById<TextView>(Resource.Id.textView1);
Button button = FindViewById<Button>(Resource.Id.button1);
button.Click += delegate
{
button.Text = string.Format("{0} clicks!", count++);
BroadcastStarted();
};
catcher = new BroadcastMessageCatcher();
catcher.TickEvent += delegate
{
Log.Debug(TAG, "before listener");
txtNote.Text = "Tick";
Log.Debug(TAG, "after listener");
};
}
protected override void OnResume()
{
base.OnResume();
// RegisterReceiver (catcher, new IntentFilter (Intent.ActionTimeTick));
IntentFilter filter = new IntentFilter(BroadcastMessageCatcher.GRID_STARTED);
RegisterReceiver(catcher, filter);
}
protected override void OnPause()
{
base.OnPause();
UnregisterReceiver(catcher);
}
private void BroadcastStarted()
{
// Broadcast message to the view
// Source: https://forums.xamarin.com/discussion/1147/updating-activity-using-a-background-service
Intent BroadcastIntent = new Intent(this, typeof(BroadcastMessageCatcher));
BroadcastIntent.SetAction(BroadcastMessageCatcher.GRID_STARTED);
//BroadcastIntent.AddCategory(Intent.CategoryDefault);
Log.Debug(TAG, "Broadcast started");
SendBroadcast(BroadcastIntent);
}
}
[BroadcastReceiver]
public class BroadcastMessageCatcher : BroadcastReceiver
{
static readonly string TAG = "MainActivity";
public static readonly string GRID_STARTED = "GRID_STARTED";
public override void OnReceive(Context context, Intent intent)
{
// if (intent.Action == Intent.ActionTimeTick)
if (intent.Action == GRID_STARTED)
{
Log.Debug(TAG, "before event");
// Here I get the error:
TickEvent();
Log.Debug(TAG, "after event");
}
}
public delegate void TickEventHandler();
public event TickEventHandler TickEvent;
}
}
[我正在获取'System.NullReferenceException:'对象引用未设置为对象的实例。” TickEvent();
内部BroadcastMessageCatcher
上的错误(在注释中标记。)>
我正在尝试在BroadcastReceiver收到自定义消息时启动TickEvent。例如,当intent.Action == Intent.ActionTimeTick时(而不是GRID_STARTED),它可以正常工作。我注释掉了...
我理解操作有误。主要是因为我不知道发起活动的意图和发起行动的意图是完全不同的两件事。