我有一个非常基本的android应用程序。大多数仍然来自模板。我为XMPP客户端使用了自己的类库。现在发生的事情是,如果我声明一个全局TextView用于事件或其他方法(OnCreate,OnResume等),则事件似乎不会引发。 自从我在不同环境下对其进行测试以来,我的库绝对不是原因。
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
public XMPPClient client;
TextView consoleText;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
fab.Click += FabOnClick;
//consoleText = FindViewById<TextView>(Resource.Id.consoleText);
client = new XMPPClient("10.0.2.2", 5222, "chris3", "Define")
{
AuthenticationInfo = true
};
client.OnPublishEvent += Client_OnPublishEvent;
client.OnConnection += Client_OnConnection;
client.OnMessageReceived += Client_OnMessageReceived;
}
private void Client_OnMessageReceived(object sender, MessageEventArgs e)
{
//consoleText.Text += "\nMessage: " + e.text + " from " + e.from;
Log.Debug("mytag", "Message!");
}
private void Client_OnPublishEvent(object sender, SubscriptionEventArgs e)
{
//consoleText.Text += "\nPublication: " + e.title + " with content " + e.content + " at " + e.published;
Log.Debug("mytag", "Publication");
}
private void Client_OnConnection(object sender, ConnectionEventArgs e)
{
//consoleText.Text += "\nConnection status changed: " + e.Status;
Log.Debug("mytag", "ConnectionChange");
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.menu_main, menu);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
int id = item.ItemId;
if (id == Resource.Id.action_subscribe)
{
client.Subscribe("Node1");
Log.Debug("mytag", "Subscribed");
return true;
}
return base.OnOptionsItemSelected(item);
}
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
client.Connect();
}
}
当出现TextView consoleText对象时,开始时以及关闭客户端时都会触发我的OnConnection事件。 但是,如果不存在,则每个事件都可以正常运行。 现在,因为我是Xamarin的初学者,所以我对问题的根源非常感兴趣。
答案 0 :(得分:1)
您可能需要使用主调度程序(UI线程)包装要处理的文本分配。
例如,它看起来像这样。
private void Client_OnMessageReceived(object sender, MessageEventArgs e)
{
Activity.RunOnUiThread(() => {
consoleText.Text += "\nMessage: " + e.text + " from " + e.from;
});
Log.Debug("mytag", "Message!");
}
尝试一下,让我知道它是否仍然出错,不要忘记,您需要将所有consoleText.Text
分配都包装在其中。
Activity.RunOnUiThread(() => {
});
// You might not need the Activity part, I can't remember exactly which
// one it is for an AppCompatActivity.
RunOnUiThread(() => {
});