使用Android手機的人,都遇到過這樣子的情況,有些應用會推送消息,會在手機屏幕的上方彈一個消息出來,點擊會跳轉到一個頁面中,讓用戶查看消息,這個在Android中稱爲通知(Notification)。自己要做一個類似的通知需要一下幾個步驟:
1、獲取通知管理類
mNotificationManager = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);2、構建通知對象
Intent intent = new Intent (this,NotifacationActivity.class); PendingIntent pi = PendingIntent.getActivity (this, 0, intent, 0); Notification notification = new NotificationCompat.Builder (this) .setContentTitle ("This is content title")//設置標題 .setContentInfo ("This is content text")//設置內容信息 .setWhen (System.currentTimeMillis ())//設置通知時間 .setLargeIcon (BitmapFactory.decodeResource (getResources (), R.mipmap.ic_launcher))//設置通知大圖標 .setSmallIcon (R.mipmap.ic_launcher)//設置通知小圖標 .setContentIntent (pi)//點擊通知後的操作 .setAutoCancel (true)//設置當點擊通知後,通知不會繼續在系統欄中 .setSound (Uri.fromFile (new File ("/system/media/audio/ringtones/MI.ogg")))//設置通知來時的聲音 .setVibrate (new long[]{0,1000,1000,1000})//設置通知來時振動,要權限 .setLights (Color.YELLOW,1000,1000)//設置通知來時呼吸燈閃爍 .setPriority (NotificationCompat.PRIORITY_MAX)//設置通知的重要程度 .setStyle (new NotificationCompat.BigPictureStyle().bigPicture (BitmapFactory.decodeResource (getResources (),R.mipmap.ic_launcher)))//在內容中添加圖片 .build ();//構建對象以下對構建中使用的方法即參數做個詳細的介紹
(1)創建一個NotificationCompat.Builder的對象。
new NotificationCompat.Builder(this)
(2)設置通知的標題。
setContentTitle(CharSequence title);
(3)設置通知的內容信息。
setContentInfo(CharSequence info);
(4)設置通知的時間,設置當時發送:System.currentTimeMillis()。
setWhen(long when);
(5)設置通知的大圖標,下拉系統欄時,可以看到。
setLargeIcon(Bitmap icon);
(6)設置通知的小圖標,當通知來時會出現在狀態欄上,參數是圖片的ID。
setSmallIcom(int icon);
(7)設置通知意圖,點擊通知後,做哪些操作,參數是PendingIntent,這裏點擊通知後可以是啓動一個頁面,可以發送一條廣播,可以啓動一個服務。
setContentIntent(PendingIntent intent);
(8)設置通知點擊後,是否在下拉系統欄中顯示了。
setAutoCancel(boolean autoCancel);
(9)設置當通知來時播放的聲音,參數是Uri,可以調用Uri.fromFile(File file)來獲取聲音。
setSound(Uri sound);
(10)設置當通知來時手機要震動,手機震動需要申請權限,參數是個數組,第一個表示手機靜止時的時長,第二標識手機震動的時長,單位是ms,後邊以此類推。
<uses-permission android:name="android.permission.VIBRATE"/>
setVibrate(long[] pattern);
(11)設置當通知到來時,呼吸燈閃爍,參數1呼吸燈的顏色ID,參數2呼吸燈亮的時長,參數3呼吸燈滅的時長。
setLights(int color,int onMs,int offMs);
(12)設置通知的優先順序。
setPriority(int priority)
參數可取的值即含義
PRIORITY_DEFAULT 默認的優先級
PRIORITY_MIN 最低的優先級
PRIORITY_LOW 較低的優先級
PRIORITY_HIGH 較高的優先級
PRIORITY_MAX 最高的優先級
(13)設置長文字,設置大圖片。
setStyle(NotificationCompat.Style style);
NotificationCompat.BigTextStyle().bigText(CharSequence text);
NotificationCompat.BigPictureStyle().bigPicture(Bitmap b);
(14)構建Notification對象。
build();
3、使用通知管理類發送通知
mNotificationManager.notify (1,notification);參數1:通知的ID
參數2:通知對象。