在Android中的Internet连接上调用自定义代码

发布于 2025-02-13 17:16:51 字数 168 浏览 2 评论 0原文

当我打开互联网并生成通知时,我想从服务器中获取最新更新,但是当该应用程序从最近的项目中关闭/杀死/刷新时,无法保持我的服务活力并聆听网络变更事件,因此我可以ping我的服务器,我不确定如何做以及当我们打开移动互联网时收到新的通知时,诸如whatsapp之类的其他应用程序如何进行。

任何帮助将不胜感激,谢谢。

I want to get latest updates from my server when I turn on the internet and generate a notification, but when the app is closed/killed/swiped from recent items, there is no way to keep my service alive and listening to network change event so that I can ping my server, I'm not sure how to do it and how other apps such as whatsapp does it when we receive new notification the moment we turn on mobile internet.

Any help is appreciated, thanks in advance.

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

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

发布评论

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

评论(1

情丝乱 2025-02-20 17:16:51

弄清楚@gobucsg评论的内容。您有以下选项:

  1. 一直通过前景服务运行您的应用程序,并收听WiFi Connected广播。这是不是一个好的解决方案,并浪费了电池寿命。
  2. 使用 workmanager api 来安排作业。

Workmanager API专门为您指定的目的而开发。 API允许您为工作设置所需的条件,例如网络连接。它还可以通过设备重新启动来安排工作,因此您不必这样做。唯一的缺点是,当代码运行时,您没有对的微调控制,因为工人的目标之一是通过延迟和批处理作业来挽救电池寿命。

编辑:
另一个选择是使用 push nockitionations 。如果您正在开发消息传递应用程序,并且您希望服务器 push 向客户端通知他们的消息,这很有用。但是,如果您需要做的就是每天与服务器建立一次联系,那么您应该使用Workmanager。

Making clear what @GobuCSG commented. You have the following options:

  1. Run your application all the time via a foreground service and listen for wifi connected broadcast. This is not a good solution and wastes battery life.
  2. Schedule jobs using the WorkManager API.

The WorkManager API was developed specifically for the purpose you specified. The API allows you to set required conditions for your job to run, such as network connectivity. It also persists scheduled jobs through device reboots, so you don't have to. The only downside is that you don't have fine tune control of when the code runs, as one of the goals of WorkManager is to save battery life by delaying and batching jobs.

EDIT:
Another option is to use push notifications. This is useful if your are developing a messaging app and you want your server to push a message to the client so they can be notified of a received message. But, if all you need to do is establish contact with your server once a day, then you should use WorkManager.

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