android - 当 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;
}
任何帮助将不胜感激。
解决方案
Android 10(API 级别 29)及更高版本对应用在后台运行时何时启动 Activity 施加了限制。这些限制有助于最大限度地减少对用户的干扰,并使用户更好地控制屏幕上显示的内容。
出于启动活动的目的,运行前台服务的应用程序仍被视为“在后台”
显示活动的替代方案
后台应用程序应显示时间敏感通知,以向用户提供紧急信息,而不是直接启动活动。
限制的例外情况: 应用程序可以直接显示活动的一些例外情况,其中一些是:
- 该应用程序有一个可见窗口,例如前台的活动。
- 该应用程序在前台任务的后台堆栈中有一个活动。
- 该应用程序在“最近”屏幕上现有任务的后台堆栈中有一个活动。
有关更详细的文章,请阅读此
推荐阅读
- arrays - 缩短计算二维数组中唯一字符数的函数
- sql - Rails 查询通过每个产品的颜色聚合(使用数组或 jsonb 哈希)订购产品的数量
- python - 检查日志文件是否已更新/仅解析新数据 - Python
- node.js - 如何让我的系统使用 Homebrew 安装的节点版本?
- postgresql - 为什么我在加入横向功能时不能参考表格?
- vue.js - 如何将图像路径从标签传递到 Vue 组件
- c++ - 为单元测试调用继承类的私有成员
- python - 我需要制作一个 python 项目,但我知道 C#,但不知道如何转换它
- python - 在命令行中运行 python 文件没有输出
- c# - .net MVC中是否有任何方法可以将数据库日期导出到不在本地机器中的文件中,并作为文件附件与电子邮件一起发送。?