哪种实施方式最好?在用户设置的时间后触发代码的 2 种方法

Which implementation is best? 2 ways to fire code after a user-set amount of time

场景:

用户在 EditText 中输入 45(分钟),然后按下 "OK" 按钮..

45分钟过去后,我想执行一段代码..

我一直在争论两种不同的方法来做到这一点 - 哪种方法最好,为什么?


选项 #1 - AlarmManager -> PendingIntent -> Intent -> BroadcastListener

    int timeValue = Integer.parseInt(editText_timer_value.getText().toString());

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent intent = new Intent(this, TimerReceiver.class);

    PendingIntent pendingIntent = PendingIntent
            .getBroadcast(this.getApplicationContext(), 234324243, intent, 0);

    alarmManager.set(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + (timeValue * 60000), pendingIntent);

    finish();

    // TimerReceiver.class fires when the time is up, and contains additional Code.


(或)

选项 #2 - 意图 -> 意图附加 -> 服务 -> CountDownTimer

    String timeValue = editText_timer_value.getText().toString();

    Intent intent = new Intent(this, TimerService.class);

    intent.putExtra("TIMER_VALUE", timeValue);

    getApplicationContext().startService(intent);

    finish();

    // TimerService.class starts immediately and runs a CountDownTimer from intent Extras



SO,哪个实现是 "better" 或 "correct",为什么?
谢谢! :)

PS.. 也非常欢迎任何其他建议!

报警管理器: 此 class 提供对系统警报服务的访问。这些允许您将您的应用程序安排在将来的某个时间 运行。当警报响起时,系统会广播为其注册的 Intent,如果尚未 运行ning 则自动启动目标应用程序。已注册的闹钟在设备处于睡眠状态时会保留(如果闹钟在此期间关闭,则可以选择唤醒设备),但如果关闭并重新启动,则会被清除。

只要警报接收器的 onReceive() 方法正在执行,警报管理器就会持有 CPU 唤醒锁。这保证 phone 在您处理完广播之前不会休眠。

注意:警报管理器适用于您希望在特定时间获得您的应用程序代码 运行 的情况,即使您的应用程序当前未 运行ning .对于正常的计时操作(滴答、超时等),使用 Handler 更容易、更有效。

https://developer.android.com/reference/android/app/AlarmManager.html

了解更多信息

服务: 服务只是一个组件,即使用户没有与您的应用程序交互,它也可以 运行 在后台运行。因此,您应该仅在需要时才创建服务。

如果您需要在主线程之外执行工作,但仅在用户与您的应用程序交互时执行,那么您可能应该创建一个新线程而不是服务。例如,如果你想播放一些音乐,但只在你的 activity 处于 运行ning 时,你可以在 onCreate() 中创建一个线程,在 onStart() 中启动它 运行ning ,然后在 onStop() 中停止它。还可以考虑使用 AsyncTask 或 HandlerThread,而不是传统的 Thread class。有关线程的更多信息,请参阅进程和线程文档。

https://developer.android.com/guide/components/services.html

了解服务

根据文档,Android 说,你应该使用服务来做很长的 运行ning,任务很重。既然你只想在一段时间内使用计时器,那么为此使用服务完全是无稽之谈和资源浪费。

所以我建议您使用 AlaramManager,正如 android 在文档中所说的那样。