How schedule local notifications Android?
Asked Answered
M

2

9

I have a question about local notifications in Android. I am developing an application where in the first part I must receive all meetings of the company of my own server (this I have achieved), and the second part I must notify one day before each meeting, but with local notifications.

How to schedule local notifications at a given date?

Munro answered 16/4, 2014 at 9:56 Comment(1)
Check This and thisOrndorff
M
16

To schedule local notification you need to know some of the things which are used to schedule the notification like:

  1. BroadcastReceivers

  2. IntentFilters

  3. AlarmManager

  4. NotificationService

  5. PendingIntent

In the MainActivity do the following:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
 
        Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
        notificationIntent.addCategory("android.intent.category.DEFAULT");
 
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
 
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, 15);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
    }

The above code will schedule an alarm after 15 seconds. After 15 seconds it will broadcast the NotificationIntent.

The action specified in the Intent constructor is defined in the AndroidManifest.xml

To understand the full working of local notification and to see a sample notification code check out this article

Matland answered 11/8, 2015 at 16:2 Comment(5)
what to do to repeat the process?Jeconiah
Use the HOUR_OF_DAY for Calendar and setRepeatingAlarm Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 09); cal.add(Calendar.MINUTE, 0); cal.add(Calendar.SECOND, 0); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24 * 60 * 60 * 1000 , broadcast);Matland
@Jeconiah : could you accept this as answer if this helped solve your problem, otherwise put a comment that it didn't help. It would help others looking for similar question.Officiant
@AjitSingh Not calling the broadcast receiver at all in my app. Tried both app is closed & running conditionsFerrell
NOTE: developer.android.com/guide/components/broadcasts#android_80 since android 8, don't allow to register custom BroadcastReciver while the app not running.Inequality
S
4

Edit: I've now tried WorkManager, and it seems to be hugely unreliable in timing as well. Sorry about that.

If you want to schedule a local notification that doesn't need extremely precise time, you're better off not using AlarmManager, as many Android phones will run it way too late, or never. Instead use WorkManager from androidx.

All this was explained awesomely by Josip Žitković in this blog.

First, schedule the notification whereever you want:

WorkRequest work = new PeriodicWorkRequest.Builder(MyWorker.class, 1, TimeUnit.DAYS)
    .setInitialDelay(delay, TimeUnit.MINUTES)
    .build()
;
WorkManager.getInstance(context).enqueue(work);

Now create MyWorker, that will be called to show the actual notification:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.TaskStackBuilder;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class MyWorker extends Worker {
    public MyWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
        Context context = this.getApplicationContext();

        // Intent to start when notification is tapped
        Intent notificationIntent = new Intent(context, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(notificationIntent);
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        createNotificationChannel(context);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "my_channel")
            .setContentTitle("hello, world")
            // Only on api < 26, see createNotificationChannel otherwise
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Default sound, vibration etc
            // Only on api < 26, see createNotificationChannel otherwise
            .setDefaults(Notification.DEFAULT_ALL)
            .setContentIntent(pendingIntent);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(0, builder.build());

        return Result.success();
    }

    /**
     * This needs to be called at least once on android API >= 26 before creating a notification.
     */
    public static void createNotificationChannel(Context context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("my_channel", "MyApp notifications", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("They will wake you up in the night");
            channel.enableVibration(true);

            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

Stricture answered 14/1, 2021 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.