當我們平時使用手機的時候,經常會收到一些通知,比如短信,電話,我們通過從屏幕上下拉就可以看到。如下圖
那到底這個是怎麼實現的呢?
因爲隨着AndroidSDK的版本的升級,有些方法會逐漸的被一些好的方法取代,這裏就出現了這種情況。
低於API Level 11版本(即Android 2.3.3之前的系統)中,setLatestEventInfo()函數是唯一的實現方法。不過現在我們的使用的版本基本都會高於11。
這裏我們主要需要用到一個Notificationl(通知),創建Notification的步驟
1 首先創建NotificationManager,對notification進行管理
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
2 然後創建我們的notification對象,這裏有三個參數,第一個參數爲通知的圖標,第二個參數爲通知的內容,第三個參數爲指定通知被創建的時間,以毫秒爲單位。
Notification notification = new Notification(R.mipmap.ic_launcher,"this is notify",System.currentTimeMillis());
3 創建完通知之後,我們需要對通知的佈局進行設定,這裏需要調用setLatestEventInfo這個方法,這裏第一個參數爲context對象,第二個參數爲通知的標題內容,第三個參數爲通知的具體內容,最後一個參數先不講,設置爲null
notification.setLatestEventInfo(this,"this is notify","this is a a a a a notify",null);
4 最後通過NotificationManager的notify()方法,就可以將這個通知顯示出來。第一個參數爲id,必須保證每一個id的都是不同的,否則會引起混淆。(下面我們會介紹)
manager.notify(1,notification);
當我們使用高於API Level 11 低於API Level 16的時候我們就需要使用Notification.Builder來構造函數。但要使用getNotification()來使notification實現。
Notification.Builder builder = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
notification=builder.getNotification();
當使用高於API Level 16的時候,我們就需要使用Builder和build()函數使用notification。
Notification notification = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.build();
到這裏我們這個差不多已經設置完成了,但是這個時候當我們點擊下拉下來的通知時,沒有反應,本來在我們平時使用手機的時候,都是能點擊,觸發一些事件的,這裏我就給大家介紹一下。
熟悉android編程的同學都知道,我們點擊觸發一些事件的時候,比如轉到另一個activity的時候,需要使用Intent這個意圖類,我們類似的,也需要用到這個類,但是我們還需要一個PendingIntent這個類,和Intent這類比較相似,都可以指明意圖,但是PendingIntent可以簡單的理解爲延遲的Intent.
下面我將開始介紹PendingIntent這個類的用法,首先,我們需要得到PendingIntent這個對象,這裏我們根據需求,來選擇不同的方法,方法有getAction(),getBroadcast(),getService(),
Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
這裏,第一個參數爲context,第二個參數就爲我們前面定義過的id,之所以要求是唯一的,就是因爲這個原因,第三個參數就是我們的意圖對象intent,第四個參數就爲PendingIntent的行爲,具體有四種,又需要了解的同學,可以自行查閱文檔。
最後我們將前面設置爲null的參數改爲pendingIntent,這樣,我們這個功能也算是告一段落了。
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(this, ShowNotificationActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification.Builder(this).setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent).setContentTitle("title").setContentText("content").setNumber(1).get();
manager.notify(1, notification);