I created a notification to notify at some time. Now I want to delete a created notification before it is fired on some button click or any user action.
Below is the method handleNotification() which I call to create a notification
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);
}
Here is my Receiver class 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);
}
}
Here is my service class 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);
}
}
I tried below code but didn't worked
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
How can I achieve it. If it is not possible when notification is started from service then is there any other way to start a notification and also delete/cancel it even before firing.
0 comments:
Post a Comment