我正在尝试在Android中安排Future的通知。但它现在就给我通知了。
scheduleNotification Method。
private void scheduleNotification(Notification notification, long delay) {
Intent notificationIntent = new Intent(getContext(), NotificationReceiver.class);
notificationIntent.putExtra(Constants.TimeTableTasksNotification.NOTIFICATION_ID, 1);
notificationIntent.putExtra(Constants.TimeTableTasksNotification.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = delay - (new Date()).getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(futureInMillis);
Toast.makeText(context, "" + futureInMillis, Toast.LENGTH_SHORT).show();
Toast.makeText(context, "" + minutes, Toast.LENGTH_SHORT).show();
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
getNotification方法。
private Notification getNotification(String message) {
Notification.Builder builder = new Notification.Builder(getContext());
builder.setContentTitle("Time To do the Task.");
builder.setContentText(message);
builder.setSmallIcon(R.drawable.logo);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
builder.setLights(Color.BLUE, 3000, 3000);
return builder.build();
}
我将此格式的日期作为字符串日期。
String inputDate = "09/05/2017 10:20";
使用下面的代码我得到的时间是毫秒。
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ENGLISH);
try {
Date date = simpleDateFormat.parse(inputDate);
long milliSeconds = date.getTime();
scheduleNotification(getNotification("Notification Title."), milliSeconds);
} catch (ParseException e) {
Log.d("DialogAddScheduleTask", e.getMessage());
e.printStackTrace();
}
和最后这是我的NotificationReceiver类
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(Constants.TimeTableTasksNotification.NOTIFICATION);
int id = intent.getIntExtra(Constants.TimeTableTasksNotification.NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
所有东西也都在Manifest中。我添加了权限,并且我也注册了我的接收器。
但无法弄清楚为什么它确实及时给我通知。
答案 0 :(得分:0)
答案 1 :(得分:0)
检查futureInMillis的值