Android 开始一个activity的同时保留导航

来源:互联网 发布:手机淘宝上架图片尺寸 编辑:程序博客网 时间:2024/06/15 13:57

首先是两个基本概念:

  1. Regular activity 常规 通知 : 处于你的应用的工作流中(一般都是有父activity的)先退到app,再退到主屏幕
  2. 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,需要用TaskStackBuilderTaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// 添加ResultActivity的所有父ActivitystackBuilder.addParentStack(ResultActivity.class);// 将Intent放入栈顶stackBuilder.addNextIntent(resultIntent);// 获取到一个包含所有parentActivties的PendingIntentPendingIntent 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 中添加相关的属性:

  1. android:name = “” 与在代码中设置的 FLAG_ACTIVITY_NEW_TASK 标志相结合,确保此Activity不会跑到应用的默认任务中

  2. android:excludeFromRecents = “true” 将新的task从对最新动态中排除,以免用户在无意间,导航回它 ?

创建与发布

// Instantiate a Builder object.NotificationCompat.Builder builder = new NotificationCompat.Builder(this);// Creates an Intent for the ActivityIntent notifyIntent =        new Intent(new ComponentName(this, ResultActivity.class));// Sets the Activity to start in a new, empty tasknotifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |        Intent.FLAG_ACTIVITY_CLEAR_TASK);// Creates the PendingIntentPendingIntent notifyIntent =        PendingIntent.getActivity(        this,        0,        notifyIntent,        PendingIntent.FLAG_UPDATE_CURRENT);// Puts the PendingIntent into the notification builderbuilder.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 NotificationManagermNotificationManager.notify(id, builder.build());
0 0