以下内容包括建立、更新、撤銷通知和懸浮窗型通知。本文适用于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代碼:
全局變量:
NotificationManager mNotificationManager;
int notificationId=;//通知的id
在onCreate中初始化NotificationManager:
在需要出現通知的地方寫下如下代碼,注意,如果需要選擇導入,均導入的是用版本 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, , resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);//允許更新
builder.setContentIntent(resultPendingIntent);
//如果沒有就建立,如果有就更新,
//第一個參數是設定建立通知的id或者需要更新通知的id
mNotificationManager.notify(notificationId, builder.build());
在通知要跳轉到的活動的注冊的地方加一句:
2.撤銷通知
撤銷指定id的通知,或本應用發出的所有通知。:
mNotificationManager.cancel(notificationId);//撤銷指定id通知
//mNotificationManager.cancelAll();//撤銷本程式發出的全部通知
3.浮動通知(彈窗式通知)
像懸浮窗一樣的通知,懸浮在螢幕上部,效果如下:
與狀态欄的通知的唯一差別是加了下面一句:
builder.setFullScreenIntent(resultPendingIntent,true);
下面是比較完整的代碼,寫在之前定義的活動裡,需要浮動通知的地方:
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, , resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//building the notification
builder.setContentIntent(resultPendingIntent);
//更新或建立通知,并注明通知的id
//下面一句是懸浮通知與一般通知的唯一差別
builder.setFullScreenIntent(resultPendingIntent,true);
mNotificationManager.notify(notificationId, builder.build());