2014年1月28日 星期二

Android 開發 (十八) Notification

甚麼是Notification



可以看到上圖的NavigateTo SecondActivity這個 Notification
有很多地方可以看到Notification的應用
例如: 收到信件,需要軟體更新時,收到GCM時,鬧鐘

在這邊會稍微介紹如何使用Notification



    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent notifyIntent = new Intent(MainActivity.this,
      SecondActivity.class);
    notifyIntent.putExtra("SecondActivity", "Btn");
    
    PendingIntent appIntent = PendingIntent.getActivity(
      MainActivity.this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new Notification();
    notification.icon = R.drawable.ic_launcher;
    notification.tickerText = "notification on status bar.";
          notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    notification.setLatestEventInfo(MainActivity.this,
      "NavigateTo", "SecondActivity", appIntent);
    notificationManager.notify(0, notification);

首先先取得 NotificationManager  接著創造 intent ,  SecondActivity為點擊時倒向的Activity,
PendingIntent用來存取 intent ,其中有個重點 PendingIntent.FLAG_UPDATE_CURRENT為必要的,假設缺少這行會造成SecondActivity在getIntent的時候只會取得第一次的Intent,
如果需要瞭解這行的用意,只需要實作多個Intent帶入不同參數,並倒向同一個activity就可以複製出這個問題。

接著創造 Notification  並且做相關設定,其中Notification.FLAG_AUTO_CANCEL為點擊時Notification會自動消失。
在notificationManager.notify之後就會產生出notification。

接著要介紹如何客製化UI


    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.customview);

    contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);

    contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
    Intent notifyIntent = new Intent(MainActivity.this,
      MainActivity.class);
    
    PendingIntent appIntent = PendingIntent.getActivity(
      MainActivity.this, 0, notifyIntent, 0);
    int icon = R.drawable.ic_launcher;
       long when = System.currentTimeMillis();
       Notification notification = new Notification(icon, "Custom Notification", when);
         // Notification notification = new Notification();
    notification.contentIntent = appIntent;
    notification.contentView = contentView;
          notification.flags |= Notification.FLAG_AUTO_CANCEL; //Do not clear the notification
          notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
          notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
          notification.defaults |= Notification.DEFAULT_SOUND; // Sound
         
          
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);

創建 RemoteViews contentView之後,並且設定 notification.contentView = contentView;
其中 R.layout.customview 為任意客製化UI。

在這裡附上 sample code

沒有留言:

張貼留言