2017-02-15 35 views
0

當我在使用System.Timers.ElapsedEventHandler(checkForMessage)時調用Print函數時,我的應用崩潰。c#Android Xamarin - 與ElapsedEventHandler一起使用TextView.Text時崩潰

我在其他上下文中調用了Print函數,並沒有問題。

using System; 
using Android.App; 
using Android.Widget; 
using Android.OS; 

namespace Ev3BtCom 
{ 
    [Activity(Label = "Ev3BtCom", MainLauncher = true, Icon = "@drawable/icon")] 
    public class MainActivity : Activity 
    { 
     Ev3Messaging _ev3Messaging = new Ev3Messaging(); 

     bool isParsing = true; 
     TextView infosLabel; 

     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 

      SetContentView (Resource.Layout.Main); 

      ... 
      infosLabel = FindViewById<TextView>(Resource.Id.Infos); 

      _ev3Messaging = new Ev3Messaging(); 


      System.Timers.Timer checkForTime = new System.Timers.Timer(500); 
      checkForTime.Elapsed += new System.Timers.ElapsedEventHandler(checkForMessage); 
      checkForTime.Enabled = true; 



      connectBut.Click += async (object sender, EventArgs e) => 
      { 
       bool error = false; 
       try 
       { 
        await _ev3Messaging.Connect(brickNameET.Text); 
       } 
       catch (Exception ex) 
       { 
        Print(ex.Message); 
        error = true; 
       } 
       if(!error) 
       { 
        Print("Connected"); 
        isParsing = false; 
       } 
      }; 

      ...//Many use of the print function in the same context WITHOUT CRASH 
     } 

     async void checkForMessage(object source, System.Timers.ElapsedEventArgs e) 
     { 
      if (!isParsing) 
      { 
       isParsing = true; 
       byte[] datas = new byte[0]; 
       try 
       { 
        datas = await _ev3Messaging.ReceiveText(); 
       }catch (Exception ex) 
       { 
        await _ev3Messaging.SendText("Text", ex.Message); 
        Print(ex.Message); // MAKES APP CRASH 
       } 
       if (datas.Length != 0) 
       { 
        string printedText = "Received: "; 
        foreach (byte b in datas) 
         printedText += (int)b + ","; 
        Print(printedText); // MAKES APP CRASH 
        await _ev3Messaging.SendText("Text", printedText); 
       } 
       Print("Test"); // MAKES APP CRASH 
       isParsing = false; 
      } 
     } 

     void Print(string text) 
     { 
      infosLabel.Text += text + "\n"; // When I remove this line, there is no more crash 
     } 
    } 
} 
+0

什麼是Exception/StackTrace? – SushiHangover

+0

沒有顯示異常,應用程序關閉時沒有任何消息...對不起,我是初學者,我不知道「StackTrace」是什麼意思... –

+0

你可以在你的' adb logcat'。 –

回答

0

Timer.Elapsed事件總是排隊在一個線程池線程執行,所以你需要確保你更新UI線程的UI控件。爲了達到這個目的,你可以使用RunOnUiThread方法,如下所示:

void Print(string text) 
{ 
    RunOnUiThread(() => infosLabel.Text += text + "\n"); 
} 
+0

非常感謝!有效 !我正在學習編程Xamarin,我從來沒有聽說過RunOnUiThread ... –

+0

很高興聽到這個消息。你可能會遇到很多這樣的未知問題,但不要放棄。總有一個明智的解釋,爲什麼有些東西不能正常工作。 – hankide

相關問題