通知用法:1.在活動裏創建;2.在廣播接收器裏創建;3.在服務裏創建
步驟:
1.通過NotificationManager來對通知進行管理,調用Context的getSystemService()方法獲取到(參數爲Context.NOTIFICATION_SERVICE);
2.創建一個Notification對象。參數一:指定通知的圖標;參數二:指定通知ticker內容;參數三:指定通知被創建的時間,以毫秒爲單位
3.對通知的佈局進行設定,調用Notification的setLatestEventInfo()方法來設置。參數一:Context;參數二:標題內容;參數三:正文內容;參數四:點擊事件
4.設置點擊效果,PendingIntent,可根據需求使用getActivity()、getBroadcast()、getService()方法獲取。參數一:Context;參數二:0;參數三:Intent對象;參數四:PendingItent的行爲
5.顯示通知,調用NotificationManager的notify()方法。參數一:id,每個通知所指定的id是唯一的;參數二:Notification對象
NotificationManager mamager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker text",System.currentTimeMillis());
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, "This is content title", "This is content text", pi);
mamager.notify(1, notification);
6.使通知消失
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);
想要取消哪一條通知,就在cancel()方法中傳入該通知的id
高級技巧
1.音頻
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/...."));
notification.sound = soundUri;
2.震動
long[] vibrates = {0, 1000, 1000, 1000};
notification.vibrate = vibrates;
下標爲0: 表示手機靜止時常。下標爲1:表示手機震動時常。依次類推
權限:<uses-permission android:name="android.permission.VIBRATE"/>
3.LED燈
notification.ledARGB = 0xFF0000;
notification.ledOnMS = 1000;
notification.ledOffMS = 1000;
notification.flags = Notification.FLAG_SHOW_LIGHTS;
也可以默認設置,會根據手機的具體環境來設置
notification.defaults = Notification.FLAG_SHOW_LIGHTS;