Android 中Notification的運用

jopen 8年前發布 | 20K 次閱讀 Android開發 移動開發 Notification

Notification在手機的運用中是很常見的,比如我們收到一個短信,在我們的通知欄就會顯示一個消息的圖標用來提示我們,這種我們就可以用Notification來實現。他有很多的用法,比如類似消息的一個提示,進度條式的提示,折疊式啊,或者懸掛式等。下面我們可以看一個簡單的也是最基本的Notification:

第一種:基本的Notification

1.API 11 以下的,現在被棄用了,它的簡單用法是這樣的

1.1這里需要使用PendingIntent,跟Intent相似,Intent 是及時啟動,intent 隨所在的activity 消失而消失,而PendingIntent它不是馬上被調用,它主要用于即將發生的事情,在Notification中,它在下拉狀態條點擊時候才會發生activity的跳轉

 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,  new Intent(this, MainActivity.class), 0);  

1.2然后我們在來看Notification 的使用方法

 Notification notify = new Notification();  
    notify.icon = R.drawable.ic_launcher;  
    notify.tickerText = "有新短消息了!";  
    notify.when = System.currentTimeMillis();  
    notify.setLatestEventInfo(this, "通知的消息title",     在后來的版本中基本上會提示找不到,或者提示不建議使用
       "消息內容", pendingIntent);  
     notify.number = 1;  //消息的數量
     notify.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明當通知被用戶點擊時,通知將被清除。

簡單提一下2.x版本的處理方式:

Notification notify1 = new Notification(R.drawable.message, "有新短消息了", System.currentTimeMillis()); 

1.3然后我們需要使用系統的通知管理器來發起通知

 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_FLAG, notify);  //發起通知

我們看一下效果圖:是不是很熟悉的感覺啊

2.API11以后 主要是通過Notification.Builder來創建通知,我們看一下代碼實現

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,  new Intent(this, MainActivity.class), 0);

Notification notify= new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) // 設置狀態欄中的小圖片,尺寸一般建議在24×24, 這里也可以設置大圖標 .setTicker(有新短消息了!")// 設置顯示的提示文字 .setContentTitle("Title")// 設置顯示的標題 .setContentText("This is message content")// 消息的詳細內容 .setContentIntent(pendingIntent) // 關聯PendingIntent .setNumber(1) // 在TextView的右方顯示的數字,可以在外部定義一個變量,點擊累加setNumber(count),這時顯示的和 .getNotification(); // 需要注意build()是在API level16及之后增加的,在API11中可以使用getNotificatin()來代替 notify.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager manager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_FLAG, notify);</pre>

總體上來是沒有什么變化,同時我們還可以設置下面的一些屬性:

 //設置優先級
   notify.setPriority(Notification.PRIORITY_DEFAULT);
    //設置通知類別
   notify.setCategory(Notification.CATEGORY_MESSAGE);

3.我們也可以使用自定義的Notification:主要使用RemoteViews,

第一步:寫好你想要  Notification樣式的xml 文件
第二步:在上面的列子中加入下面的代碼:
RemoteViews remote = new RemoteViews(getPackageName(),  
                    R.layout.my_notification);  
            rv.setTextViewText(R.id.content, "hello!");  
            myNotify.contentView = rv; 

可以使用它做折疊視圖,簡單說一下,它主要是用來顯示長文本,它擁有2個視圖,一個是普通狀態下的,一個是展開狀態下的,

Intent intent = new Intent(Intent.ACTION_MAIN);
               PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
                       intent, 0);
               Notification.Builder buider = new Notification.Builder(this)
                       .setSmallIcon(R.mipmap.ic_launcher)
                       .setTicker("您有新短消息")
                       .setContentTitle("Notification Title")
                       .setContentText("This is message")
                       .setContentIntent(contentIntent)
                       .setAutoCancel(true)
                       .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

           RemoteViews contentView = new RemoteViews(getPackageName(),
                   R.layout.my_notification);
           contentView.setTextViewText(R.id.text_content, "show!");
           Notification notification1=buider.build();
           //指定視圖Notification 正常狀態下的視圖
           notification1.contentView=contentView;
           RemoteViews expandView = new RemoteViews(getPackageName(),
                   R.layout.my_notification_expand);
           //展開時的視圖
           notification1.bigContentView = expandView;

           manager.notify(NOTIFICATION_FLAG, notification1);</pre> <p>4.懸掛式Notification,他是5.0中新增的,也就是API中的Headsup的Notification,可以子啊不打斷用戶操作的時候,給用戶通知</p>

它跟其他的不同,主要在下面這句代碼:

 //設置為懸掛,主要設置 setFullScreenIntent
   notify.setContentText("Heads-Up,Notification on5.0").setFullScreenIntent(pendingIntent, true);

如下圖:

5.進度條的Notification,我們一般常見的是下載軟件的時候,顯示的會有一個下載進度的通知,其實這個也是很好實現的‘

在Api中是這樣介紹的:

To use a progress indicator on platforms starting with Android 4.0, call setProgress() . For previous versions, you must create your own custom notification layout that includes a  ProgressBar view.

它的意思是在android4.0以上平臺,我們可以直接setProgress()的方法,但是對于之前的我們只能自定義布局。

我們來簡單看一下:這個是api給的一個demo。 下面我們重點看一下著色的部分

mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                builder = new NotificationCompat.Builder(this);
                builder.setContentTitle("Picture Download")
                        .setContentText("Download in progress")
                        .setSmallIcon(R.mipmap.ic_launcher);
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                int incr;
                                // Do the "lengthy" operation 20 times
                                for (incr = 0; incr <= 100; incr+=5) {
                                    // Sets the progress indicator to a max value, the
                                    // current completion percentage, and "determinate"
                                    // state
                                    builder.setProgress(100, incr, false);
                                    // Displays the progress bar for the first time.
                                    mNotificationManager.notify(0, builder.build());
                                    // Sleeps the thread, simulating an operation
                                    // that takes time
                                    try {
                                        // Sleep for 5 seconds
                                        Thread.sleep(5*1000);
                                    } catch (InterruptedException e) {
                                        Log.d(TAG, "sleep failure");
                                    }
                                }
                                // When the loop is finished, updates the notification
                                builder.setContentText("Download complete")
                                        // Removes the progress bar
                                        .setProgress(0,0,true);
                                mNotificationManager.notify(NOTIFICATION_FLAG, builder.build());
                            }
                        }
// Starts the thread by calling the run() method in its Runnable
                ).start();
mBuilder.setProgress(100, incr, false);和 mBuilder.setProgress(0, 0, true);的區別,如果把藍色的部分替換為前者,在運行的時候,我們會看見是它下載完成后會給我們一個通知說下載完成,但是后者會給我們提示下載完成的同時,進度條是在運行的,不斷的和滾動,也就是效果是有所不同
如下圖:第一個圖是下載在進行的時候,第二個是我使用后 mBuilder.setProgress(0, 0, true),下載完成的時候,我們可以發現他還存在進度條,但是一直在滾動,我這里是靜態圖片,大家可以運行一下看看效果,第三個圖,mBuilder.setProgress(100,incr,false) ,下載完成時顯示的通知
  還有一些其他的,辟比如鎖屏下的,顯示等級的Notification,在這里我就不寫了,大家可以沒事看看api。介紹的很詳細。
</div>

來自: http://www.cnblogs.com/ai394495243/p/5121714.html

</span></span></span>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!