android AlarmManager 详解

      在开发互联网应用时候,我们常常要使用心跳来保证客户端与服务器的连接。怎么完成心跳很关键,在说道客户端心跳功能时,如果使用Timer或者专门开起一个线程来做心跳的工作,会浪费CPU工作时间,而且也会更多的消耗电量。相对来说使用AlarmManager 来处理心跳的话,使用的是系统全局的定时服务,会一定成都减少CPU的消耗,耗电量也会少很多。正好这段时间也要做推送,就顺便学习了一下怎么做心跳。

// 取消已经注册的与参数匹配的闹铃
void   cancel(PendingIntent operation)
  //注册一个新的闹铃
void   set(int type, long triggerAtTime, PendingIntent operation)
  //注册一个重复类型的闹铃
void   setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)
    //设置时区
void   setTimeZone(String timeZone)

public static final int ELAPSED_REALTIME 
//当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是相对时间,是从系统启动后开始计时的,包括睡眠时间,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3    (0x00000003)。


 public static final int ELAPSED_REALTIME_WAKEUP
 //能唤醒系统,用法同ELAPSED_REALTIME,系统值是2 (0x00000002) 。


public static final int RTC  
//当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是绝对时间,所用时间是UTC时间,可以通过调用System.currentTimeMillis()获得。系统值是1 (0x00000001) 。


 public static final int RTC_WAKEUP
 //能唤醒系统,用法同RTC类型,系统值为 0 (0x00000000) 。


 Public static final int POWER_OFF_WAKEUP 
//能唤醒系统,它是一种关机闹铃,就是说设备在关机状态下也可以唤醒系统,所以我们把它称之为关机闹铃。使用方法同RTC类型,系统值为
4(0x00000004)。

AlarmManager处理心跳间隔的相关代码如下:

private AlarmManager mAlermManager;


  final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  final Intent intent = new Intent();
  intent.setAction("Const.ACTION_HEARTBEAT");
  intent.putExtra("message", "心跳");


  final PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  final long time = System.currentTimeMillis();// 设置当前时间
 
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 8000,pendingIntent);// 设定精确重复提醒
//    alarmManager.set(AlarmManager.RTC, time, pendingIntent);// 设置单次闹钟提醒
//    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, time, 8000, pendingIntent);// 设置不精确的重复的提醒
//    alarmManager.cancel(pendingIntent);// 取消闹钟

 定义一个广播接收器,在接收器中处理与服务器的连接等操作:

public class HeartReceiver extends BroadcastReceiver {
        private static final String TAG = "HeartReceiver";
        @Override
        public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.d(TAG, "action" + action);
                if (Const.ACTION_START_HEART.equals(action)) {
                        Log.d(TAG, "Start heart");
                } else if (Const.ACTION_HEARTBEAT.equals(action)) {
                        Log.d(TAG, "Heartbeat");
                        //在此完成心跳需要完成的工作,比如请求远程服务器……
                } else if (Const.ACTION_STOP_HEART.equals(action)) {
                        Log.d(TAG, "Stop heart");
                }
        }
}

原文地址:https://www.cnblogs.com/zhongle/p/3478898.html