首先是两个基本概念:
- Regular activity 常规 通知 : 处于你的应用的工作流中(一般都是有父activity的)先退到app,再退到主屏幕
- Special activity 特殊 通知 : 只能从Notification中打开的activity,直接退到主屏幕
设置常规的 activity pendingIntent
要设置一个开启Activity的 PendingIntent,需要两步:
1 . 定义Activity的manifest,(是有注明谁是谁的父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>
<activity
android:name=".ResultActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
2 . 创建一个基于 用于打开Activity的Intent 的 backStack
int id = 1;
...
Intent resultIntent = new Intent(this, ResultActivity.class);
// 要创建一个backStack,需要用TaskStackBuilder
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// 添加ResultActivity的所有父Activity
stackBuilder.addParentStack(ResultActivity.class);
// 将Intent放入栈顶
stackBuilder.addNextIntent(resultIntent);
// 获取到一个包含所有parentActivties的PendingIntent
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
...
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());
创建一个特殊的Activity的
特殊的Activity,不需要添加 parentActivity,不过相对的,你必须在它的 manifest 中添加相关的属性:
android:name = “”
与在代码中设置的 FLAG_ACTIVITY_NEW_TASK 标志相结合,确保此Activity不会跑到应用的默认任务中android:excludeFromRecents = “true”
将新的task从对最新动态中排除,以免用户在无意间,导航回它 ?
创建与发布
// Instantiate a Builder object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Creates an Intent for the Activity
Intent notifyIntent =
new Intent(new ComponentName(this, ResultActivity.class));
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
PendingIntent notifyIntent =
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// Puts the PendingIntent into the notification builder
builder.setContentIntent(notifyIntent);
// Notifications are issued by sending them to the
// NotificationManager system service.
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Builds an anonymous Notification object from the builder, and
// passes it to the NotificationManager
mNotificationManager.notify(id, builder.build());