Android: How to use AlarmManager

前端 未结 6 1113
时光取名叫无心
时光取名叫无心 2020-11-22 06:40

I need to trigger a block of code after 20 minutes from the AlarmManager being set.

Can someone show me sample code on how to use an AlarmManager<

6条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:08

    What you need to do is first create the intent you need to schedule. Then obtain the pendingIntent of that intent. You can schedule activities, services and broadcasts. To schedule an activity e.g MyActivity:

      Intent i = new Intent(getApplicationContext(), MyActivity.class);
      PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),3333,i,
      PendingIntent.FLAG_CANCEL_CURRENT);
    

    Give this pendingIntent to alarmManager:

      //getting current time and add 5 seconds in it
      Calendar cal = Calendar.getInstance();
      cal.add(Calendar.SECOND, 5);
      //registering our pending intent with alarmmanager
      AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
      am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), pi);
    

    Now MyActivity will be launched after 5 seconds of the application launch, no matter you stop your application or device went in sleep state (due to RTC_WAKEUP option). You can read complete example code Scheduling activities, services and broadcasts #Android

提交回复
热议问题