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
Related
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.
i am trying to generate notification. here i am facing problem with deprecated method for higher API level and when i am going to use Notification.Builder() then it gives error that
Call requires API level 11
here is my code
public void generateNotification(Context context, String message,String id) {
int icon = R.drawable.notiIcon;
String title = context.getString(R.string.app_name);
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification;
notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context,
NotificationViewActivity.class);
notificationIntent.putExtra("msg", message);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message,
intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//here i have Notification.Builder ... that gives error API leve
/*
notification = new Notification.Builder(context)
.setContentTitle(title).setContentText(message)
.setSmallIcon(icon).build();
*/
notificationManager.notify(id, notification);
}
how to resolve this problem .. because i require min version 8 and target 17.
Use NotificationCompat.Builder instead. From the standard support library v4.
By the way, the targetSdkVersion is not a problematic parameter in most of situations, no need to specify it in this problem. Just try to use the latest API all the time (and currently is 19).
There's nothing wrong with using deprecated methods, no harm in that.
Also, you can differentiate between the SDK levels with
if (android.os.Build.VERSION.SDK_INT > 10) {
}
else {
}
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)
Is possible create a permanent notification of battery level starting from this code?:
public void onCreate(Bundle savedInstanceState) {
...
this.registerReceiver(this.myBatteryReceiver , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
...
}
private BroadcastReceiver myBatteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
//here you can use level as you wish.
}
};
And this is an example of a notification.
private void CheckNoti(){
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
service.this);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Context");
notificationBuilder.setTicker("TickerText");
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setSmallIcon(R.drawable.ic_stat_icon);
Intent notificationIntent = new Intent(this, service.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(1,
notificationBuilder.build());
} }
I have to create a permanent notification with the battery level if possible. How can i do it?
Use the ongoing flags : http://developer.android.com/reference/android/app/Notification.Builder.html#setOngoing%28boolean%29
The user will not be able to cancel the notification so please don't forget to remove it when it's not useful anymore.
For toggle in it, you need to add a PreferenceActivity or a PreferenceFragment to your app. Then add a checkboxPreference : http://developer.android.com/guide/topics/ui/settings.html
In your code, you can now toggle this particular setting :
boolean permanent = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("permanent", false);
if(permanent) {
notificationBuilder.setOngoing(true);
}
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.