Android实现横幅通知
生活随笔
收集整理的這篇文章主要介紹了
Android实现横幅通知
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下:
/*** 通知欄(兼容android 8.0以上)*/boolean isVibrate=true;//是否震動//1.獲取消息服務NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);//默認通道是defaultString channelId="default";//2.如果是android8.0以上的系統,則新建一個消息通道if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {channelId="chat";/*通道優先級別:* IMPORTANCE_NONE 關閉通知* IMPORTANCE_MIN 開啟通知,不會彈出,但沒有提示音,狀態欄中無顯示* IMPORTANCE_LOW 開啟通知,不會彈出,不發出提示音,狀態欄中顯示* IMPORTANCE_DEFAULT 開啟通知,不會彈出,發出提示音,狀態欄中顯示* IMPORTANCE_HIGH 開啟通知,會彈出,發出提示音,狀態欄中顯示*/NotificationChannel channel=new NotificationChannel(channelId,"消息提醒",NotificationManager.IMPORTANCE_HIGH);//設置該通道的描述(可以不寫)//channel.setDescription("重要消息,請不要關閉這個通知。");//是否繞過勿打擾模式channel.setBypassDnd(true);//是否允許呼吸燈閃爍channel.enableLights(true);//閃關燈的燈光顏色channel.setLightColor(Color.RED);//桌面launcher的消息角標channel.canShowBadge();//設置是否應在鎖定屏幕上顯示此頻道的通知//channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);if (isVibrate) {//是否允許震動channel.enableVibration(true);//先震動1秒,然后停止0.5秒,再震動2秒則可設置數組為:new long[]{1000, 500, 2000}channel.setVibrationPattern(new long[]{1000,500,2000});} else {channel.enableVibration(false);channel.setVibrationPattern(new long[]{0});}//創建消息通道manager.createNotificationChannel(channel);}//3.實例化通知NotificationCompat.Builder nc = new NotificationCompat.Builder(this, channelId);//通知默認的聲音 震動 呼吸燈nc.setDefaults(NotificationCompat.DEFAULT_ALL);//通知標題nc.setContentTitle("標題");//通知內容nc.setContentText("內容");//設置通知的小圖標nc.setSmallIcon(android.R.drawable.ic_popup_reminder);//設置通知的大圖標nc.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));//設定通知顯示的時間nc.setWhen(System.currentTimeMillis());//設置通知的優先級nc.setPriority(NotificationCompat.PRIORITY_MAX);//設置點擊通知之后通知是否消失nc.setAutoCancel(true);//點擊通知打開軟件Context application = getApplicationContext();Intent resultIntent = new Intent(application, MainActivity.class);resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);PendingIntent pendingIntent = PendingIntent.getActivity(application, 0, resultIntent, 0);nc.setContentIntent(pendingIntent);//4.創建通知,得到buildNotification notification = nc.build();//5.發送通知manager.notify(1, notification);總結
以上是生活随笔為你收集整理的Android实现横幅通知的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: App inventor打地鼠
- 下一篇: 设计模式-开宝箱