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

Android调用Google Maps服务时出现Unknown calling package name错误的解决方法

Android应用运行报错:Failed to get service from broker(Unknown calling package name 'com.google.android.gms')

错误详情

运行应用时触发以下错误:

Failed to get service from broker.
java.lang.SecurityException: Unknown calling package name 'com.google.android.gms'

完整堆栈跟踪:

at android.os.Parcel.createExceptionOrNull(Parcel.java:3057)
at android.os.Parcel.createException(Parcel.java:3041)
at android.os.Parcel.readException(Parcel.java:3024)
at android.os.Parcel.readException(Parcel.java:2966)
at m.cqy.q(:com.google.android.gms.policy_maps_core_dynamite@234210309@234210304072.587101654.587101654:180)
at m.cpk.run(:com.google.android.gms.policy_maps_core_dynamite@234210309@234210304072.587101654.587101654:54)
at android.os.Handler.handleCallback(Handler.java:958)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:205)
at android.os.Looper.loop(Looper.java:294)
at android.os.HandlerThread.run(HandlerThread.java:67)

相关代码与配置

Game_Activity代码

package il.co.jonathan.monstercatch.ACTIVITIES;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import il.co.jonathan.monstercatch.R;

public class Game_Activity extends FragmentActivity implements OnMapReadyCallback {

    private Location currentLocation;
    private LocationCallback locationCallback;

    private FusedLocationProviderClient fusedClient;
    private static final int REQUEST_CODE = 101;
    private FrameLayout map;
    private ImageView menuIcon;

    private void initializeViews() {
        map = findViewById(R.id.map);
        menuIcon = findViewById(R.id.menuIcon);
    }

    private void setAdapters() {
    }

    private void setListeners() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        initializeViews();
        setAdapters();
        setListeners();
        getLocation();
    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE);
            return;
        }

        fusedClient = LocationServices.getFusedLocationProviderClient(this);
        Task<Location> task = fusedClient.getLastLocation();

        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    currentLocation = location;
                    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                    if (supportMapFragment != null) {
                        supportMapFragment.getMapAsync(Game_Activity.this);
                    } else {
                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMap.getUiSettings().setScrollGesturesEnabled(false);
        LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Player");
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
        googleMap.addMarker(markerOptions);
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLocation();
            }
        }
    }
}

Gradle配置

plugins {
    id("com.android.application") version "8.2.2"
    id("com.google.gms.google-services") version "4.4.0"
    id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") version "2.0.0"
}


android {
    namespace = "il.co.jonathan.monstercatch"
    compileSdk = 34

    defaultConfig {
        applicationId = "il.co.jonathan.monstercatch"
        minSdk = 27
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }
    secrets {
        propertiesFileName = "secrets.properties"


        defaultPropertiesFileName = "local.defaults.properties"

        // Configure which keys should be ignored by the plugin by providing regular expressions.
        // "sdk.dir" is ignored by default.
        ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
        ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    buildFeatures {
        viewBinding = true
    }
}

dependencies {

    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.11.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    implementation(project(":VIEWMODEL"))
    implementation(project(":MODEL"))
    implementation(project(":HELPER"))
    implementation("androidx.navigation:navigation-fragment:2.7.6")
    implementation("androidx.navigation:navigation-ui:2.7.6")
    implementation("com.google.android.gms:play-services-maps:18.2.0")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
    implementation("com.google.android.gms:play-services-location:21.1.0")
    implementation("com.google.android.gms:play-services-gcm:17.0.0")

}

Manifest配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="il.co.jonathan.monstercatch">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MonsterCatch"
        tools:targetApi="31">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="my api" />

        <activity
            android:name=".ACTIVITIES.Game_Activity"
            android:exported="false"
            android:label="@string/title_activity_game" />
        <activity
            android:name=".ACTIVITIES.SignUpActivity2"
            android:exported="false"
            android:label="@string/title_activity_sign_up2"
            android:theme="@style/Theme.MonsterCatch" />
        <activity
            android:name=".ACTIVITIES.LogInActivity2"
            android:exported="false" />
        <activity
            android:name=".ACTIVITIES.MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

解决方案

1. 校验Google Maps API Key配置

  • 登录Google Cloud控制台,找到你的API Key:
    • 确认Key已绑定应用的包名(il.co.jonathan.monstercatch)和对应签名的SHA-1指纹(调试和发布版本都要添加)
    • 确保已启用Maps SDK for Android服务,若用到位置相关服务,同步启用Geocoding API、Places API等

2. 统一Google Play服务依赖版本

当前项目中play-services-maps和play-services-location版本差距较大,容易引发兼容性问题。修改Gradle依赖为同一稳定版本:

implementation("com.google.android.gms:play-services-maps:21.0.1")
implementation("com.google.android.gms:play-services-location:21.0.1")

若未使用play-services-gcm,直接移除该依赖。

3. 补充Manifest权限

添加网络状态权限,确保Google服务能正常联网校验:

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

4. 清理重建项目

  • 执行Android Studio菜单栏的Build > Clean Project,再执行Build > Rebuild Project
  • 卸载设备上的旧应用,清除缓存后重新安装

5. 更新设备Google Play服务

打开测试设备的Google Play商店,搜索Google Play服务并更新至最新版本,避免因服务版本过低导致交互失败


内容的提问来源于stack exchange,提问作者Jonathan Kalush

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:30:57