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

Android:点击Firebase通知打开浏览器而非指定Activity

实现Firebase通知点击跳转至指定网页(通过自定义数据)

我来帮你把原来点击通知打开Activity的逻辑改成跳转浏览器,完全通过Firebase Console的自定义数据来实现,分两步走:

第一步:在Firebase Console发送通知时添加自定义数据

当你在Firebase控制台创建新通知时:

  • 填完通知标题、内容后,找到**自定义数据(Custom data)**模块
  • 添加一组键值对:键设为web_url,值填你要跳转的目标网页链接(必须带http://或https://前缀,比如https://your-target-url.com)
  • 完成其他设置后发送通知即可

第二步:修改Firebase消息处理代码

1. 处理前台接收的通知(App在前台时)

修改你的MyFirebaseMessagingService类,调整通知点击的Intent逻辑,改成打开浏览器:

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.media.RingtoneManager;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    private static final String KEY_WEB_URL = "web_url";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // 检查是否携带自定义数据
        if (remoteMessage.getData().size() > 0) {
            String webUrl = remoteMessage.getData().get(KEY_WEB_URL);
            String title = remoteMessage.getNotification() != null ? remoteMessage.getNotification().getTitle() : "通知";
            String content = remoteMessage.getNotification() != null ? remoteMessage.getNotification().getBody() : "";
            
            // 生成并展示通知
            sendNotification(title, content, webUrl);
        }
    }

    private void sendNotification(String title, String messageBody, String webUrl) {
        // 创建打开浏览器的Intent
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
        // 设置flags确保浏览器在新任务启动,避免和App任务栈混淆
        browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        // 创建PendingIntent,注意适配Android 12+的FLAG_IMMUTABLE
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                0,
                browserIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0)
        );

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.drawable.ic_notification) // 替换成你的通知图标
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 适配Android O及以上的通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    channelId,
                    "普通通知", // 渠道名称,可自定义
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build());
    }
}

2. 处理后台接收的通知(App在后台时)

当App处于后台时,Firebase会把通知交给系统直接展示,这时onMessageReceived不会触发。我们需要在App的启动Activity中处理跳转逻辑:

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String KEY_WEB_URL = "web_url";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 处理启动时携带的通知数据
        handleNotificationDeepLink(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // 处理App在前台时,点击系统通知携带的数据
        handleNotificationDeepLink(intent);
    }

    private void handleNotificationDeepLink(Intent intent) {
        if (intent != null && intent.getExtras() != null) {
            String webUrl = intent.getExtras().getString(KEY_WEB_URL);
            if (webUrl != null && !webUrl.isEmpty()) {
                // 打开浏览器跳转目标链接
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webUrl));
                startActivity(browserIntent);
                // 可选:如果打开浏览器后需要关闭当前Activity,取消下面的注释
                // finish();
            }
        }
    }
}

关键注意事项

  • 确保自定义数据的键web_url和代码中的常量完全一致,大小写敏感
  • 目标链接必须带http://或https://前缀,否则系统无法识别为网页链接
  • Android 12及以上版本的PendingIntent必须添加FLAG_IMMUTABLE或FLAG_MUTABLE,这里我们用FLAG_IMMUTABLE更安全
  • 如果你的App有多个启动Activity,需要在对应的入口Activity中添加上述handleNotificationDeepLink逻辑

内容的提问来源于stack exchange,提问作者Goodbye World

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:41:41