用户通过启动器图标

时间:2016-05-16 08:41:21

标签: android push-notification sms launcher

您好我正在开发一个应用程序,我希望在收到Sms时向用户发送推送通知。现在的问题是当用户通过启动器图标打开应用程序时,通知图标仍然不会被删除 这是我的代码:

NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
            notify.setSmallIcon(R.drawable.appicon);
            notify.setContentTitle(title);
            notify.setContentText(msgBody);
            notify.setAutoCancel(true);
            Notification notification = new Notification();
            notification.defaults |= Notification.DEFAULT_VIBRATE;

            //notify.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
            notify.setLights(Color.GREEN, 2000, 2000);
            notify.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
            notificationIntent.addCategory(Intent.CATEGORY_DEFAULT);
            notificationIntent.setType("vnd.android-dir/mms-sms");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent intentt = PendingIntent.getActivity(context, 0,notificationIntent, 0);
            notify.setContentIntent(intentt);
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notify.build());

我也是这样尝试的:

notificationManager.cancel(0);

并尝试了这个:

notificationManager.cancelAll();

但这些都不起作用。它们不允许发生通知。也许他们在创建之前取消了推送通知。 请帮助!

1 个答案:

答案 0 :(得分:11)

只需取消主要活动onCreate()方法

中的所有通知
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

那是因为你问了

  

用户通过启动器图标

打开应用时删除通知图标

但最好的方法是将其放在onResume()中,以便当应用在后台时,您希望显示通知并在用户将其置于前台时将其删除。

@Override
protected void onResume() {
    super.onResume();

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}