Reputation: 304
I'm building a simple application whose purpose is to show a notification as soon as the app is launched.
Following the steps described by the Android's documentation, I wrote a method named createNotification
, which sets up the notification, and inserted a call to that method into onCreate
method, which is called few moments after the application is launched, I suppose.
Nevertheless, no notification shows up when the application is launched. I'm wondering what is wrong with the code.
public class MainActivity extends ActionBarActivity {
// ...
protected void onCreate(Bundle savedInstanceState) {
// ...
createNotification();
}
private void createNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setVisibility(Notification.VISIBILITY_PUBLIC);
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(1, builder.build());
}
}
Upvotes: 3
Views: 84
Reputation: 43314
See the docs
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()
If you add a smallIcon, for example android.R.drawable.ic_dialog_alert
it will work (I tested this just now). You can of course also add an icon of your own, but I used this because it is a builtin so easy for examples.
So like this
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setAutoCancel(true)
.setSmallIcon(android.R.drawable.ic_dialog_alert) // Add this line
.setWhen(System.currentTimeMillis())
.setVisibility(Notification.VISIBILITY_PUBLIC);
I must say that I find it weird it doesn't show an error or anything when you don't add a smallIcon.
Upvotes: 3