嗨我正在使用报警管理器3分钟的特定时间间隔,我开始监控.它有时工作,突然我注意到有不规则的时间间隔,这是不正确的!你可以在附件日志中看到"20-Jul-2016 12:22:03 pm"时间变化!我连接了手机并关闭了屏幕并进行了监控!每3分钟,我点击服务器并获得响应为1.但是,有一次,它需要5分钟才能到达服务器!这个奇怪的问题为何发生?
这是代码.
public void startAt3() { Intent alarmIntent = new Intent(ActivityTracking.this, AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(ActivityTracking.this, 0, alarmIntent, 0); AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); /* Set the alarm */ Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); /* Repeating on every 3 minute interval */ manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 180000L, pendingIntent); String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()); Log.e("alarm",mydate); }
AlarmReceiver:
public class AlarmReceiver extends WakefulBroadcastReceiver {//AlarmReceiver class @Override public void onReceive(Context context, Intent intent) {//onReceive method String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()); Log.e("alarm",mydate); Intent service = new Intent(context, SimpleWakefulService.class);//intent to call another class // Start the service, keeping the device awake while it is launching. startWakefulService(context, service);//service started }
SimpleWakefulService:
public class SimpleWakefulService extends IntentService { public SimpleWakefulService() { super("SimpleWakefulService");//instantiates simpleWakefulService } @Override protected void onHandleIntent(Intent intent) { Log.e("simpleWakeful","simpleWakeful"); serviceCall(this); //here is downloadTaskMethod called and getting response as 1. }
不要用setInexactRepeating
.顾名思义,这并没有安排闹钟在确切的时间发生.
你可以使用这样的东西:
public void scheduleSingleAlarm(Context context) { Intent intent = new Intent(context, NotificationReceiver.class); PendingIntent pendingUpdateIntent = PendingIntent.getBroadcast(context, SINGLE_ALARM_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT); Calendar futureDate = Calendar.getInstance(); futureDate.add(Calendar.MINUTE, 3); setSingleExactAlarm(futureDate.getTime().getTime(), pendingUpdateIntent); } @SuppressLint("NewApi") private void setSingleExactAlarm(long time, PendingIntent pIntent) { if (android.os.Build.VERSION.SDK_INT >= 19) { mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pIntent); } else { mAlarmManager.set(AlarmManager.RTC_WAKEUP, time, pIntent); } }
当您收到来自闹钟的呼叫时,请在另外三分钟内安排另一个闹钟响起.我在这里写了这篇博文