在活动停止服务

编程入门 行业动态 更新时间:2024-10-19 03:32:47
本文介绍了在活动停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我用下面的code停止我的服务

I'm using following code to stop my service

Intent intent = new Intent(MainActivity.this, UsageRecorderService.class); stopService(intent);

这是我的服务,它的工作原理无限期

And this is my service that works indefinitely

public class UsageRecorderService extends IntentService { public UsageRecorderService() { super("UsageRecorder"); } @Override protected void onHandleIntent(Intent intent) { while (true) { UsageRecorder.recordUsages(this, false); SystemClock.sleep(10000); } } }

为什么不停止我的服务?

Why does not stop my service?

推荐答案

这code将工作

public class UsageRecorderService extends IntentService { private boolean mStop = false; public UsageRecorderService() { super("UsageRecorder"); } public final Object sLock = new Object(); public void onDestroy() { synchronized (sLock) { mStop = true; } } @Override protected void onHandleIntent(Intent intent) { while (true) { synchronized (sLock) { if (mStop) break; } UsageRecorder.recordUsages(this, false); SystemClock.sleep(10000); } } }

您可以使用 stopService

Intent intent = new Intent(MainActivity.this, UsageRecorderService.class); stopService(intent);

此外,我建议阅读服务指南明白是怎么回事那里。

Also I recommend to read Services guide to understand what is going there.

更多推荐

在活动停止服务

本文发布于:2023-11-27 04:00:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636492.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!