Android studio中Notification.setLatestEventInfo()方法被移除的问题

前言

今天看《第一行代码》看到使用前台服务章节,发现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);//执行intent
Notification notification = builder.getNotification();//将builder对象转换为普通的notification
startForeground(1,notification);//让 MyService 变成一个前台服务,并在系统状态栏中显示出来。

补充:

NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,notification);//运行notification

notification.flags |= Notification.FLAG_AUTO_CANCEL;//点击通知后通知消失

你可能感兴趣的:(Android studio中Notification.setLatestEventInfo()方法被移除的问题)