我遇到了问题,我想为我的应用发出通知。首先我建立一个通知然后如果我不想要它然后我想再次删除它。 我怎么能这样做,我可以删除一个特定的通知
我从setOnItemLongClickListener开始这个建筑。
Mainactivity:
if (isNotificationVisible()){
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1122334455);
}
else {
int beginday = begincalendar.get(Calendar.DAY_OF_MONTH);
int beginyear=begincalendar.get(Calendar.YEAR);
int beginmonth=begincalendar.get(Calendar.MONTH);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
myIntent.setAction(String.valueOf(id));
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, begincalendar.getTimeInMillis(), pendingIntent);
}
NotificationService类:
public class NotificationService extends Service {
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setOnlyAlertOnce(true)
.setContentText("context")
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1122334455, mBuilder.build());
}
}
AlarmReceiver类:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, NotificationService.class);
context.startService(service1);
}
}
isNotificationVisible:
private boolean isNotificationVisible() {
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent test = PendingIntent.getActivity(context, 1122334455, notificationIntent, PendingIntent.FLAG_NO_CREATE);
return test != null;
}
答案 0 :(得分:0)
使用NotificationManager的public void cancel(int id)方法清除通知。
假设您想要在按钮上单击取消此通知,请在onClick()方法中添加以下代码,
mNotificationManager.cancel(1122334455); // parameter is your notification ID
有关详细信息,请参阅here.