简体   繁体   English

服务内的 startActivity 不适用于所有 Android 设备

[英]startActivity inside service is not working on all android devices

I have to start an activity from FirebaseMessagingService and I invoke the following code when I receive a notification我必须从 FirebaseMessagingService 开始一项活动,并在收到通知时调用以下代码

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // some code here...

    Intent intent = new Intent(this, MyActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

When the app is in background and I receive a notification the result was当应用程序在后台并且我收到通知时,结果是

Xiaomi mi a2: MyActivity has been launched successfully.小米 a2: MyActivity 已成功启动。

Xiaomi redmi note 7: MyActivity not launched and nothing happened even not crashing.小米红米笔记 7: MyActivity 没有启动,即使没有崩溃也没有任何反应。

Any help why starActivity is no working on all devices inside a background service, and how can I fix this issue?任何帮助为什么 starActivity 无法在后台服务中的所有设备上运行,以及如何解决此问题?

So you want the user to still receive messages after the app has been killed - you can try using background services but since Android 10 bans background services as CommonsWare mentioned, and versions 8 & 9 both will kill background services after some time, you shouldn't rely on onMessageReceived when the app is killed.因此,您希望用户在应用程序被终止后仍能收到消息 - 您可以尝试使用后台服务,但由于 Android 10 禁止了 CommonsWare 提到的后台服务,并且版本 8 和 9 都会在一段时间后终止后台服务,您不应该当应用程序被onMessageReceived时,t 依赖于onMessageReceived Instead, look into Firebase's NotificationMessage docs相反,查看 Firebase 的NotificationMessage 文档

NotificationMessage is sent to the user and received no matter whether the device is in Doze mode or the app has been killed.无论设备是否处于 Doze 模式或应用程序已被杀死, NotificationMessage都会发送给用户并接收。 This is probably the solution you're looking for - keeping background services running in Android 8+ is going to be difficult, and impossible in newer versions.这可能是您正在寻找的解决方案 - 在 Android 8+ 中保持后台服务运行将很困难,并且在较新的版本中是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM