我有一个从通知启动的活动。我使用 TaskStackBuilder 包含一个后退堆栈,以便当用户点击主页按钮(操作栏标题按钮)或使用后退键时,它将返回到应用程序。但是,它不是以这种方式工作的,而是回击或操作栏标题按钮总是导致应用程序关闭。
值得一提的是,我的项目结构是这样组织的,所有 UI 组件都位于 Android 库 (com.be.commotion) 中,而外部“包装器”项目使用该库。
这是我构建通知的方式:
// This is the activity that will be launched when tapping the notification
Intent intentNotification = new Intent(this, NowPlaying.class);
intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Create the back stack so the user can get back to the main activity when pressing the back button
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NowPlaying.class);
stackBuilder.addNextIntent(intentNotification);
PendingIntent pendingNowPlayingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup the custom notification view
RemoteViews notificationContent = new RemoteViews(getPackageName(), R.layout.notification_now_playing);
....
// Setup the intent that will play/stop music when the stop button is tapped
Intent musicControlIntent = new Intent(this, CommotionMediaPlayer.class);
PendingIntent musicPendingIntent = PendingIntent.getService(this, 0, musicControlIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationContent.setOnClickPendingIntent(R.id.ibMediaControl, musicPendingIntent);
// Update the notification with this info
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(song.text)
.setContentText(song.artist)
.setContentIntent(pendingNowPlayingIntent)
.setLargeIcon(artwork)
.setContent(notificationContent)
.setOngoing(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Using the nowPlayingNotificationId allows the notification to be updated with later calls instead of causing a new notification to show up
mNotificationManager.notify(nowPlayingNotificationId, builder.build());
这是我的 AndroidManifest.xml (用于包装器项目)中的适用定义:
<activity android:name="com.be.commotion.ui.StartupActivity"
android:label="@string/app_name"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Holo.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.be.commotion.ui.NowPlaying"
android:label="Now Playing"
android:parentActivityName="com.be.commotion.ui.StartupActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.be.commotion.ui.StartupActivity" />
</activity>