gpt4 book ai didi

android - 如何实现Notification的弃用方法

转载 作者:IT老高 更新时间:2023-10-28 21:47:48 26 4
gpt4 key购买 nike

我有一个小问题,但不明白如何解决这个问题。

我创建了一个用于提供通知的类,但这些行被标记为已弃用:

...
Notification notification = new Notification(icon, text, time); // deprecated in API level 11
...
notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11
...

替代方法是:

...
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build(); // available from API level 11 and onwards
...

我可以写一个类似的代码:

if(API_level < 11)
{
...
Notification notification = new Notification(icon, text, time); // deprecated in API level 11
...
notification.setLatestEventInfo(this, title, text, contentIntent); // deprecated in API level 11
...
}

else
{
...
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build(); // available from API level 11 and onwards
...
}

我提供的最低 sdk 版本为“8”。

编辑:

我确实喜欢以下内容:

int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB){

Notification notification = new Notification(icon, text, time);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TaskDetails.class), 0);

notification.setLatestEventInfo(this, title, text, contentIntent);

notification.flags |= Notification.FLAG_AUTO_CANCEL;

mNM.notify(NOTIFICATION, notification);
}
else
{
// what to write here
}

我可以为 else 部分写什么??

最佳答案

这就是我最终得到解决方案的方式:

if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {

notification = new Notification(icon, text, time);
notification.setLatestEventInfo(this, title, text, contentIntent); // This method is removed from the Android 6.0
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNM.notify(NOTIFICATION, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(text).setWhen(time)
.setAutoCancel(true).setContentTitle(title)
.setContentText(text).build();

mNM.notify(NOTIFICATION, notification);
}

编辑:

上述解决方案有效。尽管如此,由于引入了 NotificationCompat.Builder 类,我们可以跳过 if 条件来检查是否比较当前 API 版本。因此,我们可以简单地删除 if...else 条件,然后继续:

NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(text).setWhen(time)
.setAutoCancel(true).setContentTitle(title)
.setContentText(text).build();
mNM.notify(NOTIFICATION, notification);

关于android - 如何实现Notification的弃用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16852270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com