我已经寻找了好几个小时,想要准确地实现以下内容:
我希望每天(除了周末)在某个特定时间(比如说下午6点)发送一条通知,但前提是应用程序没有打开。就像 Gmail 应用程序在您收到邮件时的情况一样。 当用户点击通知时,它应该消失,并且应该跳转回 MainActivity。
我尝试过很多使用 AlarmManager 的方法,但都没有成功显示出通知。
以下是我尝试过的代码,感觉非常接近正确:
在我的 MainActivity 中:
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
Intent intent = new Intent(this, NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
我的NotificationService:
public class NotificationService extends IntentService {
public NotificationService() {
super("NotificationService");
}
@Override
@SuppressWarnings("deprecation")
protected void onHandleIntent(Intent intent) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "reminder", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent , 0);
notification.setLatestEventInfo(getApplicationContext(), "It's about time", "You should open the app now", contentIntent);
nm.notify(1, notification);
}
}
请注意,我使用了被弃用的内容,因为这是唯一的方式,即使不使用AlarmManager,通知也会出现。如果可能的话,请提供一个不包含被弃用内容但最新的解决方案 :P
非常非常感谢您的提前帮助!!!
最亲切的问候
android:name="be.menis.timesheet.service.AlarmReceiver"
是什么?我想每天上午10点设置通知。 - Neo