How to create Multiple statusbar Notifications in android

老子叫甜甜 提交于 2019-11-27 14:20:53

You need to pass a unique ID to each notification. Once you have clicked on the notification you use that ID to remove it.

public class SimpleNotification extends Activity {

    private NotificationManager mNotificationManager;
    private int SIMPLE_NOTFICATION_ID_A = 0;
    private int SIMPLE_NOTFICATION_ID_B = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Button start = (Button) findViewById(R.id.start_button);        

        start.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // display A
                displayNotification("Extra for A", "This is A", "Some text for activity A", MyActivityA.class, SIMPLE_NOTFICATION_ID_A);
                // display B
                displayNotification("Extra for B", "This is B", "Some text for activity B", MyActivityB.class, SIMPLE_NOTFICATION_ID_B);
            }
        });
    }

    private void displayNotification(String extra, String contentTitle, String contentText, Class<?> cls, int id) {     
        Notification notifyDetails = new Notification(R.drawable.icon, "New Alert!", System.currentTimeMillis());
        Intent intent = new Intent(this, cls);
        intent.putExtra("extra", extra);
        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), id, intent, PendingIntent.FLAG_ONE_SHOT);
        notifyDetails.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);
        mNotificationManager.notify(id, notifyDetails);
    }
}

MyActivityA - in onCreate()

...
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID_A);
...

Just use different IDs on mNotificationManager.notify(ID, notifyDetails);

If you reuse the ID it will not add a new one, instead the old will be updated.

Here is a guide on how to use notifications.

you have to chnage the notfication id because it's all time not the solution is that you have to use ramdom number concept

Random random = new Random();
int randomNumber = random.nextInt(9999 - 1000) + 1000;
notificationManager.notify(randomNumber, notification);
Sanath

This example shows how to create multiple Notification

g4gaj

If you want to show different data on each notification. Use the Flag FLAG_UPDATE_CURRENT in your pending Intent.

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

It updates the data on every notification, without having to recreate it each time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!