Android Notification使用方法总结
AndroidNotification使用方法总结
一.基本使用
1.构造notification
NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(appContext) .setSmallIcon(appContext.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(true)//当点击通知的时候会自动取消 .setContentTitle(contentTitle) .setTicker(notifyText)//状态栏提示 .setContentText(summaryBody) .setContentIntent(pendingIntent) .setNumber(notificationNum); Notificationnotification=mBuilder.build();
2.显示通知
notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notifyID,notification);
3.手机震动提醒
/** *手机震动和声音提示 */ publicvoidviberateAndPlayTone(EMMessagemessage){ if(message!=null){ if(EMChatManager.getInstance().isSlientMessage(message)){ return; } } if(System.currentTimeMillis()-lastNotifiyTime<1000){ //receivednewmessageswithin2seconds,skipplayringtone return; } try{ lastNotifiyTime=System.currentTimeMillis(); //判断是否处于静音模式 if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT){ EMLog.e(TAG,"inslientmodenow"); return; } EaseSettingsProvidersettingsProvider=EaseUI.getInstance().getSettingsProvider(); if(settingsProvider.isMsgVibrateAllowed(message)){//检测是否允许震动 long[]pattern=newlong[]{0,180,80,120}; vibrator.vibrate(pattern,-1); } if(settingsProvider.isMsgSoundAllowed(message)){//检测是否允许声音 if(ringtone==null){ UrinotificationUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);//获取系统默认通知铃声 ringtone=RingtoneManager.getRingtone(appContext,notificationUri); if(ringtone==null){ EMLog.d(TAG,"cantfindringtoneat:"+notificationUri.getPath()); return; } } if(!ringtone.isPlaying()){//防止响铃叠加 Stringvendor=Build.MANUFACTURER; ringtone.play(); //forsamsungS3,wemeetabugthatthephonewill //continueringtonewithoutstop //soaddbelowspecialhandlertostopitafter3sif //needed if(vendor!=null&&vendor.toLowerCase().contains("samsung")){ ThreadctlThread=newThread(){ publicvoidrun(){ try{ Thread.sleep(3000); if(ringtone.isPlaying()){ ringtone.stop(); } }catch(Exceptione){ } } }; ctlThread.run(); } } } }catch(Exceptione){ e.printStackTrace(); } }
4.取消Notification
voidcancelNotificaton(){ if(notificationManager!=null) notificationManager.cancel(notifyID);//根据ID取消,每个Notification都有唯一的ID。一般在Activity的基类的onResume调用。这样可以达到进入程序后,通知自动取消的效果 }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!