編輯:關於 Android 程式設計
手機來了短信而我還沒點開時,狀態列上方會出現一個小圖示提示——這就是 Notification。本文把不同 Android 版本的通知寫法一次整理清楚。



package net.loonggg.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
public class MainActivity extends Activity {
private static final int NOTIFICATION_FLAG = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void notificationMethod(View view) {
// 通知管理器是系統 Service
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
switch (view.getId()) {
// 舊式寫法(相容 2.x,但已被棄用)
case R.id.btn1:
// PendingIntent 與 Intent 類似,但延後執行,
// 適合用在「點通知才啟動」的場景
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notify1 = new Notification();
notify1.icon = R.drawable.message;
notify1.tickerText = "TickerText:您有新短消息,請注意查收!";
notify1.when = System.currentTimeMillis();
notify1.setLatestEventInfo(this, "Notification Title",
"This is the notification message", pendingIntent);
notify1.number = 1;
// 點擊後自動清除
notify1.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFICATION_FLAG, notify1);
break;
// Builder 寫法,API 11 之後可用
case R.id.btn2:
PendingIntent pendingIntent2 =
PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notify2 = new Notification.Builder(this)
.setSmallIcon(R.drawable.message) // 狀態列小圖,建議 24x24
.setTicker("TickerText:您有新短消息,請注意查收!")
.setContentTitle("Notification Title")
.setContentText("This is the notification message")
.setContentIntent(pendingIntent2)
.setNumber(1)
.getNotification(); // API 16 起改用 build()
notify2.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFICATION_FLAG, notify2);
break;
// Builder + build(),API 16 之後可用
case R.id.btn3:
PendingIntent pendingIntent3 =
PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notify3 = new Notification.Builder(this)
.setSmallIcon(R.drawable.message)
.setTicker("TickerText:您有新短消息,請注意查收!")
.setContentTitle("Notification Title")
.setContentText("This is the notification message")
.setContentIntent(pendingIntent3)
.setNumber(1)
.build();
notify3.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFICATION_FLAG, notify3);
break;
// 自訂版面
case R.id.btn4:
Notification myNotify = new Notification();
myNotify.icon = R.drawable.message;
myNotify.tickerText = "TickerText:您有新短消息,請注意查收!";
myNotify.when = System.currentTimeMillis();
myNotify.flags = Notification.FLAG_NO_CLEAR; // 不自動清除
RemoteViews rv = new RemoteViews(getPackageName(),
R.layout.my_notification);
rv.setTextViewText(R.id.text_content, "hello wrold!");
myNotify.contentView = rv;
Intent intent = new Intent(Intent.ACTION_MAIN);
PendingIntent contentIntent =
PendingIntent.getActivity(this, 1, intent, 1);
myNotify.contentIntent = contentIntent;
manager.notify(NOTIFICATION_FLAG, myNotify);
break;
// 清除通知
case R.id.btn5:
manager.cancel(NOTIFICATION_FLAG);
// manager.cancelAll(); // 清除全部
break;
default:
break;
}
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="默認通知(已被拋棄,但是通用)" />
<Button android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="默認通知(API11之後可用)" />
<Button android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="默認通知(API16之後可用)" />
<Button android:id="@+id/btn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="自定義通知" />
<Button android:id="@+id/btn5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="清除通知" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="@+id/text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>
讓通知常駐在「正在執行」區:設定 Notification.flags = Notification.FLAG_ONGOING_EVENT 即可,這正是音樂播放器那類應用的做法。
自訂常駐通知的版面:建立 RemoteViews 指定給 contentView,再把 PendingIntent 指定給 contentIntent:
PendingIntent contentIntent = PendingIntent.getActivity(
arg0.getContext(), R.string.app_name, i,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews rv = new RemoteViews(Main.this.getPackageName(),
R.layout.notification_view);
rv.setImageViewResource(R.id.image, R.drawable.chat);
rv.setTextViewText(R.id.text, "Hello, there, I'm john.");
n.contentView = rv;
n.contentIntent = contentIntent;
nm.notify(R.string.app_name, n);
關鍵注意事項:一旦使用了 contentView,就不要再呼叫 setLatestEventInfo。兩者會互相覆蓋——誰寫在後面,畫面就顯示誰的效果。所以無論你想用哪種方式,請確保最後只有一行程式在設定它,先前的設定完全是多餘的。
最後提醒:Android 8.0(API 26)之後,所有通知都必須指定通知渠道(NotificationChannel),否則通知根本不會顯示;同時 setLatestEventInfo 已被移除,請一律改用 Notification.Builder 的串接寫法。
Android UI 系列:Dialog 對話框完整圖解
在介面上彈出一個對話框,是 Android 開發中再日常不過的操作。本篇系統性地梳理 Dialog 的概念,並逐一實作五種常見的 AlertDialog 變體。 一、D
Android Studio 右鍵選單裡找不到 Git?兩張圖教你搞定
從 Git clone 一個專案並打開後,許多人會習慣性地像在 Eclipse 裡那樣,選中工程按右鍵,想找出 Git 的版本控制選項。 但如下圖所示,你會發現右鍵選單裡
PagerSlidingTabStrip 客製化:滑動頁籤與選中文字變色
PagerSlidingTabStrip 是常見的滑動頁籤元件。本文在原始版本上加入選中文字變色功能,讓頁籤在切換時更清楚。 主要調整 修改後的版本新增 selected
Android 屬性動畫入門(二):從原理到 API 上手
上一篇聊完了逐幀動畫與補間動畫,這篇把重心放到屬性動畫上。它是目前最靈活、也最常用的動畫方案,可配置的項目包括: Duration:動畫總時長,預設 300ms; Ti