Вопрос

Following code will repeat the alarm every 5 seconds. But I want this alarm to get canceled after 60 seconds.

 AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
 Intent i = new Intent(context, CrawlAlarm.class);
 PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
 am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 5, pi); // Millisec * Second * Minute
Это было полезно?

Решение

AlarmManager am=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, CrawlAlarm.class);
final PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 5, pi); // Millisec * Second * Minute  

Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {

    @Override
    public void run() {
        am.cancel(pi);
    }

}, 60 * 1000);

This will cancel it after 60 seconds.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top