如何在自定义时间开始通知?

时间:2012-01-30 12:14:23

标签: android calendar notifications

我想在特定日期和时间在android中设置我的通知,我在java中使用日期尝试它,但我的通知在时间之前被触发。那么我可以在指定的时间内解雇它。提前致谢!

以下是我的通知代码:

Calendar cal = java.util.Calendar.getInstance();
cal.set(2012, 00, 30);
Date date = cal.getTime();
date.setHours(17);
date.setMinutes(30);
date.setSeconds(15);

long time = date.getTime();

Log.e("date is",""+date);
long when = time;


Notification notification = new Notification(notificationIcon,tickerText,date.getTime());

notification.when = date.getTime();

RemoteViews contentView = new RemoteViews("com.LayoutDemo",R.layout.userscreen);        
notification.contentView= contentView;
Intent intent = this.getIntent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.contentIntent= contentIntent;

notification.flags= Notification.FLAG_AUTO_CANCEL;

int NOTIFICATION_ID =1;             
nManager.notify(NOTIFICATION_ID,notification);

2 个答案:

答案 0 :(得分:4)

通知字段“when”用于对状态栏中的通知进行排序。它不用于在指定时间触发通知。

如果要在指定时间触发操作,请使用AlarmManager:http://developer.android.com/reference/android/app/AlarmManager.html

答案 1 :(得分:2)

使用Android闹钟服务并设置待定意图

Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
       AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
       Calendar calendar = Calendar.getInstance();
       calendar.setTimeInMillis(System.currentTimeMillis());
       calendar.add(Calendar.SECOND, 10);
       alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);