【问题标题】:fail to start activity from service无法从服务启动活动
【发布时间】:2023-03-23 23:29:01
【问题描述】:

在问这个问题之前。我首先看的是其他人是否也遇到了这个问题。但我没有找到。 简短的: 我想在通过 FCM 收到消息时开始一项活动。 每当消息传入使用此代码处理时,在 onMessageReceived(@NonNull RemoteMessage remoteMessage) 中

Intent intent = new Intent(getApplicationContext(), IncomingMeetingConference.class);
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

如果应用程序前台工作正常。但是当我在后台制作应用程序时。活动未启动。

到目前为止,我在控制台中观察到

I/Timeline: Timeline: Activity_launch_request time:771108234

但没有与 ActivityThread 相关的消息。

而当应用程序处于前台时,我会在控制台中收到 ActivityThread 日志消息。请告诉我如何解决这个问题?

【问题讨论】:

  • 使用 PendingIntent 并为用户发送通知
  • 还可以了解来电如何在后台向用户显示消息。
  • @MarcosVasconcelos 谢谢。我不知道如何知道应用程序是在后台还是前台。经过一番搜索,我得到了答案并作为答案分享。

标签: android firebase android-activity android-service


【解决方案1】:

你不能那样做。不鼓励这种行为。当您从服务器收到消息时,您不能打断用户。正确的行为是显示Notification。然后用户可以点击Notification 来查看Activity。这允许用户决定何时以及是否想要查看它。

【讨论】:

    【解决方案2】:

    感谢大卫给了我正确的想法。所以我通过

    找到了检查应用程序的代码是在后台还是前台
    public boolean foregrounded() {
        ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
        ActivityManager.getMyMemoryState(appProcessInfo);
        return (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
    }
    

    如果应用程序在前台,它将返回 true。如果应用在后台,它将返回 false。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多