The constructor is deprecated - android

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)

Related

Is there any Android notifications setContentTitle and setContextText magic values?

I'm currently working on a library with android support.
I'm being asked to notify user on foreground service start.
The notification must contain "ApplicationName" as title, and "ApplicationName is running" as text. The notification icon has to be the same as the launcher one.
The target API level is 26.
The notification did not work because the previous developper forgot to open the notification chanel. This is now fixed, we have the notification that pops correctly. And the label are matching expectation.
But now i'm questioning why the notification contains the expected values. I could not find any reference in the javadoc.
The following code will display the notification as expectecd the application's name as title and the text "ApplicationName is running" :
#Override
public void onCreate() {
NotificationChannel channel = new NotificationChannel("APPLICATION_CHANNEL", "MyService", NotificationManager.IMPORTANCE_LOW);
channel.setDescription(notificationChannelText);
//block below useful for head up notification
channel.setSound(null, null);
channel.setShowBadge(false);
channel.enableLights(false);
channel.enableVibration(false);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
foregroundNotification();
return Service.START_STICKY;
}
/**
* In order to start foreground service we and generate a service running notification.
*/
private void foregroundNotification() {
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, getClass());
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(context, "APPLICATION_CHANNEL")
.setContentTitle("Title")
.setContentText("Subject")
.setContentIntent(pendingIntent)
.build();
startForeground(42666, notification);
}
Why doesn't it just display a notification with "Title" as the title and "Subject" as content ?
Are there any constants or magic values that we have to know ?
Where can we find any documentation or definition about it ?
Edit 2020/04/01 : Added code representing notification channel creation
I found your problem. This is result of your code:
and after add small icon:
.setSmallIcon(R.mipmap.ic_launcher)
It works fine

Open app after clicking on Notification

I have a notification in my app with the following code:
public class NewMessageNotification {
private static final String NOTIFICATION_TAG = "NewMessage";
public static void notify(final Context context,
final String exampleString,final String boday ,final int number) {
final Resources res = context.getResources();
// This image is used as the notification's large icon (thumbnail).
// TODO: Remove this if your notification has no relevant thumbnail.
final Bitmap picture = BitmapFactory.decodeResource(res, R.drawable.billsms);
final String ticker = exampleString;
final String title = res.getString(
R.string.new_message_notification_title_template, exampleString);
final String text = boday;
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
// Set appropriate defaults for the notification light, sound,
// and vibration.
// Set required fields, including the small icon, the
// notification title, and text.
.setSmallIcon(R.drawable.billsms)
.setContentTitle(title)
.setContentText(text)
// All fields below this line are optional.
// Use a default priority (recognized on devices running Android
// 4.1 or later)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Provide a large icon, shown with the notification in the
// notification drawer on devices running Android 3.0 or later.
.setLargeIcon(picture)
// Set ticker text (preview) information for this notification.
.setTicker(ticker)
// Show a number. This is useful when stacking notifications of
// a single type.
.setNumber(number)
// If this notification relates to a past or upcoming event, you
// should set the relevant time information using the setWhen
// method below. If this call is omitted, the notification's
// timestamp will by set to the time at which it was shown.
// TODO: Call setWhen if this notification relates to a past or
// upcoming event. The sole argument to this method should be
// the notification timestamp in milliseconds.
//.setWhen(...)
// Set the pending intent to be initiated when the user touches
// the notification.
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")),
PendingIntent.FLAG_UPDATE_CURRENT))
// Show expanded text content on devices running Android 4.1 or
// later.
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(text)
.setBigContentTitle(title)
.setSummaryText("Dummy summary text"))
// Example additional actions for this notification. These will
// only show on devices running Android 4.1 or later, so you
// should ensure that the activity in this notification's
// content intent provides access to the same actions in
// another way.
.addAction(
R.drawable.ic_action_stat_share,
res.getString(R.string.action_share),
PendingIntent.getActivity(
context,
0,
Intent.createChooser(new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_TEXT, "Dummy text"), "Dummy title"),
PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(
R.drawable.ic_action_stat_reply,
res.getString(R.string.action_reply),
null)
// Automatically dismiss the notification when it is touched.
.setAutoCancel(true);
notify(context, builder.build());
}
#TargetApi(Build.VERSION_CODES.ECLAIR)
private static void notify(final Context context, final Notification notification) {
final NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
nm.notify(NOTIFICATION_TAG, 0, notification);
} else {
nm.notify(NOTIFICATION_TAG.hashCode(), notification);
}
}
/**
* Cancels any notifications of this type previously shown using
* .
*/
#TargetApi(Build.VERSION_CODES.ECLAIR)
public static void cancel(final Context context) {
final NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
nm.cancel(NOTIFICATION_TAG, 0);
} else {
nm.cancel(NOTIFICATION_TAG.hashCode());
}
}
}
My notifications fires very well, but my problem is that, when I click on notification in Notification Center, it does not start my app.
Basically, after clicking on my notification nothing happens!Thanks.
Basically your Pending Intent should have your application's one of the activity components.
Intent appIntent = new Intent(context, YourActivityName.class);
PendingIntent.getActivity(context, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Similarly you can add other components like Activity, Service and Receiver.
PendingIntent.getActivity ...
PendingIntent.getBroadcast ...
PendingIntent.getService ...
Hope this helps.
I found the answer to my question.
The only change this code :
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")),
PendingIntent.FLAG_UPDATE_CURRENT))
To this code :
.setContentIntent(
PendingIntent.getActivity(
context,
0,
new Intent(context.getApplicationContext(),MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT))

Notification "setContentInfo" not show up

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.

Cannot Resolve Method setLatestEventInfo

I am working on Notifications and I have to use setLatestEventInfo. However, Android Studio shows the following error message:
cannot resolve method setLatestEventinfo
Here is my code snippet:
private void createNotification(Context context, String registrationID) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,"Registration Successfull",System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(context,RegistrationResultActivity.class);
intent.putExtra("registration_ID",registrationID);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
notification.setLatestEventInfo(context,"Registration","Successfully Registered",pendingIntent);
}
Or if their is another way to do so, kindly suggest me that.
Well below is a simple example of working with Notifications, go through it, hope it helps!
MainActivity.java
public class MainActivity extends ActionBarActivity {
Button btnShow, btnClear;
NotificationManager manager;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialise();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
/*
//API level 8
Notification myNotification8 = new Notification(R.drawable.ic_launcher, "this is ticker text 8", System.currentTimeMillis());
Intent intent2 = new Intent(MainActivity.this, SecActivity.class);
PendingIntent pendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 2, intent2, 0);
myNotification8.setLatestEventInfo(getApplicationContext(), "API level 8", "this is api 8 msg", pendingIntent2);
manager.notify(11, myNotification8);
*/
}
});
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
private void initialise() {
btnShow = (Button) findViewById(R.id.btnShowNotification);
btnClear = (Button) findViewById(R.id.btnClearNotification);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/btnShowNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification" />
<Button
android:id="#+id/btnClearNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Notification" />
</LinearLayout>
And the activity that will be opened on click of Notification,
public class SecActivity extends Activity {
}
According to : https://developer.android.com/sdk/api_diff/23/changes/android.app.Notification.html
This method was removed in M (api 23). So if your compile SDK version is set to api 23+ you'll see this issue.
You write you have to use setLatestEventInfo. Does it mean you are ready to have your app not compatible with more recent Android versions? I strongly suggest you to use the support library v4 that contains the NotificationCompat class for app using API 4 and over.
If you really do not want to use the support library (even with Proguard optimization, using NotificationCompat will add a good 100Ko on the final app), an other way is to use reflection. If you deploy your app on an Android version that still has the deprecated setLatestEventInfo, first of all you should check if you are in such an environment, and then you use reflection to access the method.
This way, Android Studio or the compiler will not complain, since the method is accessed at runtime, and not at compile time. For instance :
Notification notification = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification();
notification.icon = R.mipmap.ic_launcher;
try {
Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);
deprecatedMethod.invoke(notification, context, contentTitle, null, pendingIntent);
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
Log.w(TAG, "Method not found", e);
}
} else {
// Use new API
Notification.Builder builder = new Notification.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(contentTitle);
notification = builder.build();
}
Go to project -> properties and set android-target 21

