如何在Android上安排本地通知?

9

我对Android本地通知有一个问题。我正在开发一个应用程序,在第一部分中,我必须接收自己服务器上公司的所有会议(这一点我已经实现了),在第二部分中,我必须在每次会议前一天使用本地通知进行提醒。

如何在特定日期安排本地通知?


3
请看这个这个 - Skynet
2个回答

16

要安排本地通知,您需要了解一些用于安排通知的东西,例如:

  1. BroadcastReceiver(广播接收器)

  2. IntentFilter(意图过滤器)

  3. AlarmManager(闹钟管理器)

  4. NotificationService(通知服务)

  5. PendingIntent(待定意图)

MainActivity中,请执行以下操作:

    @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);
    }

以上代码将在15秒后安排一个闹钟,15秒后它将广播NotificationIntent

在Intent构造函数中指定的操作在AndroidManifest.xml中定义。

要了解本地通知的完整工作原理并查看示例通知代码,请查看此文章


如何重复该过程? - Saty
1
使用Calendar的HOUR_OF_DAY并设置重复闹钟Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 9); cal.add(Calendar.MINUTE, 0); cal.add(Calendar.SECOND, 0); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24 * 60 * 60 * 1000 , broadcast); - Ajit Singh
1
@Saty:如果这个回答有帮助解决了你的问题,能否接受一下呢?否则请留下评论说明没有帮助。这将有助于其他寻找类似问题的人。 - bianca
@AjitSingh 我的应用程序根本没有调用广播接收器。尝试了应用程序关闭和运行条件。 - mpsbhat
注意:自 Android 8 开始,不允许在应用程序未运行时注册自定义的“BroadcastReciver”。 - Yuri Misyac

4
编辑:我现在尝试了WorkManager,但它的时间安排非常不可靠。很抱歉。

如果您想安排一个不需要非常精确时间的本地通知,则最好不要使用AlarmManager,因为许多Android手机会延迟执行或者从未执行。而是使用androidx中的WorkManager

Josip Žitković在此博客中出色地解释了所有这些内容。

首先,无论何时都可以安排通知:

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

现在创建MyWorker,它将被调用以显示实际通知:
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);
        }
    }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接