Android 通知(使用NotificationCompat.Builder )
以下內容包括創建、更新、撤銷通知和懸浮窗型通知。本文適用于android 8.0之下情況,android 8.0需要為通知添加渠道,可以參考我的這篇:Android 8.0 通知顯示,本文代碼所有通知都沒有添加渠道。
Android 的通知,之前的寫法是用Notification notification=new Notification (……)。這種方法已經被棄用。還有一些實現方法總是包含一些建議不再使用的方法或變量,的下面講述的是,支持Android 3.0及其以上的通知使用方法(不使用那些棄用的方法):使用NotificationCompat.Builder(v4庫下的,即import android.support.v4.app.NotificationCompat;)。實現點擊通知,進入活動,同時通知消失,并且不會讓該活動之前的活動出棧,若本活動已經創建,將不會重新創建活動。實現的效果:點擊通知,相當于從系統主頁,直接點擊應用圖標進入應用的相應活動。
1.創建或者更新一個通知
要求點擊通知后進入活動,同時通知消失,不會讓之前的活動出棧,若已有該活動則,不再銷毀原活動后重新創建活動。如果沒有就創建,如果有就更新指定id的通知。效果如下(在真機測試時,圖標是彩色的,這里應該是因為沒有使用Material Design):
java代碼:
全局變量:
在onCreate中初始化NotificationManager:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);在需要出現通知的地方寫下如下代碼,注意,如果需要選擇導入,均導入的是用版本 4 支持庫中的類。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher)//左部圖標.setContentTitle("通知標題")//上部標題.setContentText("通知內容")//中部通知內容.setAutoCancel(true);//點擊通知后自動消失 builder.setDefaults(Notification.DEFAULT_ALL);//通知的聲音震動等都隨系統 //也可以選擇使用聲音文件,這里的文件是res/raw/miui_notice.mp3 // Uri uri=Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.miui_notice); // builder.setSound(uri);Intent resultIntent = new Intent(this, Main2Activity.class);//點擊通知后進入的活動//這兩句非常重要,使之前的活動不出棧resultIntent.setAction(Intent.ACTION_MAIN);resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);//允許更新builder.setContentIntent(resultPendingIntent);//如果沒有就創建,如果有就更新,//第一個參數是設置創建通知的id或者需要更新通知的idmNotificationManager.notify(notificationId, builder.build());在通知要跳轉到的活動的注冊的地方加一句:
android:launchMode="singleTask"2.撤銷通知
撤銷指定id的通知,或本應用發出的所有通知。:
mNotificationManager.cancel(notificationId);//撤銷指定id通知 //mNotificationManager.cancelAll();//撤銷本程序發出的全部通知3.浮動通知(彈窗式通知)
像懸浮窗一樣的通知,懸浮在屏幕上部,效果如下:
與狀態欄的通知的唯一區別是加了下面一句:
下面是比較完整的代碼,寫在之前定義的活動里,需要浮動通知的地方:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher)//左部圖標.setContentTitle("通知標題")//上部標題.setContentText("點擊前往第二界面")//中部通知內容.setAutoCancel(true);//點擊通知后自動消失Intent resultIntent = new Intent(this, Main2Activity.class);resultIntent.setAction(Intent.ACTION_MAIN);resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);//building the notificationbuilder.setContentIntent(resultPendingIntent);//更新或創建通知,并注明通知的id //下面一句是懸浮通知與一般通知的唯一區別builder.setFullScreenIntent(resultPendingIntent,true);mNotificationManager.notify(notificationId, builder.build());總結
以上是生活随笔為你收集整理的Android 通知(使用NotificationCompat.Builder )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上帝为什么不直接把魔鬼撒但这等邪…
- 下一篇: java 数组定义是必须指定长度吗