Android notification at specific date

Buze picture Buze · Mar 29, 2012 · Viewed 13.6k times · Source

I have to create an app in which I must set a date and at that specific date at 9 O'clock, I must give a notification. What is the simplest method of doing this? I want the app to work even when the app gets killed anyway. Is AlarmManager a solution?

Answer

Wajdi Hh picture Wajdi Hh · Mar 29, 2012

To schedule an Action you can use the AlarmManager

Try this code it's work for me:

1 / Declare the BroadcastReceiver CLASS to launch the Action, this class can be inside your activity or outside in an other java file

public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(context, intent.getStringExtra("param"),Toast.LENGTH_SHORT).show();
    }

}

2/ Inside your Oncreate Method put this code

AlarmManager alarms = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    Receiver receiver = new Receiver();
    IntentFilter filter = new IntentFilter("ALARM_ACTION");
    registerReceiver(receiver, filter);

    Intent intent = new Intent("ALARM_ACTION");
    intent.putExtra("param", "My scheduled action");
    PendingIntent operation = PendingIntent.getBroadcast(this, 0, intent, 0);
    // I choose 3s after the launch of my application
    alarms.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+3000, operation) ;   

Launch your App a Toast will be appeared after 3 seconds, So you can change "System.currentTimeMillis()+3000" with your wake up time.