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

.NET 7.0下无法设置GoogleServicesJson生成操作的问题求助

解决.NET MAUI 7中Firebase推送通知的google-services.json生成操作问题

核心问题原因

Xamarin.GooglePlayServices系列包(包括Base/Basement)仅官方支持.NET 6.0,在.NET 7.0 MAUI项目中,其自带的MSBuild目标会因框架版本不匹配被自动跳过,导致GoogleServicesJson生成操作无法显示。

解决方案1:手动强制导入MSBuild目标(推荐)

不需要回退.NET版本,直接在项目文件中手动引入Xamarin.GooglePlayServices.Basement的构建目标,同时配置google-services.json的处理规则:

  1. 确保已安装Xamarin.GooglePlayServices.Basement包(即使是.NET 6.0版本,MAUI Android项目兼容该版本库)
  2. 打开项目的.csproj文件,添加以下配置:
<!-- 配置google-services.json的处理 -->
<ItemGroup>
  <GoogleServicesJson Include="google-services.json" Condition="$(TargetFramework.StartsWith('net7.0-android'))">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </GoogleServicesJson>
</ItemGroup>

<!-- 手动导入.NET 6.0版本的构建目标,强制适配.NET 7.0项目 -->
<Import Project="$(NuGetPackageRoot)\Xamarin.GooglePlayServices.Basement\118.1.0.3\buildTransitive\net6.0-android31.0\Xamarin.GooglePlayServices.Basement.targets" 
        Condition="Exists('$(NuGetPackageRoot)\Xamarin.GooglePlayServices.Basement\118.1.0.3\buildTransitive\net6.0-android31.0\Xamarin.GooglePlayServices.Basement.targets')" />

注意:将版本号118.1.0.3替换为你实际安装的Basement包版本

  1. 保存.csproj后,重新加载项目,此时GoogleServicesJson生成操作应该会显示,可直接在文件属性中设置。

解决方案2:手动初始化Firebase(不依赖生成操作)

如果上述方法仍无效,可以完全绕过自动生成操作,手动读取配置并初始化Firebase:

  1. 将google-services.json的生成操作设置为AndroidAsset(在文件属性中选择)
  2. 在Android项目的MainApplication.cs中,解析google-services.json并手动初始化Firebase:
using System.IO;
using System.Text.Json;
using Firebase;
using Firebase.Messaging;

public override void OnCreate()
{
    base.OnCreate();

    // 读取Assets中的google-services.json
    using var stream = Assets.Open("google-services.json");
    using var reader = new StreamReader(stream);
    var jsonContent = reader.ReadToEnd();
    var config = JsonDocument.Parse(jsonContent).RootElement;

    // 提取配置参数
    var appId = config.GetProperty("client")[0].GetProperty("client_info").GetProperty("mobilesdk_app_id").GetString();
    var apiKey = config.GetProperty("client")[0].GetProperty("api_key")[0].GetProperty("current_key").GetString();
    var senderId = config.GetProperty("project_info").GetProperty("project_number").GetString();

    // 初始化Firebase
    var options = new FirebaseOptions.Builder()
        .SetApplicationId(appId)
        .SetApiKey(apiKey)
        .SetGcmSenderId(senderId)
        .Build();

    if (FirebaseApp.DefaultInstance == null)
    {
        FirebaseApp.InitializeApp(this, options);
    }
    FirebaseMessaging.Instance.AutoInitEnabled = true;
}

额外检查项

  • 确认项目的.csproj中,Android目标框架设置正确(例如net7.0-android33.0)
  • 清理并重建解决方案,确保MSBuild缓存已更新
  • 若使用Visual Studio,尝试删除.vs文件夹后重启,清除项目缓存

内容的提问来源于stack exchange,提问作者Christopher Phillips

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:05:36