Dealing with Notifications on API 10 in Android

The code i'm putting in onCreate() is the following:
if(Build.VERSION.SDK_INT >= 11)
notifApiGT10();
else
notifApiLT10();
Where,
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void notifApiGT10() {
// TODO Auto-generated method stub
Notification.Builder builder ;
NotificationManager notifier;
builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setOngoing(true).setContentTitle("my Title").setContentText("my displayed text");
notifier = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT>=11 && Build.VERSION.SDK_INT<=15)
notifier.notify(1, builder.getNotification());
else if (Build.VERSION.SDK_INT > 15)
notifier.notify(1, builder.build());
}
private void notifApiLT10()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentText("is actually in use")
.setContentTitle("my Title")
.setOngoing(true)
.setTicker("my ticker")
.setSmallIcon(R.drawable.ic_launcher);
Notification notif = builder.getNotification();
NotificationManager mN = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mN.notify(1, notif);
}
The above code is not working on API 10. My device is running Gingerbread and it's not working on it.
I wonder why...Any experts?
SOLUTION:
Notification notification = new Notification(R.drawable.ic_launcher, "my ticker", System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
Intent i = new Intent(this,Main.class);
PendingIntent pd = PendingIntent.getActivity(this, 1, null, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(context, "my title", "my text", pendingintent);
NotificationManager mN = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mN.notify(1,notification);
The above solution solved my problem,
even if you don't want to run anything on click, you should put the pendingintent inside the method setLatestEventInfo, but in pd as you noticed, in the 3rd field, i have set the intent to null
Have you tried using NotificationCompat.Builder.build()? NotificationCompat.Builder.getNotification() is deprecated.
FYI, last time I used NotificationCompat.Builder, setNumber() did not work properly and I ended up constructing Notification directly on older devices.
EDIT: Try using Notification class directly on older devices because NotificationCompatImplBase (API <= 10) uses only 4 fields from the builder no matter how many are set.

Categories

Resources