android中的Notification(通知)

本篇介绍Notification的用法,它是一个通知栏(类似手机下拉界面的推送)




NotificationManager引用(OnCreate)
mNatifycatinManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
点击一个button添加通知,点击第二个button取消通知

用builder创建Notification
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)//build这个方法在16版本以前不能用,确定版本
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_notyfi:
Intent intent=
new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent=PendingIntent.
getActivity(getApplicationContext(), 1, intent, PendingIntent.FLAG_ONE_SHOT);//设置PendingIntent用法
Notification notification=
new Notification.Builder(MainActivity.this).setAutoCancel(true).自动取消
setContentInfo(
"提示").setContentText("内容").setContentTitle("标题").setSmallIcon(R.mipmap.ic_launcher).图标
setContentIntent(pendingIntent).build();
mNatifycatinManager.notify(1,notification);
break;
case R.id.button_cancel://dier个按钮取消通知
mNatifycatinManager.cancel(1);//点一下取消,1是标志
break;

}

}

原来的版本(很麻烦,新版本优化了步骤)
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_notyfi:
Notification notification=new Notification();
notification.icon=R.mipmap.ic_launcher;//放状态栏图片
notification.tickerText="我是一个消息";//放状态栏内容
notification.flags=Notification.FLAG_AUTO_CANCEL;//设置为可取消
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent, PendingIntent.FLAG_ONE_SHOT);
//设置PendingIntent事件
notification.setLatestEventInfo(getApplicationContext(),"我是标题","我是内容",pendingIntent);
notification.when= Calendar.getInstance().getTimeInMillis();//发送时的时间
//pending的显示内容
mNatifycatinManager.notify(1,notification);//添加通知
break;
case R.id.button_cancel://dier个按钮取消通知
mNatifycatinManager.cancel(1);//点一下取消,1是标志
break;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值