如何向通知(状态栏通知)添加标志?

4

我正在按照开发者指南中的教程进行学习,但是遇到了一个问题...

教程中提到:“为了在用户从通知窗口中选择它时清除状态栏通知,请将“FLAG_AUTO_CANCEL”标志添加到您的通知对象中”

但是...我该如何将该标志添加到我的通知中呢?

通知并没有任何添加标志的函数...那么我该怎么办呢?

3个回答

16

通知标志是一个公共成员字段。

Notification notif = new Notification(R.drawable.icon, shortMsg,
                System.currentTimeMillis());
notif.flags |= Notification.FLAG_AUTO_CANCEL;

new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) .setOnlyAlertOnce(true)... - Cristian

1

当您定义Intent时,标志放在末尾,就像这样:

PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notifyIntent, Notification.FLAG_AUTO_CANCEL);

3
“Notification.FLAG_AUTO_CANCEL”不应该放在那里。http://developer.android.com/reference/android/app/PendingIntent.html - Adam Stelmaszczyk
那么它应该放在哪里呢? :) - bofredo

0

以下是你可以尝试的代码,它是有效的。

public void notification(Context context,String title, String text) {
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(context)
        .setAutoCancel(true)
        .setSound(alarmSound)
        .setSmallIcon(R.drawable.appicon)
        .setContentTitle(title)
        .setContentText(text);

    Intent notificationIntent = new Intent(this,gps_get_data.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,                                           PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());
}

不要只是发布代码,解释你正在做什么以及如何解决问题。 - Iraniya Naynesh
如果您分享您的方法而不是代码,那么对于提问者来说会更有帮助,这样他就可以理解发生了什么。 - Sreeram TP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接