Show notification in Android 5.0.1 - java

I want to create a Notification in my Android App, but my code doesn't work!
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder nBuilder = new Notification.Builder(this);
nBuilder.setContentTitle("Title...");
nBuilder.setContentText("Text...");
nBuilder.setContentInfo("Info?");
nBuilder.setWhen(System.currentTimeMillis());
//Intent notificationIntent = new Intent(this, MainActivity.class);
//PendingIntent pendingIntent = new PendingIntent.getActivity(this, 0, notificationIntent, 0);
nManager.notify(noti_ID, nBuilder.build());
Thanks :)

From developer.android.com
Required notification contents
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
So set a small icon too.

Related

Notification doesn't show all action buttons

I'm trying to create a simple notification for a music player that has 3 buttons, Pause, Previous and Next. My code only shows one of them which is Next. Any suggestions where I did a mistake?
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent playNextIntent = new Intent(this, BroadcastReceiver.class);
playNextIntent.setAction("NEXT_ACTION");
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 1, playNextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, BroadcastReceiver.class);
pauseIntent.setAction("PAUSE_ACTION");
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 2, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent playPreviousIntent = new Intent(this, BroadcastReceiver.class);
playPreviousIntent.setAction("PREVIOUS_ACTION");
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 3, playPreviousIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "D")
.setSmallIcon(R.drawable.ic_launcher_background) //notification icon
.setContentTitle("Simple Music Player")
.setContentText("Currently playing: " + mediaPlayerHolder.getSongsList().get(songIterator).getSongName())
.setPriority(NotificationCompat.PRIORITY_MAX)
.setWhen(0)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true) //user can't remove notification
.addAction(R.drawable.ic_previous, "Previous", prevPendingIntent) // #0
.addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) // #1
.addAction(R.drawable.ic_next, "Next", nextPendingIntent) // #2
.setStyle(new NotificationCompat.BigTextStyle())
.setContentIntent(pendingIntent); //on click go to app intent
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, mBuilder.build()); //show notification
There's nothing wrong with your code. If you run your code in an emulator on stock android the actions show up as expected.
On Android displaying notifications is done by the launcher. Like any other app launchers can contain bugs. In this case there is a bug in the launcher you're using to display multiple actions in a notification.
I recommend you to try a google sample Universal Music player Here is a GitHub link . It includes all of you want in notifications and it has a latest notification Android Oreo features just try out it .

Notification in Nougat

I have two problem with my app:
1. I don't know how to retrieve the color of the small icon of notification when a notification arrives?
2. Can I edit app name that displayed at top of the notification by programmatically?
I'm using android Nougat .
You can use the below code to set smallIcon :(Use Small icon same color as Title Color)
Change color by this site
.setSmallIcon(R.drawable.ic_launcher_icon)
Reference Code :
private void sendNotification(String messageBody,String message2, Bitmap image, String TrueOrFalse) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// .setLargeIcon(image)/*Notification icon image*/
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher_icon))
.setSmallIcon(R.drawable.ic_launcher_icon)
.setContentTitle(messageBody)
.setContentText(message2)
.setColor(getResources().getColor(R.color.colorAccent))
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
This API seems to allow custom title and icon: https://developer.android.com/reference/android/app/Notification.Builder.html

Notifications Builder in android 2.3

