我希望在手机锁屏的情况下也能接收Wi-Fi数据包,但是问题在于当我锁定屏幕后,我的前台服务就停止接收数据包了。我是这样使用前台服务的:
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
var notification = new Notification.Builder(this)
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(Resources.GetString(Resource.String.notification_text))
.SetSmallIcon(Resource.Drawable.ic_stat_name)
.SetContentIntent(BuildIntentToShowMainActivity())
.SetOngoing(true)
.AddAction(BuildRestartTimerAction())
.AddAction(BuildStopServiceAction())
.Build();
// Enlist this instance of the service as a foreground service
StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification);
/*DO THIS EVEN WHEN SCREEN IS LOCKED*/
var powerManager = (PowerManager)GetSystemService(PowerService);
_wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "WakeLockTag");
_wakeLock.Acquire();
var wifiManager = (WifiManager)GetSystemService(WifiService);
_wifiLock = wifiManager.CreateWifiLock(WifiMode.FullHighPerf, "xamarin_wifi_lock");
_wifiLock.Acquire();
if (!powerManager.IsIgnoringBatteryOptimizations("com.xamarin.xample.foregroundservicedemo") ||
!_wakeLock.IsHeld || !_wifiLock.IsHeld)
throw new InvalidOperationException("OPTIMIZATIONS NOT ACTIVE");
string msg = timestamper.GetFormattedTimestamp();
Log.Debug(TAG, msg);
Intent intent = new Intent(Constants.NOTIFICATION_BROADCAST_ACTION);
intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings);
intent.PutExtra(Constants.BROADCAST_MESSAGE_KEY, msg);
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
Task.Run(() =>
{
using (var client = new UdpClient(12345))
{
while (true)
{
var result = client.ReceiveAsync().Result;
Console.WriteLine($"RECEIVED: {result.Buffer.Length}");
}
}
});
return StartCommandResult.Sticky;
}
我正在做以下几件事情来确保它不会被杀掉:
- 启动前台服务
- 使用
StartCommandResult.Sticky
- 使用唤醒锁(Wake Lock)
- 使用WiFi锁
- 将WiFi睡眠策略设置为
Never
(我在手机设置中进行了设置) - 在意图中设置
ActionIgnoreBatteryOptimizationSettings
- 在调试时通过adb命令提示符将我的应用程序加入白名单
还有其他什么我需要注意的吗?我正在使用Android 6.0 - API 23的三星A5。
我查看了来自adb命令提示符的日志,并检查了我的服务是否实际上作为前台服务运行,并且所有锁都已保持。
powerManager.IsIgnoringBatteryOptimizations
。 - FCin