一、Notification的基本使用
通知的創建可以放在Activity、Service、BroatcastReceiver里面。
1.創建通知
1.1NotificationManager
首先需要創建一個NotificationManager對象用來管理通知。創建方式Context.getSystemService()方法,參數傳入Context.NOTIFICATION_SERVICE。
NotificationManagermanager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
1.2Notification
1.2.1由于Android每個版本都會對通知進行部分修改,所以為了統一,我們使用v4包里面的NotificationCompat類,這是一個空的通知:
Notification notification =new ?NotificationCompat.Builder(context).build();
1.2.2最基本設置的natification:
Notificationnotification=newNotificationCompat.Builder(mContext)
? ? ? ? ? ? ? ? ? ? ? ? .setContentTitle("這是通知標題") ?//通知標題
? ? ? ? ? ? ? ? ? ? ? ? .setContentText("這是通知內容")//通知內容
? ? ? ? ? ? ? ? ? ? ? ? .setWhen(System.currentTimeMillis())//通知時間,毫秒數
? ? ? ? ? ? ? ? ? ? ? ? .setAutoCancel(true)//點擊后自動取消
? ? ? ? ? ? ? ? ? ? ? ? .setSmallIcon(R.mipmap.ic_launcher)//通知的小圖標(狀態欄上顯示,只能使用純alpha通道的圖片)
? ? ? ? ? ? ? ? ? ? ? ? setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))///通知的大圖片,通知欄上顯示
? ? ? ? ? ? ? ? ? ? ? ? .build();//通知創建
1.3發出通知
利用NotificationManager的notify方法發出通知,兩個參數,第一個是通知的id,該條通知的唯一標識,可以用來取消通知等等。第二個參數是Notification對象,代碼如下:
manager.notify(1,notification);
2.通知的點擊事件
2.1 獲取PendingIntent對象
要實現的通知的點擊效果需要使用PendingIntent類,調用靜態方法可以獲得對象。
PendingIntent? pendingIntent=PendingIntent.getActivity(mContext,0,intent,PendingIntent.FLAG_ONE_SHOT);//跳轉activity
PendingIntent pendingIntent=PendingIntent.getService(mContext,0,intent3,PendingIntent.FLAG_ONE_SHOT);跳轉服務
PendingIntent? pendingIntent=PendingIntent.getBroadcast(mContext,0,intent3,PendingIntent.FLAG_ONE_SHOT);//跳轉廣播
PendingIntent pendingIntent=PendingIntent.getForegroundService(mContext,0,intent3,PendingIntent.FLAG_ONE_SHOT);//跳轉前臺服務(要求API 26)
由上面可以看出雖然方法不一樣,但是方法的參數都是一樣的,第一個參數是上下文Context,第二個參數是請求碼,隨便填一個int值,第三個參數是要執行的”意圖“Intent,第四個參數是確定PendingIntent的行為,有4個可選值,PendingIntent.FLAG_ONE_SHOT、PendingIntent.FLAG_NO_CREATE、PendingIntent.FLAG_CANCEL_CURRENT、PendingIntent.FLAG_UPDATE_CURRENT具體含義可以查看相關文檔,或者從字面理解。
2.2設置到Notification里面
通過在創建Notification對象的時候添加setContentIntent(),傳入PendingIntent對象
Notificationnotification2=newNotificationCompat.Builder(mContext)
? ? ? ? .setContentTitle("這是通知標題")//通知標題
? ? ? ? ?.setContentText("這是通知內容")//通知內容
? ? ? ? ?.setContentIntent(serviceIntent)//點擊后的操作
? ? ? ? ?.setWhen(System.currentTimeMillis())//通知時間,毫秒數
? ? ? ? ?.setAutoCancel(true)//點擊后自動取消
? ? ? ? ?.setSmallIcon(R.mipmap.ic_launcher)//通知的小圖標(狀態欄上顯示,只能使用純alpha通道的圖片)
? ? ? ? ?.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))///通知的大圖片,通知欄上顯示
? ? ? ? .build();//通知創建
其他步驟照舊就OK了。