[Android] Notification.setLatestEventInfo()方法被移除的问题

来源:互联网 发布:网络教育学位证好拿吗 编辑:程序博客网 时间:2024/05/16 09:41

前言

今天看《第一行代码》看到使用前台服务章节,发现Notification.setLatestEventInfo()报错,经过自己的摸索,发现此方法在 API23 中被移除,遂翻了一下API文档,发现可以用 Notification.Builder 来替代:

Notification.Builder 是什么?

Builder class for Notification objects. Provides a convenient way to set the various fields of a Notification and generate content views using the platform’s notification layout template. If your app supports versions of Android as old as API level 4, you can instead use NotificationCompat.Builder, available in the Android Support library.

Notification 的 Builder 类,提供了一个便捷的方式来设置 Notification,并使用平台的 notification 的 layout 模板生成 content views。如果您的 app 支持 Android API4 的老版本,你可以改用在Android的支持库中可用的 NotificationCompat.Builder。

Example:

Notification noti = new Notification.Builder(mContext)     .setContentTitle("New mail from " + sender.toString())     .setContentText(subject)     .setSmallIcon(R.drawable.new_mail)     .setLargeIcon(aBitmap)     .build();

然后调用 Notification.Builder 的

setContentTitle(CharSequence title);
setContentText(CharSequence text);
setSmallIcon(Icon icon);
setContentIntent(PendingIntent intent);

方法。

《第一行代码》中原代码如下:

Notification notification = new Notification(R.mipmap.iic_launcher,"Notification comes",System.currentTimeMillis());Intent notificationIntent = new Intent(this,MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);notification.setLatestEventInfo(this,"This is title","This is content",pendingIntent);startForeground(1,notification);

由于 Notification.setLatestEventInfo()方法的删除导致以上代码不能使用,现有如下方法可以替代,使用 Notification.Builder:

Notification.Builder builder = new Notification.Builder(this);//新建Notification.Builder对象Intent notificationIntent = new Intent(this, MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);builder.setContentTitle("This is title");//设置标题builder.setContentText("This is content");//设置内容builder.setSmallIcon(R.mipmap.ic_launcher);//设置图片builder.setContentIntent(pendingIntent);//执行intentNotification notification = builder.getNotification();//将builder对象转换为普通的notificationstartForeground(1,notification);//让 MyService 变成一个前台服务,并在系统状态栏中显示出来。

补充:

NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);manager.notify(1,notification);//运行notificationnotification.flags |= Notification.FLAG_AUTO_CANCEL;//点击通知后通知消失
0 0