2012-03-29 53 views
3

我有触发在首次多警报的问题,这里是我的代码多个火警在同一时间

是发射活动,其中我写了下面的代码::

** onCreate方法:

// Calling Method setNextAlarm two times..with different id and time 

    setNextAlarm(0,60000); 
    setNextAlarm(1,120000); 

和setNextAlarm在这里::

private void setNextAlarm(int id,long time) { 
      AlarmManager mgr = (AlarmManager) TestAct.this 
      .getSystemService(Context.ALARM_SERVICE); 
      Intent i = new Intent(TestAct.this, OnBootReceiver.class); 
      i.putExtra("id", id); 

      Log.e("Firing up next alarm in "+id,""+time/(60*1000) +"minutes"); 

      PendingIntent pi = PendingIntent.getBroadcast(TestAct.this, id, i,PendingIntent.FLAG_ONE_SHOT); 
      mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, pi); 
    } 

当我运行这段代码将它称为onBootReceiver,它是我们的广播接收器类。

所以我的问题是::

定义这个方法

setNextAlarm(0,60000); 
setNextAlarm(1,120000); 

为什么它火的同时,不同的时间和ID后面?除了第一次以固定的时间间隔运行。

这是我onBootReceiver类的方法的onReceive

Bundle b = intent.getExtras(); 

int id = b.getInt("id"); 

if(id==1){ 
    PERIOD=300000; 
}else{ 
    PERIOD=120000; 
} 

Log.e("OnBootReceiver"," Calling"+id+" in "+PERIOD/60000 + "minutes"); 

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    Intent i=new Intent(context, OnAlarmReceiver.class); 
    i.putExtra("id", id); 
    PendingIntent pi=PendingIntent.getBroadcast(context, id,i, 0); 
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
         SystemClock.elapsedRealtime()+60000, 
         PERIOD, 
         pi); 

感谢。

+0

在启动接收器,用于ID 0,周期变120000相同ID 1.我错了? – tartar 2012-03-29 07:53:31

+0

你是正确的..为id 0期间成为120000为id 1期间是300000 – Ajay 2012-03-29 07:54:54

回答

0
在OnBootReceiver

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
        SystemClock.elapsedRealtime() + 60000, PERIOD, pi); 

这里是改变

我设置

SystemClock.elapsedRealtime() + 60000 for id = 0 

,并设置

SystemClock.elapsedRealtime() + 120000 for id = 1 

,问题解决了。

但我仍在等待更好的解释。

我找到的资料很少在这里约SystemClock.elapsedRealtime()

elapsedRealtime()以毫秒为单位计数从这个系统被启动,其中包括深度睡眠。测量可能跨越系统睡眠周期的时间间隔时应使用此时钟。

http://developer.android.com/reference/android/os/SystemClock.html