我在某个时候创建了通知。现在,我希望在某些按钮点击或任何用户操作触发之前删除已创建的通知。
以下是我打电话来创建通知的方法handleNotification()
private void handleNotification() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, selYear);
calendar.set(Calendar.MONTH, selMonthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, selDayOfMonth);
calendar.set(Calendar.HOUR_OF_DAY, selHourOfDay);
calendar.set(Calendar.MINUTE, selMinute);
calendar.set(Calendar.SECOND, 00);
Intent alarmIntent = new Intent(getActivity(), MyReceiver.class);
alarmIntent.putExtra("when", calendar.getTimeInMillis());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, alarmIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
这是我的Receiver课程 MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyService.class);
service1.putExtra("when", intent.getIntExtra("when",0));
context.startService(service1);
}
}
这是我的服务类 NotificationService.java
public class MyService extends Service {
public static Context context;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
NotificationService.context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int when = intent.getIntExtra("when", 0);
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setContentText("message")
.setAutoCancel(true)
.setWhen(when)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(id), mBuilder.build());
return super.onStartCommand(intent, flags, startId);
}
}
我尝试了以下代码,但没有工作
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
我怎样才能实现它。如果从服务开始通知是不可能的,那么还有其他方法可以启动通知,甚至在解雇之前也可以删除/取消通知。
答案 0 :(得分:0)
(仅为正当): 当您不希望显示通知时,请禁用alarmManager。 : - )