編輯:關於 Android 程式設計
需要跟使用者溝通「一件重要但不急著看的事」時,Toast 並不合適——它兩秒就消失,無法回看。這正是 Notification 的價值所在:它會常駐在狀態欄,使用者下拉即可查看,離開 App 也不受影響。本文以實例說明三種常見做法:常駐型通知、系統預設提醒效果,以及完全自訂視圖的個性化通知。
主介面放兩個按鈕,分別觸發一般通知與自訂通知。
<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:background="@android:color/black"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/title"
android:textColor="#0f0"
android:textSize="20sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="30dp"
android:onClick="normal"
android:text="@string/notification"
android:textColor="#0f0"
android:textSize="20sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="30dp"
android:onClick="custom"
android:text="@string/custom"
android:textColor="#0f0"
android:textSize="20sp" />
</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="match_parent"
android:background="#000"
android:orientation="vertical">
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="@string/action_settings"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#0f0"
android:textSize="15sp" />
</LinearLayout>
package com.itfom.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.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.RemoteViews;
public class MainActivity extends Activity {
private NotificationManager mNotificationManager;
private Context context;
private Notification notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// 一般通知
@SuppressWarnings("deprecation")
public void normal(View v) {
createNotification("普通的通知");
// 常駐於「正在執行」區,不輕易清除
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
// 點擊後自動消失
notification.defaults |= Notification.FLAG_AUTO_CANCEL;
String textTitle = "Notification 示例";
String textContent = "程式正在執行,點擊此處跳轉到演示介面";
Intent it = new Intent(context, MainActivity.class);
PendingIntent pendintent = PendingIntent.getActivity(context, 0, it, 0);
notification.setLatestEventInfo(context, textTitle, textContent, pendintent);
mNotificationManager.notify(0, notification);
}
// 自訂通知
public void custom(View v) {
createNotification("個性化的通知");
// 自訂提示音(放在 SD 卡根目錄的 non.mp3)
notification.sound = Uri.parse(Environment.getExternalStorageDirectory() + "/non.mp3");
// 自訂震動節奏:立即震 0ms、停 100ms、震 200ms、停 300ms
long[] vibrate = {0, 100, 200, 300};
notification.vibrate = vibrate;
// 自訂 LED 呼吸燈顏色與頻率
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 500;
notification.ledOffMS = 500;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
RemoteViews contentView = new RemoteViews(this.getPackageName(), R.layout.notify);
contentView.setTextViewText(R.id.tv, "這是個性化的通知");
notification.contentView = contentView;
Intent it = new Intent(context, MainActivity.class);
PendingIntent pendintent = PendingIntent.getActivity(context, 0, it, 0);
notification.contentIntent = pendintent;
mNotificationManager.notify(1, notification);
}
// 一般通知與自訂通知的前段建立流程相同,因此抽成獨立方法
@SuppressWarnings("deprecation")
public Notification createNotification(String text) {
context = this;
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
return notification = new Notification(icon, text, when);
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
// 離開時一併取消通知
mNotificationManager.cancel(0);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}

按下兩個按鈕後的效果如下。一般通知走系統預設的聲音、震動與燈光;自訂通知則使用自備音效、三段震動節奏與綠色呼吸燈。

註:截圖無法呈現聲音,實際執行時會有提示音;若裝置有補光燈,也能看到 LED 閃爍。
其一,createNotification() 之所以獨立出來,是因為不論一般或自訂通知,開頭的取得服務與建立物件流程都一樣,抽出來可避免重複。其二,自訂視圖必須透過 RemoteViews 而非一般 View,因為通知實際上是跨進程繪製的。其三,上述寫法使用了 setLatestEventInfo() 與 new Notification() 這類已被標記為老舊的 API,新專案請改用 Notification.Builder 或 NotificationCompat.Builder,並記得在 Android 8.0 以上建立 NotificationChannel,同時處理通知執行權限的申請。
QQ掃描不出AR火炬怎麼辦 兩個方法試試
QQ火炬手是騰訊QQ為今年里約奧運會推出的傳遞活動,參與的人越來越多,各種問題也随之浮現。例如不少用戶反映:掃描時看不到AR火炬,該怎麼辦?小編下面就講解最新版QQ無法掃
微信也能辦護照!線上申請全流程手把手教學
微信不只能辦護照,還能續簽港澳通行證,可惜知道的人不多。對於經常出行、出差的朋友來說,這項功能極具便利。那麼微信究竟該如何辦理護照?微信官方也公布了「微信辦護照教學」,以
動手打造 SwipeBackLayout:一步步實現 Android 右滑退出 Activity
SwipeBackLayout 是什麼GitHub 上早有成熟的手滑返回開源庫,我也日常在用。但身為一個喜歡刨根問底的開發者,我總好奇它背後的實現原理。很多高水平作者寫的
Android 拍照與相冊封裝實戰:告別崩潰、空白與圖片方向錯亂
項目下載地址:https://github.com/Aiushtha/android-PictureSelector 最早使用 Android 調用系統拍照時,我遇到了各