I'm using Android Studio. I wanna add message with number of notifications. Why when I run app there is no content info on the screen?
>
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void notyfikacja(View view) {
Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentInfo("You have"+ ++i + "messages" )
.setContentText("ContentText")
.setContentTitle("ContentTitle")
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification = builder.build();
NotificationManagerCompat.from(this).notify(0, notification);
}
I add the Notification Screeshot
I am not sure about why the setContentInfo doesn't work. Probably cause you are trying in Nougat ? Anyways, according to the documentation, it is recommended to use setSubText(CharSequence) instead of setContentInfo(CharSequence info)
From Doc:
This method was deprecated in API level 24. use setSubText(CharSequence) instead to set a text in the header. For legacy apps targeting a version below N this field will still show up, but the subtext will take precedence.
Related
I want to run background location service. It works more or less, however - instead of my custom notification with text and content intent, generic notification is shown. Why is that?
I am using Nexus API 28 emulator.
Service starting method:
private void moveToRunningState() {
Intent serviceStartIntent = new Intent(getApplicationContext(), this.getClass());
int requestId = 1;
Intent goToMainScreenIntent = new Intent(getApplicationContext(), MainActivity.class);
serviceStartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent onTapIntent = PendingIntent.getActivity(getApplicationContext(), requestId, goToMainScreenIntent, 0);
Notification.Builder builder = NotificationUtils.notificationBuilderO(this);
builder.setContentTitle("Location tracking is running");
builder.setContentText("Your location is beeing sent to the server so it can be shown on map");
builder.setFullScreenIntent(onTapIntent, true);
builder.setProgress(0,100,true);
if (NotificationUtils.isPreAndroidO()) {
Log.d(TAG, "moveToStartedState: Running on Android N or lower - startService(intent)");
startService(serviceStartIntent);
} else {
Log.d(TAG, "moveToStartedState: Running on Android O - startForegroundService(intent)");
startForegroundService(serviceStartIntent);
}
startForeground(1, builder.build());
Log.i(TAG, "Service moved to start state");
isRunning = true;
}
Just in case, builder creation
public static Notification.Builder notificationBuilderO(Context ctx) {
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(UUID.randomUUID().toString(), "Geoloc channel", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
Notification.Builder builder = new Notification.Builder(ctx, notificationChannel.getId());
return builder;
and actual result:
As usual, I had to post question on SO only to find answer myself seconds afterwards.
The problem is, that I am not setting notification icon. I have tried to show the same notification using NotificationManager and it failed with explainatory exception saying that this icon is not set. This exception is not shown in logs in my case when using startForeground
All in all, setting icon fixes the issue.
I have an app that kicks off a notification on a Wear device (the notification is created and shown on the Wear device).
What I want to do is have the "first" notification page display some high level info (app name, scroll to see more, etc...), and then have a list of pages containing content after that.
That works fine. The issue is that I want to attach an Action to each page (to kick off a PendingIntent). However, no matter what I try, I can't get the page to perform the Action.
I've tried:
setContentIntent
addAction
addAction and extend(new Notification.WearableExtender().setContentAction(0))
Anyone have any ideas?
I'm using Notification, not NotificationCompat, but I don't think that should make a difference.
UPDATE: I'm creating the notification on the watch. Here is the code I use:
private void createNotifications(ArrayList<Thing> things) {
DataApi data = Wearable.DataApi;
int notificationId = 0;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder mainBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.default_icon)
.setContentTitle("Things")
.setContentText("Swipe to see your things")
.setPriority(Notification.PRIORITY_DEFAULT);
List<Notification> pages = new ArrayList<>(things.size());
for(Thing thing : things) {
pages.add(createNotificationPageForThing(data, thing, notificationId).build());
notificationId++;
}
Notification n = new Notification.WearableExtender().addPages(pages).extend(mainBuilder).build();
nm.notify(notificationId, n);
}
private Notification.Builder createNotificationPageForThing(DataApi data, Thing thing, int notificationId) {
Asset bitmapAsset = getBitmapAsset(data, contact);
Intent thingIntent = new Intent(this, WearDetailActivity.class);
thingIntent.putExtra(WearDetailActivity.DETAIL_EXTRA, thing);
PendingIntent thingPendingIntent = PendingIntent.getActivity(this, notificationId, thingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Action action = new Notification.Action(R.drawable.ic_action_social_person, "More details", thingPendingIntent);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_action_social_person)
.setContentTitle(thing.getDisplayName())
.setPriority(Notification.PRIORITY_DEFAULT)
.addAction(action)
.extend(new Notification.WearableExtender().setContentAction(0));
if(bitmapAsset != null) {
try {
Bitmap b = BitmapFactory.decodeStream(
data.getFdForAsset(connection.getClient(), bitmapAsset).await().getInputStream());
builder.setLargeIcon(b);
} catch (Throwable ignore) {}
}
return builder;
}
#Eliezer, reading at the following line I did not understand what exactly is the behaviour you're experiencing ... explaining it in details might be helpful to debug your problem.
However, no matter what I try, I can't get the page to perform the Action.
Using .addAction() should work in your case. You'd want to use WearableExtender if you were creating the notification from the device, not the watch itself. Just to confirm something obvious - you're passing the .addAction a PendingIntent right?
Here's a code snippet from one of my applications, which accomplishes exactly what you're aiming for - I have just "Swipe for actions" text in the first page, and the next 2 pages perform different actions.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Intent openIntent = new Intent(this, CommonWearIntentService.class);
openIntent.setAction(CommonWearIntentService.ACTION_OPEN_ON_PHONE);
PendingIntent openPendingIntent = PendingIntent.getService(this, 0, openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent addTransactionIntent = new Intent(this, CommonWearIntentService.class);
addTransactionIntent.setAction(CommonWearIntentService.ACTION_ADD_TRANSACTION);
PendingIntent addTransactionPendingIntent = PendingIntent.getService(this, 0, addTransactionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.swipe_for_actions))
.addAction(R.drawable.add_transaction, getString(R.string.add_transaction), addTransactionPendingIntent)
.addAction(R.drawable.common_full_open_on_phone, getString(R.string.common_open_on_phone), openPendingIntent)
.setVibrate(new long[]{500, 500, 500, 1000})
.setLights(Color.BLUE, 3000, 3000)
.setOngoing(true);
notificationManager.notify(ONGOING_NOTIFICATION_ID, builder.build());
Hope this helps!
Per the documentation, you must use NotificationCompat. After you switch to that setContentIntent() looks to be the right way to set the PendingIntent.
Example from the linked docs:
// Create builder for the main notification
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.new_message)
.setContentTitle("Page 1")
.setContentText("Short message")
.setContentIntent(viewPendingIntent);
// Create a big text style for the second page
BigTextStyle secondPageStyle = new NotificationCompat.BigTextStyle();
secondPageStyle.setBigContentTitle("Page 2")
.bigText("A lot of text...");
// Create second page notification
Notification secondPageNotification =
new NotificationCompat.Builder(this)
.setStyle(secondPageStyle)
.build();
// Add second page with wearable extender and extend the main notification
Notification twoPageNotification =
new WearableExtender()
.addPage(secondPageNotification)
.extend(notificationBuilder)
.build();
// Issue the notification
notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, twoPageNotification);
I make one android application.In my code in my java class I get some message: "The constructor Notification(int, CharSequence, long) is deprecated". Everything is ok with Application I don't have problem when I try to run the Application.
I just want to know why this message is showing up.
My code in my java class is:
public class Notifications extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notifications);
Button b = (Button) findViewById(R.id.bNotifications);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification(
android.R.drawable.stat_notify_more,
"This is important", System.currentTimeMillis());
Context context = Notifications.this;
CharSequence title = "You have been notified";
CharSequence details = "Continue with what you have doing";
Intent intent = new Intent();
PendingIntent pending = PendingIntent.getActivity(context, 0,
intent, 0);
notify.setLatestEventInfo(context, title, details, pending);
nm.notify(0, notify);
}
});
}
}
Have a look at the documentation:
public Notification (int icon, CharSequence tickerText, long when)
Added in API level 1
This constructor was deprecated in API level 11.
Use Notification.Builder instead.
As far as I can tell, this would be the corresponding call to Notification.Builder:
Context context = Notifications.this;
Notification notify = new Notification.Builder(context)
.setTicker("This is important")
.setSmallIcon(android.R.drawable.stat_notify_more)
.setWhen(System.currentTimeMillis())
.build();
As you can see, Notification.Builder offers more flexibility in setting the various notification properties and improves code readability, which might be the reason why the Notification constructor was deprecated.
Sometimes the fact that a method is deprecated doesn't mean that you won't need it nor make use of it. So, after all, you need to support older devices (not the oldest like Android Donut or previous) and you will need to use the new way and the deprecated way. In this case, I've implemented as follows:
Notification notification;
String title = context.getString(R.string.app_name);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN){
notification = new Notification(icon, message, when);
}else{
notification = new Notification.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.build();
}
Hope that it helps!
Since API level 11 Notification(int icon, CharSequence tickerText, long when) is no longer advised to be used as there exists an alternative to this. Use Notification.Builder instead.
Source: http://developer.android.com/reference/android/app/Notification.html#Notification(int, java.lang.CharSequence, long)
I'm playing around notifications in android, and I'm wondering why NotificationCompat doesn't display Large Icon, and Number in Gingerbread as it does in Jellybean (see pics), I thought that was for that purpose that it was created ?
here is how I fire the notifications :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnShow = (Button)findViewById(R.id.btnNotif);
Intent intent = new Intent(this, NotificationReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setWhen(System.currentTimeMillis())
.setContentText("You are near your point of interest.")
.setContentTitle("Proximity Alert!")
.setSmallIcon(android.R.drawable.ic_menu_info_details)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.orchide))
.setAutoCancel(true)
.setTicker("Proximity Alert!")
.setNumber(10)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_VIBRATE| Notification.DEFAULT_SOUND);
/*Create notification with builder*/
notification=notificationBuilder.build();
/*sending notification to system.Here we use unique id (when)for making different each notification
* if we use same id,then first notification replace by the last notification*/
btnShow.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
notificationManager.notify(1000, notification);
}
});
}
Large icon is ignored on pre-honeycomb API levels.
NotificationCompat.Builder documentation says:
...On platform versions that don't offer expanded notifications, methods that depend on expanded notifications have no effect...
If you look at the NotificationCompat.Builder source you'll see that large icon is used for honeycomb and above.
I am using the below code to generate the notification in my application
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
notifManager = (NotificationManager) mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
mNotification = new NotificationCompat2.Builder(mContext).setSmallIcon(android.R.drawable.sym_def_app_icon)
.setTicker("Launch download").setContentTitle("Downloader").setContentText(content)
.setContentIntent(getPendingIntent());
mNotification.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mNotification.setAutoCancel(true);
notifManager.notify(UPDATE_PROGRESS, mNotification.build());
}
private PendingIntent getPendingIntent() {
Intent i = new Intent(mContext, NotificationReceiver.class);
//i.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
return PendingIntent.getActivity(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
}
Note:- I am using NotificationCompat2 by Jake Wharton.
Now this code works fine except when a new a Notification arrives it dismisses the old notification even if it is not read by the user.
My Question
How to show all the notification in the status slidingdrawer till it is not read by the user?
A notification will be replaced by another if they have the same id. Change the id in
notifManager.notify(id, mNotification.build());
to display several notifications.