我正在Xamarin中製作Android應用程序。該應用程序具有在後臺運行的TCP偵聽器。因此,當應用程序未打開時,此偵聽程序仍處於活動狀態,我已將它移動到作爲服務運行。不幸的是,當開始時UI變得沒有響應,並且崩潰而沒有在調試器中拋出任何錯誤。C#Android服務崩潰沒有錯誤
從一個活動一個新的線程啓動服務:
btnStart.Click += (object sender, EventArgs e) =>
{
Thread listener = new Thread (() =>
{
StartService(new Intent(this, typeof(MyService)));
});
listener.Start();
};
這裏是從服務代碼:
public override void OnStart(Android.Content.Intent intent, int startId)
{
base.OnStart (intent, startId);
Log.Debug ("Service Class", "Service has started");
DoActions();
}
public void DoActions()
{
Log.Debug("Service Class", "getting local IP!");
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
int port = 1111;
IPAddress localaddr = IPAddress.Parse (localIP);
TcpListener tcpListener = new TcpListener (localaddr, port);
Log.Debug ("Service Class", "accepted local IP, starting listener");
tcpListener.Start();
Log.Debug ("Service Class", "You are now listening on " + localaddr + port);
while (true)
{
Socket socket = tcpListener.AcceptSocket();
byte[] array = new byte[1024];
socket.Receive (array);
string @string = Encoding.UTF8.GetString (array);
Log.Debug ("Service Class", "Message Received From Server:" + (@string.Replace ("\0", string.Empty)));
}
}
我起牀到「你現在監聽」 + localaddr + port「調試信息,在這種情況下,它是192.168.0.105端口1111.我有一個計時器寫入調試x秒,在應用程序崩潰之前我會得到一些響應。用於將其作爲來自同一活動的任務運行。
有沒有一種方法可以將更多信息發送給調試器,以查明哪裏出了問題? 我在4.2.2上使用Tronsmart mk908b進行測試
在此先感謝!
更新: 看來這可能與Android服務生命週期有關。仍在尋找解決這個問題的方法。
請發佈您的logcat。 – BeingMIAkashs
http://pastebin.com/di7V7AMM – user1672867
信息(364)/ InputDispatcher:應用程序沒有響應:窗口{413e3dd0 u0 SecureX2.SecureX2/securex2.ListenActivity}。事件發生後5002.8ms,等待開始後5002.3ms。原因:正在等待,因爲所觸摸的窗口尚未處理之前傳送給它的輸入事件。 – user1672867