可以設定 flag 為 Notification.FLAG_NO_CLEAR,表示該通知不可以刪除,用來傳達重要的訊息,或保留回到特定 activity 的機會。
每個通知會有一個唯一的 id,如果前後兩個通知使用一樣的 id,後發的通知會覆蓋同 id 的通知,可以作為更新通知的方式。
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/et" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="sendClearable" android:text="可清除訊息" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="sendNoClear" android:text="不可清除訊息" /> </LinearLayout>NoClearNotificationActivity
public class NoClearNotificationActivity extends Activity {
private NotificationManager nMgr;
private EditText et;
private int nId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.nMgr = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
this.et = (EditText) this.findViewById(R.id.et);
}
public void sendClearable(View v) {
this.sendNotification(false);
}
public void sendNoClear(View v) {
this.sendNotification(true);
}
private void sendNotification(boolean noClear) {
String msg = this.et.getText().toString();
Notification n = new Notification(R.drawable.ic_launcher, msg,
System.currentTimeMillis());
// 設定該通知能否清除
if (noClear) {
n.flags = Notification.FLAG_NO_CLEAR;
}
// 設定點下通知要開啟的 activity
PendingIntent pi = PendingIntent.getActivity(this, 1,
new Intent(this, NoClearNotificationActivity.class), 0);
n.setLatestEventInfo(this, (noClear ? "不可清除的" : "可清除的") + "通知標題", msg,
pi);
// id 要遞增,不然新訊息會覆蓋同 id 的舊訊息
this.nMgr.notify(this.nId++, n);
}
}
沒有留言:
張貼留言