如何使用PendingIntent 管理定时器?

       南昌APP开发公司的安卓开发人员都知道,一个PendingIntent只能登记一个定时器。这也是isOn值为false时,setServiceAlarm (Context, boolean)方法的工作原理:首先调用AlarmManager.cancel(PendingIntent)方法撤销PendingIntent的定时器,然后撤销PendingIntent。

       既然撤销定时器也随即撤消了PendingIntent,可通过检查PendingIntent是否存在来确认定时器激活与否。具体代码实现时, 传入PendingIntent.FLAG_NO_CREATE 标志给PendingIntent.getService(...)方法即可。该标志表示如果PendingIntent不存在,则返回

null,而不是创建它。

       添加一个名为isServiceAlarmOn(Context)的新方法,并传入PendingIntent.FLAG_NO_

CREATE标志,以判断定时器的启停状态,如下代码所示:

       添加isServiceAlarmOn()方法(PollService.java)

       public class PollService extends IntentService {

       ...

       public static void setServiceAlarm(Context context, boolean isOn) {

       ...

       }

       public static boolean isServiceAlarmOn(Context context) {

       Intent i = PollService.newIntent(context);

       PendingIntent pi = PendingIntent

       .getService(context, 0, i, PendingIntent.FLAG_NO_CREATE);

       return pi != null;

       }

       ...

       }

       这里的PendingIntent仅用于设置定时器,因此PendingIntent空值表示定时器还未设置。

       以上就是易速网络今天所要讲的使用PendingIntent 管理定时器的方法,在南昌APP开发中,还会有更多的方法或碰到一些难题,易速网络拥有专业的安卓开发大师,具备五年以上的开发经验,精通安卓、苹果双端,不管哪种难题都能为您轻松解决,如有需要APP开发服务的朋友,随时欢迎咨询易速网络,我们专业为您定制开发!

提供全面的搜索引擎优化学习交流,专注网站优化和搜索引擎营销推广服务。用专业的SEO技术为企业网站提升关键词排名,让你的网站不仅满足用户体验还要适合搜索引擎优化规则。
易速网站优化公司 » 如何使用PendingIntent 管理定时器?
享更多特权,立即登录下载海量资源
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