Android 中Notification弹出通知实现代码
NotificationManager是状态栏通知的管理类,负责发通知、清除通知等操作。
NotificationManager是一个系统Service,可通过getSystemService(NOTIFICATION_SERVICE)方法来获取
接下来我想说的是android5.0后的弹出通知,
网上的方法是:
//第一步:实例化通知栏构造器Notification.Builder:
Notification.Builderbuilder=newNotification.Builder(MainActivity.this);//实例化通知栏构造器Notification.Builder,参数必填(Context类型),为创建实例的上下文
//第二步:获取状态通知栏管理:
NotificationManagermNotifyMgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);//获取状态栏通知的管理类(负责发通知、清除通知等操作)
//第三步:设置通知栏PendingIntent(点击动作事件等都包含在这里):
Intentpush=newIntent(MainActivity.this,MainActivity.class);//新建一个显式意图,第一个参数Context的解释是用于获得packagename,以便找到第二个参数Class的位置
//PendingIntent可以看做是对Intent的包装,通过名称可以看出PendingIntent用于处理即将发生的意图,而Intent用来用来处理马上发生的意图
//本程序用来响应点击通知的打开应用,第二个参数非常重要,点击notification进入到activity,使用到pendingIntent类方法,PengdingIntent.getActivity()的第二个参数,即请求参数,实际上是通过该参数来区别不同的Intent的,如果id相同,就会覆盖掉之前的Intent了
PendingIntentcontentIntent=PendingIntent.getActivity(MainActivity.this,0,push,0);
//第四步:对Builder进行配置:
builder
.setContentTitle("Mynotification")//标题
.setContentText("HelloWorld!")//详细内容
.setContentIntent(contentIntent)//设置点击意图
.setTicker("Newmessage")//第一次推送,角标旁边显示的内容
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher))//设置大图标
.setDefaults(Notification.DEFAULT_ALL);//打开呼吸灯,声音,震动,触发系统默认行为
/*Notification.DEFAULT_VIBRATE//添加默认震动提醒需要VIBRATEpermission
Notification.DEFAULT_SOUND//添加默认声音提醒
Notification.DEFAULT_LIGHTS//添加默认三色灯提醒
Notification.DEFAULT_ALL//添加默认以上3种全部提醒*/
//.setLights(Color.YELLOW,300,0)//单独设置呼吸灯,一般三种颜色:红,绿,蓝,经测试,小米支持黄色
//.setSound(url)//单独设置声音
//.setVibrate(newlong[]{100,250,100,250,100,250})//单独设置震动
//比较手机sdk版本与Android5.0Lollipop的sdk
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.LOLLIPOP){
builder
/*android5.0加入了一种新的模式Notification的显示等级,共有三种:
VISIBILITY_PUBLIC只有在没有锁屏时会显示通知
VISIBILITY_PRIVATE任何情况都会显示通知
VISIBILITY_SECRET在安全锁和没有锁屏的情况下显示通知*/
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
.setCategory(Notification.CATEGORY_MESSAGE)//设置通知类别
//.setColor(context.getResources().getColor(R.color.small_icon_bg_color))//设置smallIcon的背景色
.setFullScreenIntent(contentIntent,true)//将Notification变为悬挂式Notification
.setSmallIcon(R.drawable.ic_launcher);//设置小图标
}
else{
builder
.setSmallIcon(R.drawable.ic_launcher);//设置小图标
}
//第五步:发送通知请求:
Notificationnotify=builder.build();//得到一个Notification对象
mNotifyMgr.notify(1,notify);//发送通知请求
}
但上面的做法并不能在android5.0以下的设备上使通知弹出,因此下面的做法是自己重写Notification(网上查找的一些资料,来源忘记了,不好意思)
如果需要使通知自动显示,那么就需要我们在接收到通知后重新定义通知的界面,并使其加载显示在Window界面上,这点需要读者了解Window的加载机制.
其实简单点来说,就是通过windowManager的仅有的三个方法(加载,更新,删除)来实现的.如果有大神熟悉这方面的知识可以分享分享.
自定义Notification的思路:
1.继承重写NotificationCompat,Builder来实现类似的Notification
2.自定义通知界面
3.自定义NotificationManager,发送显示通知
废话不多说,先上主要代码:
publicclassHeadsUp{
privateContextcontext;
/**
*出现时间单位是second
*/
privatelongduration=3;
/**
*
*/
privateNotificationnotification;
privateBuilderbuilder;
privatebooleanisSticky=false;
privatebooleanactivateStatusBar=true;
privateNotificationsilencerNotification;
/**
*间隔时间
*/
privateintcode;
privateCharSequencetitleStr;
privateCharSequencemsgStr;
privateinticon;
privateViewcustomView;
privatebooleanisExpand;
privateHeadsUp(Contextcontext){
this.context=context;
}
publicstaticclassBuilderextendsNotificationCompat.Builder{
privateHeadsUpheadsUp;
publicBuilder(Contextcontext){
super(context);
headsUp=newHeadsUp(context);
}
publicBuildersetContentTitle(CharSequencetitle){
headsUp.setTitle(title);
super.setContentTitle(title);//状态栏显示内容
returnthis;
}
publicBuildersetContentText(CharSequencetext){
headsUp.setMessage(text);
super.setContentText(text);
returnthis;
}
publicBuildersetSmallIcon(inticon){
headsUp.setIcon(icon);
super.setSmallIcon(icon);
returnthis;
}
publicHeadsUpbuildHeadUp(){
headsUp.setNotification(this.build());
headsUp.setBuilder(this);
returnheadsUp;
}
publicBuildersetSticky(booleanisSticky){
headsUp.setSticky(isSticky);
returnthis;
}
}
publicContextgetContext(){
returncontext;
}
publiclonggetDuration(){
returnduration;
}
publicNotificationgetNotification(){
returnnotification;
}
protectedvoidsetNotification(Notificationnotification){
this.notification=notification;
}
publicViewgetCustomView(){
returncustomView;
}
publicvoidsetCustomView(ViewcustomView){
this.customView=customView;
}
publicintgetCode(){
returncode;
}
protectedvoidsetCode(intcode){
this.code=code;
}
protectedBuildergetBuilder(){
returnbuilder;
}
privatevoidsetBuilder(Builderbuilder){
this.builder=builder;
}
publicbooleanisSticky(){
returnisSticky;
}
publicvoidsetSticky(booleanisSticky){
this.isSticky=isSticky;
}
}
publicclassHeadsUpManager{
privateWindowManagerwmOne;
privateFloatViewfloatView;
privateQueuemsgQueue;
privatestaticHeadsUpManagermanager;
privateContextcontext;
privatebooleanisPolling=false;
privateMapmap;
privateNotificationManagernotificationManager=null;
publicstaticHeadsUpManagergetInstant(Contextc){
if(manager==null){
manager=newHeadsUpManager(c);
}
returnmanager;
}
privateHeadsUpManager(Contextcontext){
this.context=context;
map=newHashMap();
msgQueue=newLinkedList();
wmOne=(WindowManager)context
.getSystemService(Context.WINDOW_SERVICE);
notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
publicvoidnotify(HeadsUpheadsUp){
if(map.containsKey(headsUp.getCode())){
msgQueue.remove(map.get(headsUp.getCode()));
}
map.put(headsUp.getCode(),headsUp);
msgQueue.add(headsUp);
if(!isPolling){
poll();
}
}
publicsynchronizedvoidnotify(intcode,HeadsUpheadsUp){
headsUp.setCode(code);
notify(headsUp);
}
publicsynchronizedvoidcancel(HeadsUpheadsUp){
cancel(headsUp.getCode());
}
privatesynchronizedvoidpoll(){
if(!msgQueue.isEmpty()){
HeadsUpheadsUp=msgQueue.poll();
map.remove(headsUp.getCode());
//if(Build.VERSION.SDK_INT<21||headsUp.getCustomView()!=null){
isPolling=true;
show(headsUp);
System.out.println("自定义notification");
//}else{
////当系统是lollipop以上,并且没有自定义布局以后,调用系统自己的notification
//isPolling=false;
//notificationManager.notify(headsUp.getCode(),headsUp.getBuilder().setSmallIcon(headsUp.getIcon()).build());
//System.out.println("调用系统notification");
//}
}else{
isPolling=false;
}
}
privatevoidshow(HeadsUpheadsUp){
floatView=newFloatView(context,20);
WindowManager.LayoutParamsparams=FloatView.winParams;
params.flags=WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|WindowManager.LayoutParams.FLAG_FULLSCREEN
|WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
params.type=WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
params.width=WindowManager.LayoutParams.MATCH_PARENT;
params.height=WindowManager.LayoutParams.WRAP_CONTENT;
params.format=-3;
params.gravity=Gravity.CENTER|Gravity.TOP;
params.x=floatView.originalLeft;
params.y=10;
params.alpha=1f;
wmOne.addView(floatView,params);
ObjectAnimatora=ObjectAnimator.ofFloat(floatView.rootView,"translationY",-700,0);
a.setDuration(600);
a.start();
floatView.setNotification(headsUp);
if(headsUp.getNotification()!=null){
notificationManager.notify(headsUp.getCode(),headsUp.getNotification());
}
}
publicvoidcancel(){
if(floatView!=null&&floatView.getParent()!=null){
floatView.cancel();
}
}
protectedvoiddismiss(){
if(floatView.getParent()!=null){
wmOne.removeView(floatView);
floatView.postDelayed(newRunnable(){
@Override
publicvoidrun(){
poll();
}
},200);
}
}
protectedvoidanimDismiss(){
if(floatView!=null&&floatView.getParent()!=null){
ObjectAnimatora=ObjectAnimator.ofFloat(floatView.rootView,"translationY",0,-700);
a.setDuration(700);
a.start();
a.addListener(newAnimator.AnimatorListener(){
@Override
publicvoidonAnimationStart(Animatoranimator){
}
@Override
publicvoidonAnimationEnd(Animatoranimator){
dismiss();
}
@Override
publicvoidonAnimationCancel(Animatoranimator){
}
@Override
publicvoidonAnimationRepeat(Animatoranimator){
}
});
}
}
protectedvoidanimDismiss(HeadsUpheadsUp){
if(floatView.getHeadsUp().getCode()==headsUp.getCode()){
animDismiss();
}
}
publicvoidcancel(intcode){
if(map.containsKey(code)){
msgQueue.remove(map.get(code));
}
if(floatView!=null&&floatView.getHeadsUp().getCode()==code){
animDismiss();
}
}
publicvoidclose(){
cancelAll();
manager=null;
}
publicvoidcancelAll(){
msgQueue.clear();
if(floatView!=null&&floatView.getParent()!=null){
animDismiss();
}
}
}
publicclassFloatViewextendsLinearLayout{
privatefloatrawX=0;
privatefloatrawY=0;
privatefloattouchX=0;
privatefloatstartY=0;
publicLinearLayoutrootView;
publicintoriginalLeft;
publicintviewWidth;
privatefloatvalidWidth;
privateVelocityTrackervelocityTracker;
privateintmaxVelocity;
privateDistancedistance;
privateScrollOrientationEnumscrollOrientationEnum=ScrollOrientationEnum.NONE;
publicstaticWindowManager.LayoutParamswinParams=newWindowManager.LayoutParams();
publicFloatView(finalContextcontext,inti){
super(context);
LinearLayoutview=(LinearLayout)LayoutInflater.from(getContext()).inflate(R.layout.notification_bg,null);
maxVelocity=ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
rootView=(LinearLayout)view.findViewById(R.id.rootView);
addView(view);
viewWidth=context.getResources().getDisplayMetrics().widthPixels;
validWidth=viewWidth/2.0f;
originalLeft=0;
}
publicvoidsetCustomView(Viewview){
rootView.addView(view);
}
@Override
protectedvoidonFinishInflate(){
super.onFinishInflate();
}
privateHeadsUpheadsUp;
privatelongcutDown;
privateHandlermHandle=null;
privateCutDownTimecutDownTime;
privateclassCutDownTimeextendsThread{
@Override
publicvoidrun(){
super.run();
while(cutDown>0){
try{
Thread.sleep(1000);
cutDown--;
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
if(cutDown==0){
mHandle.sendEmptyMessage(0);
}
}
};
publicHeadsUpgetHeadsUp(){
returnheadsUp;
}
privateintpointerId;
publicbooleanonTouchEvent(MotionEventevent){
rawX=event.getRawX();
rawY=event.getRawY();
acquireVelocityTracker(event);
cutDown=headsUp.getDuration();
switch(event.getAction()){
caseMotionEvent.ACTION_DOWN:
touchX=event.getX();
startY=event.getRawY();
pointerId=event.getPointerId(0);
break;
caseMotionEvent.ACTION_MOVE:
switch(scrollOrientationEnum){
caseNONE:
if(Math.abs((rawX-touchX))>20){
scrollOrientationEnum=ScrollOrientationEnum.HORIZONTAL;
}elseif(startY-rawY>20){
scrollOrientationEnum=ScrollOrientationEnum.VERTICAL;
}
break;
caseHORIZONTAL:
updatePosition((int)(rawX-touchX));
break;
caseVERTICAL:
if(startY-rawY>20){
cancel();
}
break;
}
break;
caseMotionEvent.ACTION_UP:
velocityTracker.computeCurrentVelocity(1000,maxVelocity);
intdis=(int)velocityTracker.getYVelocity(pointerId);
if(scrollOrientationEnum==ScrollOrientationEnum.NONE){
if(headsUp.getNotification().contentIntent!=null){
try{
headsUp.getNotification().contentIntent.send();
cancel();
}catch(PendingIntent.CanceledExceptione){
e.printStackTrace();
}
}
break;
}
inttoX;
if(preLeft>0){
toX=(int)(preLeft+Math.abs(dis));
}else{
toX=(int)(preLeft-Math.abs(dis));
}
if(toX<=-validWidth){
floatpreAlpha=1-Math.abs(preLeft)/validWidth;
preAlpha=preAlpha>=0?preAlpha:0;
translationX(preLeft,-(validWidth+10),preAlpha,0);
}elseif(toX<=validWidth){
floatpreAlpha=1-Math.abs(preLeft)/validWidth;
preAlpha=preAlpha>=0?preAlpha:0;
translationX(preLeft,0,preAlpha,1);
}else{
floatpreAlpha=1-Math.abs(preLeft)/validWidth;
preAlpha=preAlpha>=0?preAlpha:0;
translationX(preLeft,validWidth+10,preAlpha,0);
}
preLeft=0;
scrollOrientationEnum=ScrollOrientationEnum.NONE;
break;
}
returnsuper.onTouchEvent(event);
}
/**
*
*@paramevent向VelocityTracker添加MotionEvent
*
*@seeandroid.view.VelocityTracker#obtain()
*@seeandroid.view.VelocityTracker#addMovement(MotionEvent)
*/
privatevoidacquireVelocityTracker(MotionEventevent){
if(null==velocityTracker){
velocityTracker=VelocityTracker.obtain();
}
velocityTracker.addMovement(event);
}
privateintpreLeft;
publicvoidupdatePosition(intleft){
floatpreAlpha=1-Math.abs(preLeft)/validWidth;
floatleftAlpha=1-Math.abs(left)/validWidth;
preAlpha=preAlpha>=0?preAlpha:0;
leftAlpha=leftAlpha>=0?leftAlpha:0;
translationX(preLeft,left,preAlpha,leftAlpha);
preLeft=left;
}
publicvoidtranslationX(floatfromX,floattoX,floatformAlpha,finalfloattoAlpha){
ObjectAnimatora1=ObjectAnimator.ofFloat(rootView,"alpha",formAlpha,toAlpha);
ObjectAnimatora2=ObjectAnimator.ofFloat(rootView,"translationX",fromX,toX);
AnimatorSetanimatorSet=newAnimatorSet();
animatorSet.playTogether(a1,a2);
animatorSet.addListener(newAnimator.AnimatorListener(){
@Override
publicvoidonAnimationStart(Animatoranimation){
}
@Override
publicvoidonAnimationEnd(Animatoranimation){
if(toAlpha==0){
HeadsUpManager.getInstant(getContext()).dismiss();
cutDown=-1;
if(velocityTracker!=null){
velocityTracker.clear();
try{
velocityTracker.recycle();
}catch(IllegalStateExceptione){
}
}
}
}
@Override
publicvoidonAnimationCancel(Animatoranimation){
}
@Override
publicvoidonAnimationRepeat(Animatoranimation){
}
});
animatorSet.start();
}
publicvoidsetNotification(finalHeadsUpheadsUp){
this.headsUp=headsUp;
mHandle=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
super.handleMessage(msg);
HeadsUpManager.getInstant(getContext()).animDismiss(headsUp);
}
};
cutDownTime=newCutDownTime();
if(!headsUp.isSticky()){
cutDownTime.start();
}
cutDown=headsUp.getDuration();
if(headsUp.getCustomView()==null){
ViewdefaultView=LayoutInflater.from(getContext()).inflate(R.layout.notification,rootView,false);
rootView.addView(defaultView);
ImageViewimageView=(ImageView)defaultView.findViewById(R.id.iconIM);
TextViewtitleTV=(TextView)defaultView.findViewById(R.id.titleTV);
TextViewtimeTV=(TextView)defaultView.findViewById(R.id.timeTV);
TextViewmessageTV=(TextView)defaultView.findViewById(R.id.messageTV);
imageView.setImageResource(headsUp.getIcon());
titleTV.setText(headsUp.getTitleStr());
messageTV.setText(headsUp.getMsgStr());
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("HH:mm");
timeTV.setText(simpleDateFormat.format(newDate()));
}else{
setCustomView(headsUp.getCustomView());
}
}
protectedvoidcancel(){
HeadsUpManager.getInstant(getContext()).animDismiss();
cutDown=-1;
cutDownTime.interrupt();
if(velocityTracker!=null){
try{
velocityTracker.clear();
velocityTracker.recycle();
}catch(IllegalStateExceptione){
}
}
}
enumScrollOrientationEnum{
VERTICAL,HORIZONTAL,NONE
}
}
具体用法:
PendingIntentpendingIntent=PendingIntent.getActivity(MainActivity.this,11,newIntent(MainActivity.this,MainActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
Viewview=getLayoutInflater().inflate(R.layout.custom_notification,null);
view.findViewById(R.id.openSource).setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
}
});
HeadsUpManagermanage=HeadsUpManager.getInstant(getApplication());
HeadsUp.Builderbuilder=newHeadsUp.Builder(MainActivity.this);
builder.setContentTitle("提醒")
//要显示通知栏通知,这个一定要设置
.setSmallIcon(R.drawable.icon)
.setContentText("你有新的消息")
//2.3一定要设置这个参数,负责会报错
.setContentIntent(pendingIntent)
//.setFullScreenIntent(pendingIntent,false)
HeadsUpheadsUp=builder.buildHeadUp();
headsUp.setCustomView(view);
manage.notify(1,headsUp);
}
总结
以上所述是小编给大家介绍的Android中Notification弹出实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!