繁体   English   中英

哪个实施最佳? 在用户设置的时间后触发代码的两种方法

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

场景:

用户在EditText中输入45(分钟),然后按“确定”按钮。

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 ,哪个实现“更好”或“正确”, 为什么?
谢谢! :)

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

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

只要警报接收器的onReceive()方法正在执行,警报管理器就会保持CPU唤醒锁。 这样可以确保手机在完成广播处理之前不会进入睡眠状态。

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

https://developer.android.com/reference/android/app/AlarmManager.html上了解更多

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

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

通过https://developer.android.com/guide/components/services.html了解有关服务的信息

根据文档,Android表示,您应该使用服务来执行长期运行的繁重任务。 由于您只想在某个时间段内使用计时器,因此为此使用服务完全是胡说八道,浪费资源。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM