Search code examples
androidalarmmanagerandroid-notificationsandroid-date

Android notification at specific date


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?


Solution

  • 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.