You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在应用未运行或后台时无需点击通知直接启动Activity

解决Firebase消息全场景直接启动Activity问题

当前你的代码仅能在应用前台运行时生效,核心原因是:Firebase的通知消息(带notification字段的消息)在应用后台/未运行时会被系统托盘接管,不会触发onMessageReceived方法。要实现类似Truecaller的全场景直接启动Activity效果,按以下步骤调整:

1. 切换为数据消息发送

服务器端必须发送纯数据消息(或包含data字段的混合消息),这样无论应用处于前台、后台还是未启动状态,onMessageReceived都会被触发。

数据消息的JSON示例:

{
  "to": "目标设备Token",
  "priority": "high", // 高优先级确保消息及时送达
  "data": {
    "image_url": "https://example.com/your-image.jpg",
    "title": "通知标题",
    "message": "通知内容"
  }
}

2. 修改Messaging Service代码

从remoteMessage.getData()提取数据(数据消息没有notification对象),同时优化Intent启动逻辑适配系统限制:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        // 从data字段取数据,不要用getNotification()
        Map<String, String> data = remoteMessage.getData();
        String imageUrl = data.get("image_url");
        String title = data.get("title");
        String message = data.get("message");

        Intent intent = new Intent(this, FullScreenActivity.class);
        intent.putExtra("image_url", imageUrl);
        intent.putExtra("title", title);
        intent.putExtra("message", message);
        
        // 设置Flag确保Activity正确启动,避免重复实例
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
                | Intent.FLAG_ACTIVITY_CLEAR_TOP 
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        // 适配Android 10+的后台启动限制
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ActivityOptions options = ActivityOptions.makeBasic();
            startActivity(intent, options.toBundle());
        } else {
            getApplicationContext().startActivity(intent);
        }
    }
}

3. 配置Activity启动模式(可选)

在AndroidManifest.xml中给FullScreenActivity设置启动模式,避免重复创建实例:

<activity
    android:name=".FullScreenActivity"
    android:launchMode="singleTop"
    android:excludeFromRecents="true" /> <!-- 可选:从最近任务列表隐藏,更贴近Truecaller体验 -->

4. 适配Android 12+权限

如果目标SDK≥31,必须在AndroidManifest.xml中申请通知权限:

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

同时确保消息设置了priority: "high",否则系统会限制后台启动Activity。


内容的提问来源于stack exchange,提问作者Mahesh Kalamkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 05:03:29