Api demo源码学习(16)App/Activity/Alarm Alarm Controller&&Alarm Service

本节的两个小应用Alarm Controller 和Alarm Service都是定时启动服务的功能。代码比较容易理解,就不一一粘贴了。分点讲一下涉及到的知识点。

1.Pendingintent类是对intent的一个包装,可以用来延时处理intent要做的操作。主要和Android特定的的远程服务打交道(短信、通知、闹铃等),通常的应用无需使用。Pendingintent不是直接new出来的,而是通过Pendingintent.getBroadcast() ,PendingIntent.getActivity()以及PendingIntent.getService()的方式获取实例。

2.Alarm Controller采用的是定时启动广播的方式,按照代码中的注释,这类方式比较适合延时时间较短的一些操作。比如弹出Notification等。代码片段如下:
 1             Intent intent = new Intent(AlarmController.this, OneShotAlarm.class);
2 PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this, 0, intent, 0);
3 PendingIntent.getService(context, requestCode, intent, flags)
4 // We want the alarm to go off 30 seconds from now.
5 Calendar calendar = Calendar.getInstance();
6 calendar.setTimeInMillis(System.currentTimeMillis());
7 calendar.add(Calendar.SECOND, 30);
8
9 // Schedule the alarm!
10 AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
11 am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
Alarm Service 采用的是启动服务的方式,比较适合于延长时间较长的一类操作。比如定时启动下载服务进行更新等。代码片段如下:
1 // We want the alarm to go off 30 seconds from now.
2 long firstTime = SystemClock.elapsedRealtime();
3
4 // Schedule the alarm!
5 AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
6 am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000, mAlarmSender);

3.注销定时操作,调用的函数是:
1 AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
2 am.cancel(sender);//sender即之前得到的PendingIntent
4.Google的代码习惯值得学习,比如在弹出Toast提示时,用到了如下代码段,值得学习:
1// Tell the user about what we did.       
2 if (mToast != null) {
3 mToast.cancel();
4 }
5 mToast = Toast.makeText(AlarmController.this, R.string.repeating_scheduled,Toast.LENGTH_LONG);
6 mToast.show();

最后,需要在AndroidManifest.xml中注册BroadcastResolver 和Service。








原文地址:https://www.cnblogs.com/xutao1988/p/2350302.html