如何在Android中每分钟高效地更新通知功率以显示小时和分钟的时间?

问题描述 投票:0回答:1

我有一个日历应用程序,即使应用程序关闭或在后台,也需要在一个国家(即印度)的通知栏中显示当前日期和时间以及事件(节假日)。我制作了定制的通知栏并使用远程视图实现。我使用广播接收器和前台服务来实现这些功能。但我的问题太多了。

  1. 通知在一两天内随机消失。
  2. android.app.RemoteServiceException 崩溃
  3. android.app.ForegroundServiceStartNotAllowedException
  4. Context.startForegroundService() 然后没有调用 Service.startForeground()

等等。 Android 引入了工作管理器等新功能,而不是使用前台服务,但它们不允许每分钟更新一次。但我需要显示小时和分钟并每分钟更新一次。截至 2023 年底,我应该使用哪些技术(Alarm Manager、Broadcast Receiver、BOOT_COMPLETED、ACTION_TICK、DATE_CHANGED、WorkManager、Handler、Timer 等)来使应用程序不会出现 ANR 且不会崩溃。我附上了图片以便更好地理解。请帮忙。

java android service notifications alarmmanager
1个回答
0
投票

为 Android 中的日历应用程序设计稳定可靠的后台服务涉及不同组件和考虑因素的组合。下面,我将提供使用上述一些技术的推荐方法。请注意,最佳实践和库可能会在 2023 年 12 月之后发展,因此如果您希望实现 Android 日历应用程序,您应该检查最新的 Android 文档以了解未来的任何更新。

  1. 前台服务:

使用前台服务来确保您的应用程序具有更高的优先级并且不太可能被系统杀死。

// Inside your service class
startForeground(NOTIFICATION_ID, createNotification());
  1. 工作意向服务:

使用JobIntentService进行后台处理。与传统的 IntentService 相比,这是一种更现代、更值得推荐的方法。

public class MyJobIntentService extends JobIntentService {
    // Implementation
}

在您的 AndroidManifest.xml 中:

<service
    android:name=".MyJobIntentService"
    android:permission="android.permission.BIND_JOB_SERVICE"
    android:exported="false"/>
  1. 报警管理器:

使用 AlarmManager 安排定期更新。对于频繁的更新,您可能需要考虑更灵活的调度机制。

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

alarmManager.setRepeating(
    AlarmManager.RTC_WAKEUP,
    System.currentTimeMillis(),
    AlarmManager.INTERVAL_MINUTE,
    pendingIntent
);
  1. 广播接收器:

使用广播接收器接收警报并触发更新。确保在您的代码中动态注册它。

public class MyReceiver extends BroadcastReceiver {
    // Implementation
}

在您的 AndroidManifest.xml 中:

<receiver android:name=".MyReceiver"/>
  1. 作业调度器:

对于更复杂的调度,您可能需要研究 JobScheduler,它可以更有效地处理后台任务。

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(this, MyJobService.class);

JobInfo jobInfo = new JobInfo.Builder(JOB_ID, componentName)
    .setPeriodic(AlarmManager.INTERVAL_MINUTE)
    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
    .build();

jobScheduler.schedule(jobInfo);
  1. 通知处理:

谨慎处理通知。确保您正确更新它们,尤其是当应用程序位于后台时。

// Use NotificationManager to update your notification
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.notify(NOTIFICATION_ID, createNotification());

请记住,每个应用程序及其要求都是独特的,最佳方法可能取决于应用程序的具体细节。始终彻底测试并根据您的发现调整您的实施。考虑使用现代 Android 架构组件和库来使您的代码更加模块化和可维护。

© www.soinside.com 2019 - 2024. All rights reserved.