Reputation: 1860
i have a alarm application that should print a toast message every 1 minute.But it does that just once when Application is run for the first time.
here my code:
private class ConnectivityReceiver extends BroadcastReceiver{
MainActivity m= new MainActivity ();
private Timer mTimer;
private TimerTask mTimerTask;
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
wl.acquire(); Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // Every 1 minute i print the tost message. wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, ConnectivityReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 1, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, ConnectivityReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Upvotes: 0
Views: 370
Reputation: 4008
Just do one thing,
in the line PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
replace with PendingIntent sender = PendingIntent.getBroadcast(context, **someUniqueId**, intent, 0);
where uniqueId is integer either u generate or declare as "i++" where i is public static int i;
Hope this will work
Upvotes: 3
Reputation: 29672
Please update your this line
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 1, pi);
to
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ( 1000 * 60 ), 1000 * 60 * 10, pi);
This will add one minute your System.currentTimeMillis();
and will start after that time.
Upvotes: 1