Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 使用 Notification 實作普通通知欄

編輯:關於 Android 程式設計

Notification 是在應用程式常規介面之外,向使用者展示訊息的機制。當 App 發送通知時,系統會先在狀態列顯示圖示,使用者可下拉通知抽屜查看詳細內容。

Notification 的基本組成

  • 標題。
  • 通知內容。
  • 小圖示。
  • 大圖示。
  • 發送時間。
  • 點擊後的行為。

建立通知

可使用 NotificationCompat.Builder 建立通知,再透過 NotificationManager 發送。

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

builder.setSmallIcon(R.mipmap.guojia);
builder.setContentTitle("郭嘉");
builder.setContentText("我們打袁紹吧");
builder.setDefaults(Notification.DEFAULT_ALL);

Intent intent = new Intent(this, ContentActivity.class);
intent.putExtra("info", "郭嘉給你發了一個計策!");

PendingIntent pi = PendingIntent.getActivity(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

builder.setContentIntent(pi);

Notification notification = builder.build();

NotificationManager manager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

manager.notify(0x1, notification);

點擊通知後的頁面

public class ContentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);

        String info = getIntent().getStringExtra("info");
        Toast.makeText(this, info, Toast.LENGTH_SHORT).show();
    }
}

實作流程

  1. 建立觸發通知的按鈕。
  2. 使用 Builder 設定通知內容。
  3. 使用 PendingIntent 設定點擊行為。
  4. 呼叫 NotificationManager 發送通知。
  5. 在目標 Activity 中接收並處理資料。

在 Android 8.0 以上,若要發送通知,還需要建立 Notification Channel。這是後續實作時必須注意的重點。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved