Iva*_*rlg 1 android signalr xamarin signalr-hub xamarin.forms
I am making an application in Xamarin Forms that uses the Signalr service to implement a chat. The chat works perfectly in the UWP version and in the Android emulator, so it does when I am debugging on my phone (Android), but when I disconnect the phone from the PC the chaos begins. The problem is that I think that when the application goes to the background, it disconnects from the Signalr server.
我尝试过自动重新连接,甚至更改 ServerTimeout 和 KeepAliveInterval 的时间。但我没有成功。应该注意的是,我住的地方还有主要的连接问题,但我的理论仍然是应用程序进入后台时。
这是我初始化服务的代码(我使用的是单例服务)。
hubConnection = new HubConnectionBuilder()
.WithUrl(URL, options =>
{
options.AccessTokenProvider = () => Task.FromResult(_myAccessToken);
})
.WithAutomaticReconnect()
//.WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(10) })
//.WithAutomaticReconnect(new RandomRetryPolicy())
.Build();
Run Code Online (Sandbox Code Playgroud)
这是我在连接关闭时连接的代码
hubConnection.Closed += async (error) =>
{
OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...",
string.Empty));
IsConnected = false;
await Task.Delay(new Random().Next(0, 5) * 1000);
try { await ReConnectAsync(); } catch (Exception ex) { Debug.WriteLine(ex); }
};
Run Code Online (Sandbox Code Playgroud)
这是我的连接代码
public async Task ReConnectAsync()
{
await ConnectAsync();
}
public async Task ConnectAsync()
{
if (IsConnected)
{
return;
}
Debug.WriteLine(hubConnection.State);
if (hubConnection.State== HubConnectionState.Disconnected)
{
await hubConnection.StartAsync();
//CancellationToken cancellationToken = new CancellationToken();
//await ConnectWithRetryAsync(hubConnection, cancellationToken);
}
IsConnected = true;
}
Run Code Online (Sandbox Code Playgroud)
我还能尝试什么来防止它在 Android 上断开连接,或者我的代码会做错什么?
除非您有前台服务在运行,否则您将无法在 Android 上保持 SignalR 连接处于活动状态,这实质上使应用程序保持活动状态。这就是音乐应用程序等可以在后台保持运行的方式。
前台服务还需要向用户显示它正在运行的通知。
Xamarin 提供了一个很好的小示例,展示了如何在此处创建前台服务https://github.com/xamarin/monodroid-samples/tree/master/ApplicationFundamentals/ServiceSamples/ForegroundServiceDemo
本质上,您创建了一个服务:
[Service]
public class MyForegroundService : Service
{
}
Run Code Online (Sandbox Code Playgroud)
然后你从你的 Activity 开始它有一个 Intent:
var intent = new Intent(this, typeof(MyForegroundService));
StartForegroundService(intent);
Run Code Online (Sandbox Code Playgroud)
在你的服务,你需要调用StartForeground一个OnStartCommand重写,否则服务将只被打死。
问题是。您真的需要前台服务并在后台继续运行 SignalR 吗?
您是否考虑过偶尔轮询后端以获取最新消息?
你有没有想过当用户收到新消息时发送推送通知?
如果您也决定以 iOS 为目标,则会遇到更大的限制。在那里,您将无法保持 SignalR 连接处于活动状态。
| 归档时间: |
|
| 查看次数: |
1720 次 |
| 最近记录: |