(2)、使用自訂的Notification
要建立一個自訂的Notification,可以使用RemoteViews。要定義自己的擴充訊息,首先要初始化一個RemoteViews對象,然後將它傳遞給Notification的contentView欄位,再把PendingIntent傳遞給contentIntent欄位。以下範例程式碼是完整步驟:
//1、建立一個自訂的訊息布局 view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:id="@+id/image" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:layout_marginRight="10dp" />
<TextView android:id="@+id/text" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:textColor="#000" />
</LinearLayout>
//2、在程式碼中使用RemoteViews的方法來定義image和text。然後把RemoteViews對象傳到contentView欄位
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.view);
contentView.setImageViewResource(R.id.image,R.drawable.icon);
contentView.setTextViewText(R.id.text,”Hello,this message is in a custom expanded view”);
notification.contentView = contentView;
//3、為Notification的contentIntent欄位定義一個Intent(注意,使用自訂View不需要setLatestEventInfo()方法)
Intent notificationIntent = new Intent(this,Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.contentIntent = contentIntent;
//4、發送通知
mNotificationManager.notify(2,notification);
//以下是全部範例程式碼
//建立一個NotificationManager的引用
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
//定義Notification的各種屬性
int icon = R.drawable.icon; //通知表徵圖
CharSequence tickerText = "Hello"; //狀態列顯示的通知文本提示
long when = System.currentTimeMillis(); //通知產生的時間,會在通知資訊裡顯示
//用上面的屬性初始化Nofification
Notification notification = new Notification(icon,tickerText,when);
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.view);
contentView.setImageViewResource(R.id.image, R.drawable.iconempty);
contentView.setTextViewText(R.id.text, "Hello,this is JC");
notification.contentView = contentView;
Intent notificationIntent = new Intent(this,Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.contentIntent = contentIntent;
//把Notification傳遞給NotificationManager
mNotificationManager.notify(0,notification);