2014-02-24 38 views
1

我的Android應用程序在Foreground服務中啓動並保持TCP連接。該活動使用StartService()來啓動該服務。此外,服務是在它自己的過程中開始的。當屏幕關閉時Android丟棄tcp連接

這裏是服務OnStartCommand

// Code is in C# using Xamarin but regular Java/Android answers are acceptable 
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) 
{ 
    base.OnStartCommand (intent, flags, startId); 

    ... 

    var ongoingNotification = new Notification (Resource.Drawable.icon, "Service running"); 
    var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0); 
    ongoingNotification.SetLatestEventInfo (this, "Service", "The service is running.", pendingIntent); 
    StartForeground ((int)NotificationFlags.ForegroundService, ongoingNotification); 
    return StartCommandResult.RedeliverIntent; 
} 

的連接是正常時,手機屏幕上,不論是否從我的應用程序的活動是開放與否。然而,在關閉屏幕後不到30秒,我總是失去tcp連接。我的應用程序會自動重新連接,以便連接返回,但在屏幕關閉時它會不斷斷開連接。我把它重新打開並且沒問題,即使我的應用中的活動未打開。

它可以連接到Android生命週期,但我只是不知道如何。根據我寫入手機文本文件的調試消息(當連接了來自IDE的調試器時不會發生該問題),該服務似乎按照應有的操作,但連接不穩定。

我也測試了這一點,並且沒有選擇開發者選項中的「不要保留活動」選項。所以它至少不應該與活動生命週期有關。

爲什麼Android會丟棄我的tcp連接,但只有在屏幕關閉的情況下?

+0

你獲得了wifi鎖嗎?或者你在手機上? – 323go

+0

測試在wifi上完成,但應用程序可以使用wifi或移動。我沒有使用wifi鎖(因爲在你提到它之前我沒有意識到它)。在移動設備上進行快速測試後,它看起來像移動設備發生的問題與WiFi一樣。 –

+1

此時您將擁有的選項是獲取WakeLock或定期喚醒您的應用程序(通過AlarmManager),然後獲取WakeLook並進行後臺更新。我會建議後者最大限度地延長電池壽命。你醒來的頻率取決於你的應用需要做多少背景傳輸。理想情況下,您可以讓服務器發送推送通知,並通過輪詢請求響應您的服務。 – 323go

回答

1

我在服務運行期間通過獲取部分WakeLock解決了該問題。

private PowerManager.WakeLock mWakeLock; 

public override void OnCreate() 
{ 
    PowerManager pm = (PowerManager) GetSystemService(Context.PowerService); 
    mWakeLock = pm.NewWakeLock (WakeLockFlags.Partial, "PartialWakeLockTag"); 
    mWakeLock.Acquire(); 
} 

public override void OnDestroy() 
{ 
    mWakeLock.Release(); 
} 

如果我在未來實現更高效的功能,我會更新此答案。