Skip to content Skip to sidebar Skip to footer

Custom Notification Center

Currently I have a requirement that enables push notifications in the app but we can't use other APIs like google's Firebase. So we have the handle the notification management by o

Solution 1:

You need to generate notification from app. (with alarm manager at specific time)

Add in manifest.xml

<uses-permissionandroid:name="android.permission.WAKE_LOCK" /><serviceandroid:name=".LocalNotificationIntentService"android:enabled="true"android:exported="false"/><receiverandroid:name=".OnBootBroadcastReceiver"><intent-filter><actionandroid:name="android.intent.action.BOOT_COMPLETED" /></intent-filter></receiver>

SplashScreen (Activity)

onCreate()
{
    LocalNotificationEventReceiver.setupAlarm(getApplicationContext());
}

OnBootBroadcastReceiver.class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

publicclassOnBootBroadcastReceiverextendsBroadcastReceiver {
    @OverridepublicvoidonReceive(Context context, Intent intent) {
        LocalNotificationEventReceiver.setupAlarm(context);
    }
}

LocalNotificationEventReceiver.class

publicclassLocalNotificationEventReceiverextendsWakefulBroadcastReceiver {

    privatestaticfinalStringACTION_START_NOTIFICATION_SERVICE="ACTION_START_NOTIFICATION_SERVICE";
    privatestaticfinalStringACTION_DELETE_NOTIFICATION="ACTION_DELETE_NOTIFICATION";

    publicstaticvoidsetupAlarm(Context context) {
        AlarmManageralarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntentalarmIntent= getStartPendingIntent(context);


        Calendarcalendar= Calendar.getInstance();
        CalendarsetCalendar= Calendar.getInstance();
        setCalendar.set(Calendar.HOUR_OF_DAY, 7);
        setCalendar.set(Calendar.MINUTE, 30);
        setCalendar.set(Calendar.SECOND, 0);

        if (setCalendar.before(calendar))
            setCalendar.add(Calendar.DATE, 1);

        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                setCalendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY,
                alarmIntent);


        /*long firstRunTime = calendar.getTimeInMillis();
        long futureInMillis = 60 * 1000;
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                firstRunTime,
                futureInMillis,
                alarmIntent);*/

    }

    @OverridepublicvoidonReceive(Context context, Intent intent) {
        Stringaction= intent.getAction();
        IntentserviceIntent=null;
        if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
            serviceIntent = LocalNotificationIntentService.createIntentStartNotificationService(context);
        } elseif (ACTION_DELETE_NOTIFICATION.equals(action)) {
            serviceIntent = LocalNotificationIntentService.createIntentDeleteNotification(context);
        }

        if (serviceIntent != null) {
            startWakefulService(context, serviceIntent);
        }
    }

    privatestatic PendingIntent getStartPendingIntent(Context context) {
        Intentintent=newIntent(context, LocalNotificationEventReceiver.class);
        intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    publicstatic PendingIntent getDeleteIntent(Context context) {
        Intentintent=newIntent(context, LocalNotificationEventReceiver.class);
        intent.setAction(ACTION_DELETE_NOTIFICATION);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
}

LocalNotificationIntentService.class

import android.app.ActivityManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.text.Html;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

publicclassLocalNotificationIntentServiceextendsIntentService {

    privatestaticfinalintNOTIFICATION_ID=1;
    privatestaticfinalStringACTION_START="ACTION_START";
    privatestaticfinalStringACTION_DELETE="ACTION_DELETE";
    staticprivateintmyUserSelectedSortedType= CommonUtils.SORT_BY_CUSTOMER_NAME;

    publicLocalNotificationIntentService() {
        super(LocalNotificationIntentService.class.getSimpleName());
    }

    publicstatic Intent createIntentStartNotificationService(Context context) {
        Intentintent=newIntent(context, LocalNotificationIntentService.class);
        intent.setAction(ACTION_START);
        return intent;
    }

    publicstatic Intent createIntentDeleteNotification(Context context) {
        Intentintent=newIntent(context, LocalNotificationIntentService.class);
        intent.setAction(ACTION_DELETE);
        return intent;
    }

    @OverrideprotectedvoidonHandleIntent(Intent intent) {
        try {
            Stringaction= intent.getAction();
            if (ACTION_START.equals(action)) {
                processStartNotification();
            }
            if (ACTION_DELETE.equals(action)) {
                processDeleteNotification(intent);
            }
        } finally {
            WakefulBroadcastReceiver.completeWakefulIntent(intent);
        }
    }

    privatevoidprocessDeleteNotification(Intent intent) {
        // Log something?
    }

    privatevoidprocessStartNotification(Intent intent) {
        NotificationManagernotificationManager=
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Notificationnotification= getNotification(thePremiumReminderCount, theReminderDate, toYear);
        notificationManager.notify(NOTIFICATION_ID, notification);
    }
    private Notification getNotification() {
        booleanisActivityFound=false;

        ActivityManageractivityManager= (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningTaskInfo> services = activityManager
                .getRunningTasks(Integer.MAX_VALUE);

        if (services.get(0).topActivity.getPackageName().toString()
                .equalsIgnoreCase(this.getPackageName().toString())) {
            isActivityFound = true;
        }
        IntentopenIntent=null;

        PendingIntentcontentIntent= PendingIntent.getActivity(this, NOTIFICATION_ID,
                openIntent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(this)
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setVibrate(newlong[]{100, 250, 100, 250, 100, 250})
                        .setAutoCancel(true)
                        .setColor(this.getResources().getColor(R.color.activity_toolbar_color))
                        .setContentTitle("title")
                        .setStyle(newNotificationCompat.BigTextStyle()
                                .bigText(Html.fromHtml("text")))
                        .setPriority(Notification.PRIORITY_MAX)
                        .setContentText(Html.fromHtml("text"));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.setSmallIcon(R.drawable.notification_icon1);
        } else {
            mBuilder.setSmallIcon(R.drawable.notification_icon);
        }
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDeleteIntent(LocalNotificationEventReceiver.getDeleteIntent(this));
        return mBuilder.build();
    }
    }

Post a Comment for "Custom Notification Center"