package com.imofan.android.basic;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

/**
 * 魔方发送事件定时器
 * @author liyang
 *
 */
public class MofangAlarm{
    //PUBLISH CHECK
    private static final long intervalAlarmTime = 240000;//定时器，4分钟
//    private static final long intervalAlarmTime = 60000;//定时器，测试60秒
    
    private static PendingIntent pendingIntent = null;
    
    /**
     * 开启定时魔方发送数据定时器
     * @param context
     */
    public static void startMofangAlarm(Context context){
    	if(null!=context){
    		String devId = Mofang.getDevId(context);
    		if(null!=devId && !"".equals(devId)){
    			AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    			Intent intent = new Intent(context,MofangReceiver.class);  
    			if(null!=pendingIntent){ 
    				//取消前面之前已经过时的 定时器
    				alarmManager.cancel(pendingIntent);
    			}
    			pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    			//设置新的定时器：类型，开始时间，间隔时间，定时触发的intent
    			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), intervalAlarmTime, pendingIntent);
    		}
    	}
    }
    
    /**
     * 停止定时推送服务
     * @param context
     */
    public static void stopMofangAlarm(Context context){
        AlarmManager alarmManager = (AlarmManager) context.getSystemService("alarm");
        if(null!=pendingIntent){
            alarmManager.cancel(pendingIntent);
            pendingIntent= null;
        }
    }
}
