android - Xamarin Android 我需要在应用程序关闭时终止前台服务和通知
问题描述
让我解释一下这个场景。
我有一个任务需要每 10 分钟安排一次。
此任务需要网络和磁盘资源,即使应用程序在后台并且即使省电模式已启动。
我尝试了 AlarmManager、JobScheduler 和 ForegroundService。
然后只有一个在省电模式启动时似乎起作用的是 ForegroundService。
在 xamarin 中,我在 MainActivity.cs 中启动了一个前台服务,如下所示。
void StartSomeService()
{
var intent = new Intent(this, typeof(SomeService));
StartForegroundService(intent);
}
在我的“前台”服务中,我有一个在 android 中显示的通知。
当用户将应用程序从屏幕上滑出或点击“X”关闭应用程序时,我需要终止前台服务。
这部分确实会终止/关闭通知,但感觉不对,因为我再次调用 StartService 只是为了终止服务。
测试服务
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if ("stop_service" == intent.Action)
{
StopForeground(true);
StopSelf();
}
else
{
_cts = new CancellationTokenSource();
RegisterForegroundService();
Task.Factory.StartNew(async () =>
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(30));
// DO SOME WORK
}
});
}
return StartCommandResult.Sticky;
}
主要活动
protected override void OnDestroy()
{
var intent = new Intent(this, typeof(TestService));
intent.SetAction("stop_service");
StartService(intent);
base.OnDestroy();
}
解决方案
要停止我通常使用的前台服务:
var intent = new Intent(this, typeof(ForegroundService));
StopService(intent);
这将反过来OnDestroy()
在前台服务内部触发。
然后我OnDestroy()
做:
if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
{
StopForeground(StopForegroundFlags.Remove);
}
else
{
StopForeground(true);
}
StopSelf();
否则,我会看到服务重新启动而没有自行停止的奇怪事情。
推荐阅读
- node.js - 当我尝试从“sequelize-typescript”导入 Sequelize 时出现 TypeError
- node.js - 当错误与,req,res和next一起传递时,Express js中间件不起作用
- python - 在单独的图形上绘制 matplotlib 直方图图例
- shadow-dom - shadow dom 内文档变量的值
- python - 如何使用类似 pandas 的界面执行数据库内分析?
- delphi - Rtti:在类中调用方法时获取“无效的类类型转换”
- c# - 如何转换嵌套的泛型类型?
- nginx - NGINX 动态定位 | 别名
- node.js - Stripe Payment - 网络请求失败
- javascript - setInterval 实现问题