安卓的模拟系统为Android 4.0.3(API 15)。在调试Notification出现如下错误提示:
The method build() is undefined for the type Notification.Builder
出现错误的部分源码如下:
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
Notification notify = new Notification.Builder(this)
// 设置打开该通知,该通知自动消失
.setAutoCancel(true)
// 设置显示在状态栏的通知提示信息
.setTicker("有新消息")
// 设置通知的图标
.setSmallIcon(R.drawable.notify)
// 设置通知内容的标题
.setContentTitle("一条新通知")
// 设置通知内容
.setContentText("恭喜你,您加薪了,工资增加20%!")
// // 设置使用系统默认的声音、默认LED灯
// .setDefaults(Notification.DEFAULT_SOUND
// |Notification.DEFAULT_LIGHTS)
// 设置通知的自定义声音
.setSound(Uri.parse("android.resource://org.crazyit.ui/"
+ R.raw.msg))
.setWhen(System.currentTimeMillis())
// 设改通知将要启动程序的Intent
.setContentIntent(pi).build();
报错的位置位于左后一行:.setContentIntent(pi).build()
在网上查阅相关解决方法,有人说把android换成API17可解决这个问题,但本人没试过。
采用了网上的另一个方法:
http://stackoverflow.com/questions/19635081/the-method-build-is-undefined-for-the-type-notification-builder
将上述报错的源码进行如下更改即可正常运行:
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Notification notify = builder.setContentIntent(pi)
// 设置打开该通知,该通知自动消失
.setAutoCancel(true)
// 设置显示在状态栏的通知提示信息
.setTicker("有新消息")
// 设置通知的图标
.setSmallIcon(R.drawable.notify)
// 设置通知内容的标题
.setContentTitle("一条新通知")
// 设置通知内容
.setContentText("恭喜你,您加薪了,工资增加20%!")
// // 设置使用系统默认的声音、默认LED灯
// .setDefaults(Notification.DEFAULT_SOUND
// |Notification.DEFAULT_LIGHTS)
// 设置通知的自定义声音
.setSound(Uri.parse("android.resource://org.crazyit.ui/"
+ R.raw.msg))
.setWhen(System.currentTimeMillis())
// 设改通知将要启动程序的Intent
.setContentIntent(pi).build();
主要将报错源码的这一行:
Notification notify = new Notification.Builder(this)
更改为:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Notification notify = builder.setContentIntent(pi)
即可将错误清除!