Saturday, 2 January 2016

Local Notification Using Broadcast Receiver and AlarmManager



// From Your Activity onCreate method call
NotificationManager.getInstance().RegisterNotification(this);

// Notification Manager Class
public class NotificationManager {

      public static NotificationManager getInstance(){
        return new NotificationManager();;
    }

    public void RegisterNotification(Context context) {

        Intent myIntent = new Intent(context , NotificationReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
        context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        TimeZone timeZone= TimeZone.getDefault();
        Calendar calendar= Calendar.getInstance(timeZone);
        calendar.set(Calendar.HOUR_OF_DAY, 17);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 00);

        AlarmManager alarmManager = (AlarmManager)
              context.getSystemService(context.ALARM_SERVICE);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis(), 10 * 1000, pendingIntent);

        //set repeating every 24 hours 24 * 60 * 60 * 1000  
    // alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
  }

    public void sendNotification(Context context) {

        Intent mIntent = new Intent(context, SplashScreenActivity.class);

        mIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
          | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(context,
          0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder b = new NotificationCompat.Builder(context);

        b.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.Notify_icon)
                .setTicker("Your Tittle")
                .setContentTitle("Default notification")
                .setContentText("Content of your notification")
                .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent)
                .setContentInfo("Info");

        android.app.NotificationManager notificationManager = (android.app.NotificationManager)
         context.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1, b.build());
    }
}

// For your Receiver Class
public class NotificationReceiver extends BroadcastReceiver {

    @Override    public void onReceive(Context context, Intent intnt) {

        NotificationManager.getInstance().sendNotification(context);
    }
}

// Finally don't forget to mention in your manifest file.

<receiver android:name=".NotificationReceiver" />

2 comments: