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

vybvopom  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(145)

我有一个日历应用程序,需要显示当前日期和时间和事件(假期)在一个国家的通知栏(即印度),即使应用程序关闭或在后台.我做了自定义的通知栏,并使用远程视图实现.我使用广播接收器和前台服务来实现这些功能.但我得到了太多的问题.
1.通知在一两天内随机消失。

  1. android.app.RemoteServiceException crash
  2. android.app.ForegroundServiceStartNotAllowedException
  3. Context.startForegroundService()随后未调用Service.startForeground()
    等. Android引入了新功能,如工作管理器,而不是使用前台服务,但他们不允许每分钟更新.但我需要显示小时和分钟,每分钟更新它.截至2023年底,哪些技术(报警管理器,广播接收器, Boot _COMPLETED,ACTION_TICK,DATE_CHANGED,WorkManager,计时器等)我应该使用,使应用程序ANR和崩溃免费。我有更好的理解附加图像。请帮助。
shyt4zoc

shyt4zoc1#

在Android中为日历应用设计稳定可靠的后台服务涉及到不同组件和注意事项的组合。下面,我将提供一种使用上述一些技术的推荐方法。请注意,最佳实践和库可能会在2023年12月之后发展,所以你应该检查最新的Android文档在未来的任何更新,如果你想实现Android日历应用程序.
1.前台服务:
使用前台服务来确保您的应用具有更高的优先级,并且不太可能被系统杀死。

  1. // Inside your service class
  2. startForeground(NOTIFICATION_ID, createNotification());

字符串

  1. JobIntentService:
    使用JobIntentService进行后台处理。与传统的IntentService相比,这是一种更现代和推荐的方法。
  1. public class MyJobIntentService extends JobIntentService {
  2. // Implementation
  3. }


在AndroidManifest.xml中:

  1. <service
  2. android:name=".MyJobIntentService"
  3. android:permission="android.permission.BIND_JOB_SERVICE"
  4. android:exported="false"/>


1.报警管理器:
使用AlarmManager计划定期更新。对于频繁更新,您可能需要考虑更灵活的计划机制。

  1. AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  2. Intent intent = new Intent(this, MyReceiver.class);
  3. PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
  4. alarmManager.setRepeating(
  5. AlarmManager.RTC_WAKEUP,
  6. System.currentTimeMillis(),
  7. AlarmManager.INTERVAL_MINUTE,
  8. pendingIntent
  9. );

  1. BroadcastReceiver:
    使用BroadcastReceiver接收警报和触发更新。确保在代码中动态注册它。
  1. public class MyReceiver extends BroadcastReceiver {
  2. // Implementation
  3. }


在AndroidManifest.xml中:

  1. <receiver android:name=".MyReceiver"/>


1.职位:
对于更复杂的调度,您可能希望研究Jobblog,它可以更有效地处理后台任务。

  1. JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
  2. ComponentName componentName = new ComponentName(this, MyJobService.class);
  3. JobInfo jobInfo = new JobInfo.Builder(JOB_ID, componentName)
  4. .setPeriodic(AlarmManager.INTERVAL_MINUTE)
  5. .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
  6. .build();
  7. jobScheduler.schedule(jobInfo);


1.通知处理:
小心处理通知。确保您正确更新通知,尤其是在应用处于后台时。

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


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

展开查看全部

相关问题