天天看點

android中notification的用法(簡單易懂用法)

首先解釋一下notification的應用場景,一般我們手機來短息的時候在手機的上方都會彈出一個通知,你可以下拉上方的菜單看詳細資訊,點選這個通知就會跳轉得到相應的短信界面,那麼怎麼實作的呢我們直接上代碼解釋,notification有三種創造方式

方法一:(已經被舍棄,但是通用)

//首先我們要獲得一個通知管理器 NotificationManager,是一個系統的service
Notification manager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//PendingIntent作用類似于intent不同的是不是立刻執行,而是等通知被點選以後執行
PendingIntent PendingIntent=PendingIntent.getActivity(this,,newIntent(this,MainActivity),);
Notification notify = new Notification();
notify.icon=R.drawable.message; //設定顯示的圖檔
notify.tickerText="你有新消息";  //設定通知提示的标題
notify.when=System.CurrentTimeMills();//設定通知顯示時間,這裡擷取系統時間
notify.setLatestEventInfo(this,"notification Title","this is a message",pendingIntet)
//設定拉開菜單後,通知顯示的标題,内容,點選後觸發的事件
notify.number=;        //如果同一個通知發送多條可以用這個區分
notify.flags|=Notification.FLAG_AUTO_CANCEL//通知點選後自動消失
manager.notify(FlAG_ID,notify);//通過menager發送通知,FLAG_ID是通知的id,自己定義
           

方法二:(該方法在API11以後才使用)

//通過Builer來建立
Notification notify = new Notification.Builder(this)
    .setSmallIcon(R.drawable.message)//設定小圖,大圖用setLargeIcon設定
    .setTiker("Ticker Text")
    .setContenTitle("拉開後标題")
    .setContentText("拉開後内容")
    .setContentIntent(pandingIntent)//點選後觸發的事件
    .setNumber()//如果同一個通知發送多條可以用這個區分
    .getNotification();//擷取通知對象
notify.flags|=Notification.FLAG_AUTO_CANCEL//通知點選後自動消失
manager.notify(FlAG_ID,notify);//通過menager發送通知,FLAG_ID是通知的id,自己定義
           

建立方法三:(該方法是API16以後才支援的)

//通過Builer來建立
Notification notify = new Notification.Builder(this)
    .setSmallIcon(R.drawable.message)//設定小圖,大圖用setLargeIcon設定
    .setTiker("Ticker Text")
    .setContenTitle("拉開後标題")
    .setContentText("拉開後内容")
    .setContentIntent(pandingIntent)//點選後觸發的事件
    .setNumber()//如果同一個通知發送多條可以用這個區分
    .build();//擷取通知對象
notify.flags|=Notification.FLAG_AUTO_CANCEL//通知點選後自動消失
manager.notify(FlAG_ID,notify);//通過menager發送通知,FLAG_ID是通知的id,自己定義
           

有任何不懂或錯誤的地方,歡迎評論留言