NotificationManager(三)

來源:互聯網
上載者:User

(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);
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.