我有一个可能会显示通知的服务,问题是一旦设置了通知,它既不会在点击时清除,也不会在刷卡时清除。我正在使用标志Notification.FLAG_AUTO_CANCEL
,但它似乎没有做任何事情......
private NotificationManager nm;
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
private final int NOTIFY_ID = 1;
private void showNotification(String date, String name) {
try{
CharSequence text = "You have new Event";
Notification notification = new Notification(R.drawable.small_icon, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, viewEvents.class).putExtra("date", date), 0);
notification.setLatestEventInfo(this, name, "Date: "+date, contentIntent);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.FLAG_AUTO_CANCEL;
nm.notify(NOTIFY_ID, notification);
}catch(Exception e){
Log.i("Notification",e.toString());
}
}
那么我做错了什么?
答案 0 :(得分:3)
尝试使用Notification.Builder
或NotificationCompat.Builder
,而不是手动滚动Notification
。
除此之外,这可以防止代码中的错误,您将FLAG_AUTO_CANCEL
应用于defaults
而不是flags
。
答案 1 :(得分:0)
Notification.FLAG_AUTO_CANCEL
已在您的代码中注释掉。
但是如果不是,那么应该在notification.defaults中设置标志Notification.DEFAULT_LIGHTS
而不是在notification.flags中
答案 2 :(得分:0)
我使用此代码显示/隐藏通知:
private Handler handler = new Handler();
private Runnable task = new Runnable() {
@Override
public void run() {
NotificationManager manager = (NotificationManager) contesto.getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(contesto.getApplicationContext(), SearchHistory.class);
PendingIntent contentIntent = PendingIntent.getActivity(contesto.getApplicationContext(), 0, launchIntent, 0);
//Create notification with the time it was fired
NotificationCompat.Builder builder = new NotificationCompat.Builder(contesto);
builder.setSmallIcon(R.drawable.ic_launcher).setTicker("MESSAGE HERE!").setWhen(System.currentTimeMillis()).setAutoCancel(true).setDefaults(Notification.DEFAULT_SOUND).setContentTitle("TITLE").setContentText("MESSAGE").setContentIntent(contentIntent);
Notification note = builder.build();
manager.notify(100, note);
}
};
并调用刚放入:
handler.post(task);