0

I've been programming in Android for over a year but have never used notifications before, which I need for one of my apps.

In the app, there are events that can be set at different times. Obviously, the user can choose to change these times or add/remove events.

I plan to use notifications to notify the user 5 minutes before their event starts.

I've read through the Android developer docs for Building a Notification and Services (which I am also new to). I have decided to use Services because I figured that the notification would need to be shown even when the app not running. To help me, I have been referring to one particular SO answer as guidance.

I begun by experimenting a little with the notification builder classes in my NotificationService class like so:

public class NotificationService extends IntentService {

    private static final int NOTIFICATION_ID = 1;

    public NotificationService() {
        super(NotificationService.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        showNotification();
    }

    private void showNotification() {
        Intent intent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle("Test notification")
                .setSmallIcon(R.drawable.ic_event_black_24dp)
                .setContentText("Test description")
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());
    }

}

I also use the following to start this Service in the splash screen of my app:

Intent serviceIntent = new Intent(this, NotificationService.class);
startService(serviceIntent);

To display notifications at specific times, I've read about AlarmManager, mainly through SO questions like this one. I also know that to display multiple notifications, I would need different notification ids (like my constant NOTIFICATION_ID).

However, what I am unsure of is dynamically updating the times that notifications would be shown each time an event is added, removed, or its times changed.

Could someone provide me some guidance on how I could achieve this?

1 Answer 1

0

You implement notification part. For notify user at Specific time you should set AlarmManager. I paste whole code you need then explain each part:

public class AlarmReceiver extends WakefulBroadcastReceiver {

    AlarmManager mAlarmManager;
    PendingIntent mPendingIntent;

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

        int mReceivedID = Integer.parseInt(intent.getStringExtra(AddReminderActivity.EXTRA_REMINDER_ID));

        // Get notification title from Reminder Database
        ReminderDatabase rb = new ReminderDatabase(context);
        ApiReminderModel reminder = rb.getReminder(mReceivedID);
        String mTitle = reminder.getName();

        // Create intent to open ReminderEditActivity on notification click

        // handling when you click on Notification what should happen
        Intent editIntent = YourActivity.createActivity(context, reminder.getChannelId(), reminder.getStartTime());
        PendingIntent mClick = PendingIntent.getActivity(context, mReceivedID, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        // Create Notification
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_logo))
                .setSmallIcon(R.drawable.ic_logo)
                .setContentTitle(context.getResources().getString(R.string.app_name))
                .setTicker(mTitle)
                .setContentText(mTitle)
                .setContentIntent(mClick)
                .setSound(ringtoneUri)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true);

        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(mReceivedID, mBuilder.build());
    }

    public void setAlarm(Context context, Calendar calendar, int ID) {
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // Put Reminder ID in Intent Extra
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.putExtra(AddReminderActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
        mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        // Calculate notification time
        Calendar c = Calendar.getInstance();
        long currentTime = c.getTimeInMillis();
        long diffTime = calendar.getTimeInMillis() - currentTime;

        // Start alarm using notification time
        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime, mPendingIntent);

        // Restart alarm if device is rebooted
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }


    public void cancelAlarm(Context context, int ID) {
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // Cancel Alarm using Reminder ID
        mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0);
        mAlarmManager.cancel(mPendingIntent);

        // Disable alarm
        ComponentName receiver = new ComponentName(context, BootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
}

As you see we have setAlarm which notify users at specific time. I also pass calendar instance which is initiated before ( assign a time which user should be notify).

 Calendar mCalendar = Calendar.getInstance();
         mCalendar.add(Calendar.DAY_OF_YEAR, 7);// assume you want send notification 7 days later

        new AlarmReceiver().setAlarm(getApplicationContext(), mCalendar, id);

We have another method cancelAlarm. If you want to delete a Alaram just pass unique ID of Alarm (Which already used for creation of Alarm).

Also don't forget to add this Service to your AndroidManifest.xml:

<receiver android:name=".service.AlarmReceiver" />

There is only on thing remain When you reboot your device you should set AlarmsManager again so you need a BootRecivier service.

5
  • Thank you so much for the detailed answer, Amir. I'll try implementing this and let you know if I have any further questions. Aug 28, 2016 at 19:27
  • @FarbodSalamat-Zadeh full implementation could be find at: github.com/blanyal/Remindly
    – Amir
    Aug 28, 2016 at 19:29
  • Thanks again - just to confirm, do I still need my Service class I created earlier? Aug 28, 2016 at 20:08
  • @FarbodSalamat-Zadeh No because in AlarmReciever I put Notification too.
    – Amir
    Aug 28, 2016 at 20:28
  • 1
    Ah, I see. Thanks for the clarification. Aug 28, 2016 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.