【发布时间】:2026-01-10 14:40:02
【问题描述】:
我有一个在后台运行的服务,并且在某些时间段我使用 Notification 创建通知,当用户单击通知时,它会打开一个 Activity (SurveyForm)。我想在用户按下按钮但让后台服务运行时关闭该活动。我在 Activity 中调用了 finish() 方法,但并没有完全关闭它,Application 仍然存在于最近的应用列表中。
这是创建通知的代码。
Intent notificationIntent = new Intent(this, SurveyForm.class);
notificationIntent.setAction(Constants.SURVEY_ACTION);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Survey")
.setTicker("New Survey")
.setContentText("Please, answer the survey.")
.setSmallIcon(R.drawable.survey_notification_icon)
.setSound(alarmSound)
.setLights(0xff00ff00, 1000, 1000)
.setContentIntent(resultPendingIntent)
.setOngoing(true)
.build();
notification.defaults = Notification.DEFAULT_VIBRATE;
mNotificationManager.notify(Constants.SURVEY_NOTIFICATION_ID, notification);
按钮代码如下:
bSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Close the notification
nm.cancel(Constants.SURVEY_NOTIFICATION_ID);
//Close this Activity
finish();
}
});
更新
我已经通过在清单文件中为相应的 Activity 指定下一个属性来解决问题。
android:excludeFromRecents="true"
【问题讨论】:
-
“最小化”是什么意思? Android 没有“最小化”应用程序的概念。
-
@Karakuri 通过最小化我的意思是应用程序被隐藏但仍然出现在最近的应用程序列表中。
-
@Enrique,请将解决方案作为问题的答案发布,然后接受。它将以更好的方式帮助其他人,也将为您赢得积分。
标签: android android-activity android-service