Android:通过小部件管理服务

发布于 2024-11-23 16:10:58 字数 569 浏览 0 评论 0原文

我确信这是一个简单的答案,但这让我发疯,我希望有人能让我摆脱痛苦。

我有一个 Android 活动、小部件和服务。该服务在后台运行声音,可以运行一段设定的时间,也可以连续运行。因为我希望声音一直运行直到停止,所以我在服务中没有 stopSelf() 方法。这对于活动来说一切都很好,因为我让它在播放时启动服务,在停止时停止服务。现在我想在这个最新的更新中添加一个小部件。所以这就是我被困住的地方。因为它是一个广播接收器,所以它的功能非常有限。我可以调用 context.stopService,但我只想在按下按钮时停止服务。我只能找到一种方法来设置带有pendingIntent的onClickListener。

在我的服务的 onStartCommand() 方法中,我从传入意图中读取了额外的“循环”。所以我尝试只传递零值,但由于某种原因它似乎没有读取它。我知道 onStartCommand() 正在服务中被调用,因为音乐正在播放,但无论我在意图上添加什么额外内容,它似乎都没有读取它,我不知道为什么。所以我的问题是,从小部件的按钮停止服务的最佳策略是什么?我希望这是一个简单的答案,否则我想我可以创建一个新的活动或广播接收器来处理按钮单击,但这似乎没有必要。任何建议将非常感激!谢谢!

I'm sure this is an easy answer, but it's driving me crazy and I'm hoping someone can just put me out of my misery.

I have an android activity, widget and service. The service runs sound in the background, either for a set amount of time or continuously. Because I want the sound to run until stop is hit, I don't have a stopSelf() method in the service. This was all fine and dandy with the activity because I had it startService on play, and stopService on stop. Now I want to throw a widget in this latest update. So here's where I'm stuck. Because it's a broadcast receiver, I'm very limited in what it can do. I can call context.stopService, but I only want to stop the service when the button is pressed. I can only find a way to set an onClickListener with a pendingIntent.

In my service's onStartCommand() method, I read the "loops" extra from the incoming intent. So I tried just passing in a value of zero, but for some reason it doesn't seem to read it. I know the onStartCommand() is being called in the service because the music is playing, but regardless of what extra I throw on the intent, it doesn't seem to read it and I have no idea why. So my question is, what is the best strategy to use to stop a service from a widget's button? I'm hoping it's an easy answer, otherwise I guess I could create a new activity or broadcast receiver to handle the button click, but that seems so unnecessary. Any advice would be very much appreciated! Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

超可爱的懒熊 2024-11-30 16:10:58

您传递给 Widget 中按钮的 PendingIntent 应该能够像任何其他 Intent 一样将 Intent 额外信息发送到服务:您应该能够在 onStartCommand 中检测到该 Intent 并然后告诉服务停止声音并自行停止。如果没有一些代码,很难判断您可能还做错了什么。

The PendingIntent you pass to the button in the Widget should be able to send Intent extras to the service like any other Intent: you should be able to detect that Intent in onStartCommand and then tell the Service to stop the sound and stop itself. Hard to tell what else you might be doing wrong without some code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文