android Notification使用

今天看了一下android的消息提示Notification,別且寫了一個小例子,總結一下,一遍以後使用查找方便,同時希望能給需要的朋友提供幫助。
1.創建一個簡單的Notification提示。
使用NotificationCompat.Builder對象指定Notification的UI內容與行爲
setContentTitle()設置標題
setContentText( )設置內容
setSmallIcon()設置圖標
setContentIntent()添加PendingIntent
使用NotificationManager對象。
notify()進行展示。
下面是一段示例代碼:
private void showNotifi() {
// TODO Auto-generated method stub
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent=new Intent(this,NotificationView.class);
intent.putExtra(“notifyId”, notifyId);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
builder.setContentIntent( pendingIntent);
builder.setContentTitle(“系統提示”);
builder.setContentText(“有新的版本更新”);
builder.setSmallIcon(R.drawable.ic_launcher);
manager.notify(notifyId, builder.build());
}
實現點擊跳轉的另個界面。另外Notification經持續可見。可以是在操作完成後用
NotificationManager 的cancel()方法取消。
2.Notification的更新。當對同一個時間觸發多個Notification的時候,爲了避免多次創建Notification。我們可以使用相同的Id.使用NotificationCompat.Builder的setNumber(number)展示消息的條數。
3.展示一個帶進度條的Notification
要展示一個確定長度的進度條,調用 setProgress(max, progress, false))方法將進度條添加進notification,然後發佈這
個notification,第三個參數是個boolean類型,決定進度條是 indeterminate (true) 還是 determinate (false)。在你操作進
行時,增加progress,更新notification。在操作結束時,progress應該等於max。一個常用的調用 setProgress())的方法
是設置max爲100,然後增加progress就像操作的“完成百分比”。
當操作完成的時候,你可以選擇或者讓進度條繼續展示,或者移除它。無論哪種情況下,記得更新notification的文字來
顯示操作完成。移除進度條,調用setProgress(0, 0, false))方法.比如:

 protected void showProgressNotation() {
        // TODO Auto-generated method stub
        final NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        final NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
        builder.setContentTitle("正在下載");
        builder.setContentText("下載進度。。。。");
        builder.setSmallIcon(R.drawable.ic_launcher);

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                for(int i=0;i<100;i++){
                    try {
                        Thread.sleep(5*1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    builder.setProgress(100, i, false);
                    manager.notify(1, builder.build());
                }
                builder.setProgress(100, 0, false);
                manager.notify(1, builder.build());
            }

        }).start();

    }
發佈了42 篇原創文章 · 獲贊 11 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章