我正在尝试创建一个设置页面,用户可以在其中设置通知的时间。
我有时间以这种方式使用时间选择器:
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
mTimePicker = new TimePickerDialog(Impostazioni.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
ViewOra.setText( selectedHour + ":" + selectedMinute);
ora=selectedHour; minuti=selectedMinute;
setNotifiche(selectedHour,selectedMinute); //i call the method set notification
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
Intent notifiche = new Intent(Impostazioni.this , Notifiche.class);
这是我创建警报管理器的方法setNotification
public void setNotifiche(int h,int m) {
int hour=h; int minute=m;
Intent myIntent = new Intent(this , Notifiche.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(Impostazioni.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);
}
最后这是Notifiche.class服务,我把通知发送到了:
public void onCreate() {
Toast.makeText(this, "Notifiche", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,Impostazioni.class);
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Test").setContentText("Attempt n1").setContentIntent(pending);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
}
代码似乎有用,我的意思是当我在应用程序中午餐并在设置页面中设置特定时间时,但是如果我尝试再次设置则没有任何反应。我哪里错了?
答案 0 :(得分:0)
进行两项更改并检查其是否有效: 在setNotifiche
中PendingIntent pendingIntent = PendingIntent.getService(Impostazioni.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
在服务中
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT );
如果有效,请将其标记为正确。
答案 1 :(得分:0)
它也可能与你选择的ID有关。如果已存在您的ID 0的通知并且已创建另一个ID 0的通知,则不会播放新的通知声音。您必须先取消现有通知,或使用其他ID。考虑:
int id = new Random().nextInt(1000);
notify(id, mBuilder.build());