我对Android中的本地通知有疑问。我正在开发一个应用程序,其中第一部分必须接收我自己的服务器公司的所有会议(我已经实现),第二部分我必须在每次会议前一天通知,但有本地通知。
如何在指定日期安排本地通知?
答案 0 :(得分:12)
要安排本地通知,您需要了解用于安排通知的一些内容,例如
BroadcastReceivers IntentFilters AlarmManager NotificationService 的PendingIntent
在MainActivity中执行以下操作
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import itertools
#read in data from csv organised in columns labelled 'lat','lon','elevation'
data = np.recfromcsv('elevation-sample.csv', delimiter=',')
# create a 3d axis on a figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Find unique (i.e. constant) latitude points
id_list = np.unique(data['lat'])
# stride is how many lines to miss. set to 1 to get every line
# higher to miss more
stride = 5
# Extract each line from the dataset and plot it on the axes
for id in id_list[::stride]:
this_line_data = data[np.where(data['lat'] == id)]
lat,lon,ele = zip(*this_line_data)
ax.plot(lon,lat,ele, color='black')
# set the viewpoint so we're looking straight at the longitude (x) axis
ax.view_init(elev=45., azim=90)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_zlabel('Elevation')
ax.set_zlim([0,1500])
plt.show()
上述代码将在15秒后安排警报。 15秒后,它将广播notificationIntent。
Intent构造函数中指定的操作在AndroidManifest.xml中定义
要了解本地通知的完整工作情况并查看示例通知代码,请查看此文章 - http://www.singhajit.com/schedule-local-notification-in-android/
答案 1 :(得分:1)
编辑:我现在已经尝试了 WorkManager
,但它在时间上似乎也非常不可靠。很抱歉。
如果您想安排不需要非常精确的时间的本地通知,最好不要使用 AlarmManager,因为 many Android phones 会运行得太晚,或者绝不。而是使用 androidx 中的 WorkManager。
Josip Žitković 在 this blog 中出色地解释了所有这些。
首先,随时随地安排通知:
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);
}
}
}