How to show notification in status bar?

2019-04-30 05:02发布

问题:

So i have created this notification in my activity

Notification n = new Notification.Builder(getApplicationContext())
    .setContentTitle("New mail from " + sender)
    .setContentText(subject)
    .setSmallIcon(R.drawable.notification)
    .build();

How can i now show it in status/notification bar along with the sound?

回答1:

There is some good documentation at android developer site and have a look at the NotificationManager doc's

Here you go, some code...:

NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, n);

Note that it is also a goo idea to add your intend to the notification...

mBuilder.setContentIntent(resultPendingIntent);

To add sound you can use the Notification.Builder.setSound() method.



回答2:

How can i now show it in status/notification bar along with the sound?

Use the Notification.Builder.setSound() method.

You can get the default ringtone like this:

Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

and then set it as notification sound:

Notification.Builder(getApplicationContext()).setSound(uri);

and then after you've built your notification you launch it with:

myNotificationManager.notify(myNotificationId, n);