從通知啟動活動
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
當您透過通知啟動活動時,請務必保留使用者的
預期的導航體驗。輕觸「返回」按鈕必須讓使用者回到上一個畫面
從應用程式的正常工作流程前往主畫面,然後開啟「最近使用」
螢幕必須將活動顯示為獨立任務。保留此導覽
請在新工作中開始活動。
如需設定通知輕觸行為的基本方法,請參閱
建立基本方案
通知。
本頁說明如何設定
適用於你的 PendingIntent
藉此建立全新工作
堆疊。做法
取決於您要開始的活動類型:
- 規律活動
- 這項活動屬於應用程式正常使用者體驗流程的一部分。時間
而使用者透過通知進入活動時,新任務必須
加入完整的返回堆疊,讓使用者輕觸「返回」按鈕即可瀏覽
。
- 特殊活動
- 使用者只會看到透過通知啟動的活動。在
這個活動會延伸通知 UI,方法是提供
難以在通知內顯示這項活動不需要
返回堆疊。
設定一般活動 PendingIntent
如要從通知開始定期活動,請設定 PendingIntent
使用 TaskStackBuilder
建立新的返回堆疊,如下所示。
定義應用程式的活動階層
將
android:parentActivityName
敬上
歸因於每個 <activity>
元素。請參閱以下範例:
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- MainActivity is the parent for ResultActivity. -->
<activity
android:name=".ResultActivity"
android:parentActivityName=".MainActivity" />
...
</activity>
使用返回堆疊建構 PendingIntent
如要啟動包含返回堆疊的活動,請建立
TaskStackBuilder
的例項並呼叫
addNextIntentWithParentStack()
,
傳遞 Intent
,
您想開始的活動
只要按照上述說明為每項活動定義父項活動
一開始,您可以呼叫
getPendingIntent()
敬上
接收包含整個返回堆疊的 PendingIntent
。
Kotlin
// Create an Intent for the activity you want to start.
val resultIntent = Intent(this, ResultActivity::class.java)
// Create the TaskStackBuilder.
val resultPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {
// Add the intent, which inflates the back stack.
addNextIntentWithParentStack(resultIntent)
// Get the PendingIntent containing the entire back stack.
getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
Java
// Create an Intent for the activity you want to start.
Intent resultIntent = new Intent(this, ResultActivity.class);
// Create the TaskStackBuilder and add the intent, which inflates the back
// stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
// Get the PendingIntent containing the entire back stack.
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
如有需要,您可以呼叫以下程式碼,將引數新增至堆疊中的 Intent
物件
TaskStackBuilder.editIntentAt()
。
有時這是要確保返回堆疊中的活動
能在使用者瀏覽時,顯示有意義的資料。
接著,您可以照常將 PendingIntent
傳遞至通知:
Kotlin
val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
setContentIntent(resultPendingIntent)
...
}
with(NotificationManagerCompat.from(this)) {
notify(NOTIFICATION_ID, builder.build())
}
Java
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setContentIntent(resultPendingIntent);
...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());
設定特殊活動的 PendingIntent
因為從通知開始的特殊活動不需要返回
您可以藉由呼叫PendingIntent
getActivity()
。
不過,在資訊清單中定義適當的工作選項。
-
在您的資訊清單中,將下列屬性新增至
<activity>
元素。
-
android:taskAffinity=""
-
與
FLAG_ACTIVITY_NEW_TASK
標記您在程式碼中
請將這個屬性設為空白
這項活動不會納入應用程式的預設任務。不限
不符合應用程式預設相依性的現有工作
可能會受到影響
-
android:excludeFromRecents="true"
-
將新工作從「最近使用」畫面中排除,以便使用者
避免不小心回到該畫面
例如:
<activity
android:name=".ResultActivity"
android:launchMode="singleTask"
android:taskAffinity=""
android:excludeFromRecents="true">
</activity>
-
建構並發出通知:
-
建立
Intent
,用來啟動
Activity
。
-
將
Activity
設為在新的空白工作中啟動,方法是:
撥號中
setFlags()
並加上 FLAG_ACTIVITY_NEW_TASK
旗標
FLAG_ACTIVITY_CLEAR_TASK
。
-
透過呼叫建立
PendingIntent
getActivity()
。
例如:
Kotlin
val notifyIntent = Intent(this, ResultActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val notifyPendingIntent = PendingIntent.getActivity(
this, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
Java
Intent notifyIntent = new Intent(this, ResultActivity.class);
// Set the Activity to start in a new, empty task.
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Create the PendingIntent.
PendingIntent notifyPendingIntent = PendingIntent.getActivity(
this, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
- 照常將
PendingIntent
傳遞至通知:
Kotlin
val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
setContentIntent(notifyPendingIntent)
...
}
with(NotificationManagerCompat.from(this)) {
notify(NOTIFICATION_ID, builder.build())
}
Java
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setContentIntent(notifyPendingIntent);
...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());
如要進一步瞭解各種工作選項以及返回堆疊的方式
請參閱工作與返回堆疊。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[null,null,["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Start an Activity from a Notification\n\nWhen you start an activity from a notification, you must preserve the user's\nexpected navigation experience. Tapping the Back button must take the user back\nthrough the app's normal work flow to the Home screen, and opening the Recents\nscreen must show the activity as a separate task. To preserve this navigation\nexperience, start the activity in a fresh task.\n\nThe basic approach to set the tap behavior for your notification is described in\n[Create a basic\nnotification](/develop/ui/views/notifications/build-notification#SimpleNotification).\nThis page describes how to set up a\n[`PendingIntent`](/reference/android/app/PendingIntent) for your\nnotification's action so it creates a fresh [task and back\nstack](/guide/components/activities/tasks-and-back-stack). How you do this\ndepends on which type of activity you're starting:\n\nRegular activity\n: This is an activity that exists as a part of your app's normal UX flow. When\n the user arrives in the activity from the notification, the new task must\n include a complete back stack, letting the user tap the Back button to navigate\n up the app hierarchy.\n\nSpecial activity\n: The user only sees this activity if it's started from a notification. In a\n sense, this activity extends the notification UI by providing information that\n is difficult to display in the notification itself. This activity doesn't need a\n back stack.\n\nSet up a regular activity PendingIntent\n---------------------------------------\n\nTo start a regular activity from your notification, set up the `PendingIntent`\nusing [`TaskStackBuilder`](/reference/androidx/core/app/TaskStackBuilder)\nso that it creates a new back stack as follows.\n\n### Define your app's Activity hierarchy\n\nDefine the natural hierarchy for your activities by adding the\n[`android:parentActivityName`](/guide/topics/manifest/activity-element#parent)\nattribute to each [`\u003cactivity\u003e`](/guide/topics/manifest/activity-element)\nelement in your app manifest file. See the following example: \n\n```xml\n\u003cactivity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" \u003e\n \u003cintent-filter\u003e\n \u003caction android:name=\"android.intent.action.MAIN\" /\u003e\n \u003ccategory android:name=\"android.intent.category.LAUNCHER\" /\u003e\n \u003c/intent-filter\u003e\n\u003c/activity\u003e\n\u003c!-- MainActivity is the parent for ResultActivity. --\u003e\n\u003cactivity\n android:name=\".ResultActivity\"\n android:parentActivityName=\".MainActivity\" /\u003e\n ...\n\u003c/activity\u003e\n```\n\n### Build a PendingIntent with a back stack\n\nTo start an activity that includes a back stack of activities, create an\ninstance of `TaskStackBuilder` and call\n[`addNextIntentWithParentStack()`](/reference/androidx/core/app/TaskStackBuilder#addNextIntentWithParentStack(android.content.Intent)),\npassing it the [`Intent`](/reference/android/content/Intent) for the\nactivity you want to start.\n\nAs long as you define the parent activity for each activity as described\nearlier, you can call\n[`getPendingIntent()`](/reference/androidx/core/app/TaskStackBuilder#getPendingIntent(int,int))\nto receive a `PendingIntent` that includes the entire back stack. \n\n### Kotlin\n\n```kotlin\n// Create an Intent for the activity you want to start.\nval resultIntent = Intent(this, ResultActivity::class.java)\n// Create the TaskStackBuilder.\nval resultPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {\n // Add the intent, which inflates the back stack.\n addNextIntentWithParentStack(resultIntent)\n // Get the PendingIntent containing the entire back stack.\n getPendingIntent(0,\n PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)\n}\n```\n\n### Java\n\n```java\n// Create an Intent for the activity you want to start.\nIntent resultIntent = new Intent(this, ResultActivity.class);\n// Create the TaskStackBuilder and add the intent, which inflates the back\n// stack.\nTaskStackBuilder stackBuilder = TaskStackBuilder.create(this);\nstackBuilder.addNextIntentWithParentStack(resultIntent);\n// Get the PendingIntent containing the entire back stack.\nPendingIntent resultPendingIntent =\n stackBuilder.getPendingIntent(0,\n PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);\n```\n\nIf necessary, you can add arguments to `Intent` objects in the stack by calling\n[`TaskStackBuilder.editIntentAt()`](/reference/androidx/core/app/TaskStackBuilder#editIntentAt(int)).\nThis is sometimes necessary to ensure that an activity in the back stack\ndisplays meaningful data when the user navigates to it.\n\nThen you can pass the `PendingIntent` to the notification as usual: \n\n### Kotlin\n\n```kotlin\nval builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {\n setContentIntent(resultPendingIntent)\n ...\n}\nwith(NotificationManagerCompat.from(this)) {\n notify(NOTIFICATION_ID, builder.build())\n}\n```\n\n### Java\n\n```java\nNotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);\nbuilder.setContentIntent(resultPendingIntent);\n...\nNotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);\nnotificationManager.notify(NOTIFICATION_ID, builder.build());\n```\n\nSet up a special activity PendingIntent\n---------------------------------------\n\nBecause a special activity that starts from a notification doesn't need a back\nstack, you can create the `PendingIntent` by calling\n[`getActivity()`](/reference/android/app/PendingIntent#getActivity(android.content.Context,%20int,%20android.content.Intent,%20int)).\nHowever, define the appropriate task options in the manifest.\n\n1. In your manifest, add the following attributes to the `\u003cactivity\u003e` element.\n\n\n [android:taskAffinity](/guide/topics/manifest/activity-element#aff)`=\"\"`\n :\n Combined with the\n [FLAG_ACTIVITY_NEW_TASK](/reference/android/content/Intent#FLAG_ACTIVITY_NEW_TASK)\n flag that you use in code, set this attribute blank to ensure\n this activity doesn't go into the app's default task. Any\n existing tasks that have the app's default affinity aren't\n affected.\n\n\n [android:excludeFromRecents](/guide/topics/manifest/activity-element#exclude)`=\"true\"`\n :\n Excludes the new task from the Recents screen so that the user\n can't accidentally navigate back to it.\n\n\n This is shown in the following example: \n\n ```xml\n \u003cactivity\n android:name=\".ResultActivity\"\n android:launchMode=\"singleTask\"\n android:taskAffinity=\"\"\n android:excludeFromRecents=\"true\"\u003e\n \u003c/activity\u003e\n ```\n2. Build and issue the notification:\n 1. Create an `Intent` that starts the [Activity](/reference/android/app/Activity).\n 2. Set the `Activity` to start in a new, empty task by calling [setFlags()](/reference/android/content/Intent#setFlags(int)) with the flags `FLAG_ACTIVITY_NEW_TASK` and [FLAG_ACTIVITY_CLEAR_TASK](/reference/android/content/Intent#FLAG_ACTIVITY_CLEAR_TASK).\n 3. Create a `PendingIntent` by calling `getActivity()`.\n\n\n This is shown in the following example: \n\n ### Kotlin\n\n ```kotlin\n val notifyIntent = Intent(this, ResultActivity::class.java).apply {\n flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK\n }\n val notifyPendingIntent = PendingIntent.getActivity(\n this, 0, notifyIntent,\n PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE\n )\n ```\n\n ### Java\n\n ```java\n Intent notifyIntent = new Intent(this, ResultActivity.class);\n // Set the Activity to start in a new, empty task.\n notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK\n | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n // Create the PendingIntent.\n PendingIntent notifyPendingIntent = PendingIntent.getActivity(\n this, 0, notifyIntent,\n PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE\n );\n ```\n3. Pass the `PendingIntent` to the notification as usual: \n\n ### Kotlin\n\n ```kotlin\n val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {\n setContentIntent(notifyPendingIntent)\n ...\n }\n with(NotificationManagerCompat.from(this)) {\n notify(NOTIFICATION_ID, builder.build())\n }\n ```\n\n ### Java\n\n ```java\n NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);\n builder.setContentIntent(notifyPendingIntent);\n ...\n NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);\n notificationManager.notify(NOTIFICATION_ID, builder.build());\n ```\n\nFor more information about the various task options and how the back stack\nworks, see [Tasks and the back stack](/guide/components/activities/tasks-and-back-stack)."]]