当用户在我的通知中单击一个按钮时,我试图打开MainActivity,而应用程序仅在后台运行,并提供服务.单击按钮时,Service类中会触发以下行:

Intent openApp = new Intent(this, MainActivity.class);
openApp.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(openApp);

我已经判断过了,线被触发了,所以对按钮的点击做出react 没有问题,但是Activity不会打开.

有什么建议吗?为什么这对我不起作用,我怎样才能让它起作用?

编辑

我被要求提供更多的代码,所以在我的Service中的onStartCommand()中,如果它以intent中的停止操作开始,我调用killService()方法,它杀死Service,启动MainActivity,并做一些其他事情:

if (action != null && action.equals(ACTION_STOP_SERVICE)) {
    killService();
}

要设置Notifications按钮,我使用以下代码:

Intent stopActionIntent = new Intent(this, TimerService.class);
        stopActionIntent.setAction(ACTION_STOP_SERVICE);
        PendingIntent stopActionPendingIntent = PendingIntent.getService(this, 1, stopActionIntent, PendingIntent.FLAG_IMMUTABLE);

timerNotificationBuilder.addAction(R.drawable.stop, "Stop", stopActionPendingIntent);

正如我所说,这个按钮已经对用户点击它做出了react ,所以这不是问题所在.

推荐答案

I found it! See this answer.
This answer suggests enabling ScreeanOverlay settings because as of Android 10 and later you can no longer open an activity from the background just by calling the lines I've used.
To make it work, you'd have to add this permission through your Manifest.xml:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

And then the user would have to enable the Display over other apps setting.
I searched for an option to get the user to this setting more easily and found this answer.
This answer gives a code that redirects the user to the Display over other apps setting

if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 0);
}

and then I guide the user with the notification's content (text) on how to enable the setting.
Once the setting is enabled, The lines I've used before work.\

问题解决了吗?

还没有完全解决

this whole configuration described above works, but only if the app is not killed.
If the app was killed and I try the method listed above, the app joins the recent apps list, but won't open and show up.
A solution that solves this issue as well will be accepted as an answer instead of this one.

Java相关问答推荐

如何将kotlin代码转换为java

Oracle DUAL表上使用DDL时jOOQ问题的解析'

scanner 如何在执行hasNextLine一次后重新读取整个文件?

Java Stream,需要更新列表对象列表

填写文本字段后锁定PDF

缩小画布比例后更改滚动窗格的内部大小

如何创建一个2d自上而下的移动系统,其中移动,同时持有两个关键是可能的处理?

查找剩余的枚举

Mapstruct不能正确/完全映射属性

如何在Application.yaml中连接字符串?

将Spring Boot 3.2.0升级到3.2.1后查询执行错误

支持MySQL 5.6的最新Hibernate版本

如何在Java中为thunk创建映射器函数

错误:未找到扩展元素在JBossEAP 7.2中安装FUSE时出错

Oracle中从JSON中提取和插入数据

Java Flux中的延迟增加

使用MediaPlayer类在一段时间后停止播放音乐

我该如何为我的类编写getter和setter方法?

如何使用Java对随机生成的字母数字优惠券代码进行过期设置

如何使用java区分以下结果