通知的关键代码,由于版本的更改。需要用Notification.Builder来得到一个Notification
public class MainActivity extends Activity implements OnClickListener {
private Button btn1, btn2;
private Context context;
private NotificationManager manager;
Notification.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
btn1 = (Button) findViewById(R.id.send);
btn2 = (Button) findViewById(R.id.delete);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
//获取系统通知的服务
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onClick(View v) {
builder = new Notification.Builder(context);
switch (v.getId()) {
case R.id.send:
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
// 设置第一次通知显示的内容
builder.setTicker("您有一条新消息");
// 显示图标
builder.setSmallIcon(R.drawable.ic_launcher);
// 显示时间
builder.setWhen(System.currentTimeMillis());
// 显示标题
builder.setContentTitle("今日头条");
// 显示内容
builder.setContentText("今天北京有大到暴雨!");
// 设置通知的意图
builder.setContentIntent(pending);
// 设置响铃、震动、声音都为默认值
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.getNotification();
//设置标识并发送通知
manager.notify(1, notification);
break;
case R.id.delete:
//需要清空通知的标识
manager.cancel(1);
break;
}
}
}
清空通知还有一种方法manager.cancelAll();清空全部通知,运行结果如下图