Search code examples
javaandroidalarmandroid-alarms

Start AlarmManager on button click


I want to start an AlarManager when a button is pressed. The problem is: The AM starts when I start the app :/

My Code:

public void scheduleAlarm()
    {  
            int time = 10 * 1000;

            intentAlarm = new Intent(this, AlarmReciever.class);

            alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, time, time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));

    }

And I try to call this in a onClickListener of a button. But it starts from beginning of activity :/

Can anyone help me?


Solution

  • thanks for posting your code. Try this:

    public static String ALARM_TO_SET = "ALRMTOSEND";
    yourButton.setOnClickListener(new OnClickListener(){
    public void onClick(View view){
         int time = 10 * 1000;
    
        intentAlarm = new Intent(ALARM_TO_SET);
    
        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0)
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, time, time, pIntent);
    
    
      }
    });
    

    Your Broadcast receiver should be registered in the Manifest.xml file as:

    <receiver android:name=".AlarmRecieverClass">
    <intent-filter>
    <action android:name="ALRMTOSEND" />
    </intent-filter>
    </receiver>