ksh.max
ksh.max

Reputation: 439

Android AlarmManager effect immediately, why?

I'm learning to use AlarmManager in Android. I was looking for example in google and I found stackoverflow.com I have a class

public class Alarm extends BroadcastReceiver 
{    
     @Override
     public void onReceive(Context context, Intent intent) 
     {   
         PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TESTTEST");
         wl.acquire();

         // Put here YOUR code.
         Toast.makeText(context, "Alarm !!!!!!!!!!", 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, Alarm.class);
     PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
     am.set(AlarmManager.RTC, 1000 * 10 , pi); // Millisec * Second * Minute    
 }

 public void CancelAlarm(Context context)
 {
     Intent intent = new Intent(context, Alarm.class);
     PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
     alarmManager.cancel(sender);
 }
}

And my activity

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarm = new Alarm();
        alarm.SetAlarm(getApplicationContext());


    }

I get this exapmle code from other post on stackoverflow.com Why Toask ALARM!!! shows immediately ???

Upvotes: 0

Views: 491

Answers (2)

Rasel
Rasel

Reputation: 15477

If the time occurs in the past, the alarm will be triggered immediately. If there is already an alarm for this Intent scheduled (with the equality of two intents being defined by filterEquals(Intent)), then it will be removed and replaced by this one.

If you want your alarm after 1000 * 10 then use System.System.currentTimeMillis()+1000*10;

Upvotes: 2

Jambaaz
Jambaaz

Reputation: 2848

For 10 seconds , It is best to use this...

am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 10*1000, pi);

Upvotes: 0

Related Questions