02-24 10:05:24.731: E/AndroidRuntime(1577): java.lang.NoSuchMethodError: android.app.Notification$Builder.build
错误原因:(详见代码第51行)
Notification.Builder(context).build();方法不存在
解决方案:(详见代码第51行)
将Notification.Builder改为 NotificationCompat.Builder(import android.support.v4.app.NotificationCompat;)
package com.zml.notification;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.zml.practice.R;
/**
* @author zml2015
* @Time:2016-2-24 下午5:22:49
* @version 1.0
*/
public class NotificationActivity extends Activity implements OnClickListener {
Button bt_open, bt_cancle;
NotificationManager notificationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
bt_cancle = (Button) findViewById(R.id.bt_cancle_notifu);
bt_open = (Button) findViewById(R.id.bt_open_notify);
bt_cancle.setOnClickListener(this);
bt_open.setOnClickListener(this);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_open_notify:
Intent intent = new Intent(NotificationActivity.this,
OtherActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(
NotificationActivity.this, 0, intent, 0);
//注意,这里不是 Notification.Builder,而是NotificationCompat.Builder
Notification notification = new NotificationCompat.Builder(
NotificationActivity.this).setAutoCancel(true)
// 显示在通知栏的通知提示信息
.setTicker("Congratulation!")
// 通知标题
.setContentTitle("您有一条新通知")
// 通知内容
.setContentText("您中了100万,请速到这来领取!")
// 设置图标
.setSmallIcon(R.drawable.ic_launcher)
// 使用系统默认声音,震动,led灯等设置
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
// 加上点击后的意图
.setContentIntent(pIntent).build();
notificationManager.notify(0x001, notification);
break;
case R.id.bt_cancle_notifu:
notificationManager.cancel(0x001);
break;
default:
break;
}
}
}