点击Firebase推送通知时在WebView中打开指定URL页面
解决方案
你的问题核心在于MainActivity没有处理推送通知传递过来的URL参数,同时PendingIntent的Flag适配和Activity启动模式也需要调整,以下是具体修复步骤:
1. 修改MainActivity,处理Intent传递的URL
需要在onCreate中读取Intent的额外参数,同时重写onNewIntent方法处理应用处于前台时的通知点击事件:
public class MainActivity extends AppCompatActivity { private WebView mywebView; private static final String DEFAULT_URL = "https://example.blogspot.com/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mywebView = findViewById(R.id.webview); mywebView.setWebViewClient(new WebViewClient()); WebSettings webSettings = mywebView.getSettings(); webSettings.setJavaScriptEnabled(true); // 处理启动时的Intent参数 handleIntentUrl(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 更新当前Intent,处理应用前台时的通知点击 setIntent(intent); handleIntentUrl(intent); } private void handleIntentUrl(Intent intent) { if (intent != null && intent.hasExtra("url")) { String targetUrl = intent.getStringExtra("url"); // 检查URL不为空再加载 if (targetUrl != null && !targetUrl.isEmpty()) { mywebView.loadUrl(targetUrl); return; } } // 没有指定URL时加载默认首页 mywebView.loadUrl(DEFAULT_URL); } }
2. 适配Android 12+的PendingIntent Flag
在MyFirebaseMessagingService中,修改PendingIntent的创建逻辑,添加Android 12及以上要求的FLAG_IMMUTABLE:
public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); String url = remoteMessage.getData().get("url"); Intent intent = new Intent(this, MainActivity.class); intent.putExtra("url", url); // 适配Android 12+的Flag int flags = PendingIntent.FLAG_UPDATE_CURRENT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { flags |= PendingIntent.FLAG_IMMUTABLE; } PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, flags); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "default_channel") .setContentTitle(remoteMessage.getNotification().getTitle()) .setContentText(remoteMessage.getNotification().getBody()) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pendingIntent) .setAutoCancel(true); // 点击通知后自动取消 NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build()); // 用当前时间作为通知ID,避免重复通知被覆盖 } }
3. 设置MainActivity的启动模式
在AndroidManifest.xml中,给MainActivity添加singleTop启动模式,确保应用处于前台时不会重新创建Activity实例,而是调用onNewIntent:
<activity android:name=".MainActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
额外注意事项
- 发送推送时,确保在Firebase控制台的自定义数据中正确传入
url字段;如果是后台发送通知,建议发送数据消息(或通知+数据的组合消息),确保onMessageReceived能触发。 - 检查URL格式是否正确,避免因无效URL导致加载失败。
内容的提问来源于stack exchange,提问作者Rajesh
相关产品推荐
相关产品推荐