Pretty new in android here :)
I have a notification builder which works with no problem if the application target version is > 4.0
However when I switch to 2.3 I get an error on this line which says "Notificaiton.Builder cannot be resolved to a type".
Notification notification = new Notification.Builder(this)
.setSmallIcon(drawable_small)
.setLargeIcon(drawable_big)
.setWhen(System.currentTimeMillis()).setTicker(content_title)
.setContentTitle(content_title).setContentInfo(content_info)
.setContentText(content_text).setContentIntent(pIntent)
.getNotification();
This problem is now solved!
However I`m having another one now
It gives me an error on every R (resource) and I have the option to Import R.
If I import it,its giving me errors on every resource.
setContentView(R.layout.activity_main);
Implement your Notification like
Notification noti = new NotificationCompat.Builder(context)
.setSmallIcon(icon_small)
.setTicker(message)
.setLargeIcon(largeIcon)
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setContentText(message)
.setContentIntent(contentIntent)
//At most three action buttons can be added
.setAutoCancel(true).build();
And add support library v4 into your project and also import
import android.support.v4.app.NotificationCompat;
NotificationCompat helper for accessing features in Notification introduced after API level 4 in a backwards compatible fashion.
For more information go to:http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Try this :
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, 0);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify(0 , notification);
}
Hope this helps.
Add the v4 support library to your project by right-clicking your project, then choosing Android Tools > Add support library
Change to NotificationCompat.Builder
NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launcher,
"New Message",
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Got new Message";
String notificationText = "";
Intent myIntent = new Intent(MainActivity.this,MainActivity.class);
PendingIntent pendingIntent
= PendingIntent.getActivity(MainActivity.this, 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
n.defaults |= Notification.DEFAULT_SOUND;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(1,n);
Hope this works out:)
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(getApplicationContext(), MYDEMOACTIVITY.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MYDEMOACTIVITY.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
And add support library v4 into your project and also import
import android.support.v4.app.NotificationCompat;

make notification clickable and undestroyable

I tried to create a notification that starts a activity by clicking on it and which you can't swipe away.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("DroidSchool")
.setContentText("DroidSchool l\u00E4uft im Hintergrund...");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_FROM_BACKGROUND);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mId = 1234567890;
mNotificationManager.notify(mId, mBuilder.build());
with the code above the notification gets displayed, but nothing happens when I click on it and you can swipe it away.
To keep the Notification, in that way the user can't click it away in any way, add this flag
Notification mNotification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(mId, notification);
To start an Activity you have to use this flag for your Intent
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Do like this:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("DroidSchool")
.setContentText("DroidSchool l\u00E4uft im Hintergrund...");
Intent intent = new Intent(YourActivity.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification noti = mBuilder.build();
noti.flags |= mBuilder.build().FLAG_NO_CLEAR | mBuilder.build().FLAG_ONGOING_EVENT;
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, noti);
You want a foreground service as detailed here
It's worth noting that only android 4.3 added the persistent notification you seem to be after and it can be overriden by the users settings.
try using like this
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_UPDATE_CURRENT);
in MainActivity.java
Dont not consume your notification; ie instead of calling below 2 line code in oncreate() call under onDestro()
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(mId);
You can use NotificationCompat.Builder's .setOngoing(true), use it like this:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setContentTitle("Downloading Something")
.setContentText("Downloading")
.setSound(null)
.setDefaults(0)
.setOngoing(true);
// Makes it so the notification is clickable but not destroyable by swiping-away or hitting "clear all"

Android - Why Activity is Open after click notification?

I have a function to display a notification, which I call from various activities.
public static void CrearNotificacion(Context pContexto, String pTituloBarra, String pTitulo, String pTexto){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) pContexto.getSystemService(ns);
Notification notification = new Notification(R.drawable.icono, pTituloBarra, System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
Intent notificationIntent = new Intent(pContexto, pContexto.getClass());
PendingIntent contentIntent = PendingIntent.getActivity(pContexto, 0, notificationIntent, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(pContexto, pTitulo, pTexto, contentIntent);
mNotificationManager.notify(1, notification);
}
works perfect, the problem is that pressing on the notification opens the activity that created the notification and that's wrong, I think the notiifcacion activity should not open when I select the notification.
Why? there any way to fix this?
I do not want to open any activity when I select the notification.
thanks from now.
In order to have no action taken when clicking the notification, you may set an empty Intent as follows:
Intent notificationIntent = new Intent() ;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
Intent notificationIntent = new Intent(pContexto, pContexto.getClass());
i guess this is the line you have to change with
Intent notificationIntent = new Intent(pContexto, yourClass.class);

Categories