如何设置闹钟管理器时间?

时间:2014-04-03 10:06:38

标签: android alarmmanager

我需要在程序中设置15分钟闹钟。我该如何设置?

这是我到目前为止的代码:

public void onReceive(Context context, Intent intent) 
{   
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
   wl.acquire();

   Intent App = new Intent(context, LoginActivity.class);
   App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   context.startActivity(App);

   Toast.makeText(context, "instantmeter waking restart", Toast.LENGTH_LONG).show(); // For example
   wl.release();
}

public void SetAlarm(Context context)
{
   AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
   Intent i = new Intent(context, PollReceiver.class);
   PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
   am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 100, pi); // Millisec * Second * Minute
}

2 个答案:

答案 0 :(得分:0)

您的代码正确但时间间隔不正确。 AlarmManager以毫秒为单位接受值。所以15分钟,你需要计算如下,

15 * 60 * 1000

试试这段代码,

public void onReceive(Context context, Intent intent) 
{   
   PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
   PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
   wl.acquire();

   Intent App = new Intent(context, LoginActivity.class);
   App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   context.startActivity(App);

   Toast.makeText(context, "instantmeter waking restart", Toast.LENGTH_LONG).show(); // For example
   wl.release();
}

public void SetAlarm(Context context)
{
   AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
   Intent i = new Intent(context, PollReceiver.class);
   PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
   am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 15 * 1000 * 60 , pi); // Millisec * Second * Minute
}

答案 1 :(得分:0)

我使用了以下代码并且有效:

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver  
{
  private static final int _REFRESH_INTERVAL = 60 * 15; // 15 minutes


  public void setAlarm()
  {
    AlarmManager am=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    pi = PendingIntent.getBroadcast(context, ALARM_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    try
    {
        am.cancel(pi);
    }
    catch (Exception ignored){}
    am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * _REFRESH_INTERVAL , pi);
  }

  @Override
  public void onReceive(Context context, Intent intent) 
  {
    // Alarm action here
  }
}

猜猜SystemClock.elapsedRealtime()可以解决问题..