java - 提醒通知不显示
问题描述
我正在制作一个应用程序来提醒用户一些事情。我想在将来的某个时间显示通知。我已经按照一些教程编写了下面的代码,但它似乎不起作用。在我期待通知的时候,它没有出现。
我正在使用 aBroadcastReceiver
和 theAlarmManager
在所需时间发出通知。这是我的(简化的)代码。
设置时间的代码:
try {
Date date = format.parse(timeInput);//This part works
long time = date.getTime();//Get the time in milliseconds
Intent i = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent alarmSender = PendingIntent.getBroadcast(getBaseContext(), 0, i, 0);
AlarmManager am = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, time, alarmSender);
Toast.makeText(getBaseContext(), "Keep the app running to receive a reminder notification", Toast.LENGTH_LONG).show();
super.onBackPressed();
}catch(Exception e){
Toast.makeText(getBaseContext(), "Parsing error. Format:\ndd/MM/yyyy and HH:mm", Toast.LENGTH_SHORT).show();
}
AlarmReceiver.onReceive()
方法:
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
NotificationCompat.Builder nBulder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notify_icon)
.setContentTitle("title")
.setContentText("text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat nManager = NotificationManagerCompat.from(context);
nManager.notify(0, nBulder.build());
}
一切都在清单文件中正确声明。
解决方案
<receiver
android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true"></receiver>
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
throw new UnsupportedOperationException("Not yet implemented");
}
}
小改动:
try {
long time = System.currentTimeMillis();
Intent i = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent alarmSender = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
AlarmManager am = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, time, alarmSender);
} catch(Exception e){
Toast.makeText(getBaseContext(), "Parsing error. Format:\ndd/MM/yyyy and HH:mm", Toast.LENGTH_SHORT).show();
}
getContext() 、 getApplicationContext() 、 getBaseContext() 和“this”之间的区别
推荐阅读
- kubernetes - 如何使用 kubectl 查看 CronJob 的 restartPolicy?
- aframe - 如何通过 A 帧中的光学跟踪捏合来控制摄像机装备的方向?
- mariadb - MariaDB 10.4 QUERY 或子查询优化
- java - BroadcastReceiver 收到不止一次
- javascript - 页面刷新后 React UseState 不更新 UI
- sql - BigQuery - 连接忽略 NULL
- wordpress - 添加优惠券后隐藏和刷新 WooCommerce 结帐
- c++ - 有没有办法确保继承的成员在派生类中不可访问,同时仍然保持公共继承的好处?
- c# - 列表的 RDLC 数据类型
- neural-network - 如何可视化 TensorRT 网络图?