首页 > 解决方案 > 当 Firebase 数据发生更改时,从前台通知打开活动

问题描述

我觉得我在这里做了一些愚蠢的事情。我已经设置了一个服务来监听我的 firebase 数据库中集合的变化,当发生变化时,应用程序应该打开,除了活动没有打开。当集合中的数据发生更改时,日志消息和 toast 都会出现,但活动未打开。onStartCommand 的代码如下。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String input = intent.getStringExtra("inputExtra");
    context = getApplicationContext();
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Example Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1, notification);


    reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
            for (DocumentChange documentChange : value.getDocumentChanges()) {
                if (documentChange.getType() == DocumentChange.Type.MODIFIED) {
                    Log.d(TAG, "onComplete: reference modified");
                    Toast.makeText(context, "message received", Toast.LENGTH_SHORT).show();
                    Intent intent1 = new Intent(context, Open.class);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent1);

                }
            }
        }
    });

    return START_STICKY;
}

任何帮助将不胜感激。

标签: androidfirebasegoogle-cloud-firestore

解决方案


Android 10(API 级别 29)及更高版本对应用在后台运行时何时启动 Activity 施加了限制。这些限制有助于最大限度地减少对用户的干扰,并使用户更好地控制屏幕上显示的内容。

出于启动活动的目的,运行前台服务的应用程序仍被视为“在后台”

显示活动的替代方案

后台应用程序应显示时间敏感通知,以向用户提供紧急信息,而不是直接启动活动。

限制的例外情况: 应用程序可以直接显示活动的一些例外情况,其中一些是:

  • 该应用程序有一个可见窗口,例如前台的活动。
  • 该应用程序在前台任务的后台堆栈中有一个活动。
  • 该应用程序在“最近”屏幕上现有任务的后台堆栈中有一个活动。

有关更详细的文章,请阅读


推荐阅读