Search code examples
androidnotificationsalarmmanageralarm

How to set Scheduled notification in android


I want my app to throw a notification after 10 seconds even if the app is not running. I have made use of the AlarmManager but unable to get the notification at the desired time. I am able to get a toast at that time but not the notification. Any help will be deeply appreciated.

This is my AlarmManager class:

public class AlarmManagerActivity extends Activity {

private AlarmManagerBroadcastReceiver alarm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm_manager);
    alarm = new AlarmManagerBroadcastReceiver();
    onetimeTimer();


}

@Override
protected void onStart() {
    super.onStart();
}


public void notifyN(){

    Intent intent = new Intent(this, NotificationReceiverActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    // Build notification
    // Actions are just fake
    Notification noti = new Notification.Builder(this)
            .setContentTitle("This is a sample notification")
            .setContentText("Subject")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .addAction(R.drawable.ic_action_search, "Call", pIntent)
            .addAction(R.drawable.ic_action_search, "More", pIntent)
            .addAction(R.drawable.ic_action_search, "And more", pIntent).build();


    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, noti);
}


public void onetimeTimer(){
    Context context = this.getApplicationContext();
    if(alarm != null){
        alarm.setOnetimeTimer(context);
        notifyN();

    }else{
        Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
    }
}

}

And this is the AlarmManagerBroadcastReceiver:

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

final public static String ONE_TIME = "onetime";

@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, "YOUR TAG");
    // Acquire the lock
    wl.acquire();

    // You can do the processing here update the widget/remote views.
    Bundle extras = intent.getExtras();
    StringBuilder msgStr = new StringBuilder();

    if (extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)) {
        msgStr.append("One time Timer : ");
    }
    Format formatter = new SimpleDateFormat("hh:mm:ss a");
    msgStr.append("abcs stop the instance" + formatter.format(new Date()));

    Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();

    // Release the lock
    wl.release();

}

public void setOnetimeTimer(Context context) {
    AlarmManager am = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.TRUE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pi);

}
}

Solution

  • Create a class (call it something like ScheduledService) and let it extend IntentService. In this class you'll do what you want to do when the alarm goes off.

    public class ScheduledService extends IntentService {
    
    public ScheduledService() {
        super("My service");
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        //Do something, fire a notification or whatever you want to do here
        Log.d("debug", "Ring Ring!");
    
    }
    }
    

    then in you activity to start the alarm use the following:

    AlarmManager mgr = (AlarmManager) YourActivity.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(YourActivity, ScheduledService.class);
    PendingIntent pi = PendingIntent.getService(YourActivity, 0, i, 0);
    mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + PERIOD, pi);
    

    Where PERIOD is the time in milliseconds after which you want the alarm to goes off.

    To cancel the alarm use:

    if (mgr != null)
            mgr.cancel(pi);
    

    Finally for all this to work you need to register your ScheduledService class as a Service. In your manifest add this tou your application:

    <application
        ... />
        ...
        <service android:name=".ScheduledService" >
        </service>
    
    </application>
    

    This way the Android OS will take care of firing the alarm when it's time. even if another application is running or your app process is terminated.