Search code examples
androidalarmmanager

Schedule a message using alarm manager


I'm working on an Android application which schedules messages to be sent. I'm making use of alarm manager. My main part of the code is as follows:

mConfirm.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = 
            new Intent(getApplicationContext(),MyNotificationService.class);

        mMessage = mEditTextMessage.getText().toString();
        mNumber = mEditTextNumber.getText().toString();
        c.set(mYear, mMonth, mDay);
        c.set(Calendar.HOUR_OF_DAY, mHour);
        c.set(Calendar.MINUTE, mMinutes);

        Bundle bundle = new Bundle();
        bundle.putCharSequence("number", mNumber);
        bundle.putCharSequence("message", mMessage);
        intent.putExtras(bundle);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent = 
            PendingIntent.getService(getApplicationContext(), 0, intent, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 
            pendingIntent);
    }
});

How should I implement MyNotificationService class so that it sends the message at the set time? Should that class be a Service or a Broadcast receiver?


Solution

  • Below code will allow you to call a broadcast receiver after every 5 seconds.You can use set() ot setTimeZone() method to set at a particular time.

    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra("abc", Boolean.FALSE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    //After after 5 seconds
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
    

    AlarmManagerBroadcastReceiver class is a broadcaster.