AlarmManger 不断启动和停止,不好的做法吗?

发布于 2024-12-05 04:49:43 字数 729 浏览 0 评论 0原文

我有一个应用程序,它执行一些数据处理,然后在状态栏中通知用户是否发现任何新项目。该进程作为 AlarmManager 在设定的时间运行。一切工作正常,但我理想情况下不希望用户在积极使用应用程序时收到通知,这意味着 AlarmManager 基本上应该被挂起。我能想到的唯一解决方案是在主 Activity 的 onResume 方法中不断启动/停止警报,与此类似:

@Override
public void onResume()
{ 
      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      Intent myIntent = new Intent(this, AlarmReceiver.class);
      PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
      alarmManager.cancel(pendingIntent);
      alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, 600000, pendingIntent);
}

这不是万无一失的,但却是我能想到的最佳解决方案。只是想知道这是否是不好的做法或者是否有更好的解决方案?谢谢。

I have an application that does some data processing, then notifies the user in the status bar if any new items are found. The process runs as an AlarmManager at a set amount of time. Everything works fine, but I'd ideally not like the user to be notified while they are actively using the application, which means the AlarmManager should basically be suspended. The only solution I could think of is constantly start/stop the alarm in the main Activity's onResume method similar to this:

@Override
public void onResume()
{ 
      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      Intent myIntent = new Intent(this, AlarmReceiver.class);
      PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
      alarmManager.cancel(pendingIntent);
      alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 600000, 600000, pendingIntent);
}

This isn't foolproof, but the best solution I could think of. Just wondering if that is bad practice or if there is a better solution? Thanks.

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

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

发布评论

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

评论(1

黎夕旧梦 2024-12-12 04:49:43

只需让您的 AlarmReceiver(或其调用的服务)检查该应用程序是否可见。您需要在您的应用程序和 AlarmReceiver/Service 之间共享一些状态。您可以有一个基本 Activity 来告诉您的 AlarmReceiver/Service 在 onResume 期间位于前台,并且在 onPause 期间位于后台。然后,警报接收器/服务可以在警报响起时简单地检查此状态,并使用它来决定是否应显示通知。

Just have your AlarmReceiver (or the Service it invokes) check to see if the app is visible or not. You need to share some state between your app and the AlarmReceiver/Service. You could have a base Activity that tells your AlarmReceiver/Service that is in the foreground during onResume and that it is in the background during onPause. Then the AlarmReceiver/Service can simply check this state when the alarm goes off and use that to decide if a notification should be shown or not.

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