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

如何在通过ResolvableApiException对话框开启GPS后获取定位(Google服务)

嘿,我来帮你解决这个问题!当你通过ResolvableApiException弹出的对话框让用户开启GPS后,关键是在用户操作完成的回调里启动定位更新请求,同时用LocationCallback来接收最终的定位结果。下面是完整的实现步骤和代码示例:

步骤1:完善enableLoc方法,处理定位设置检查结果

先把你写的方法补全,用SettingsClient检查当前定位设置状态,针对可解决的异常(比如GPS未开启)弹出系统对话框引导用户开启,同时处理已开启的直接请求定位:

void enableLoc(Activity activity, int requestCode) { 
    LocationRequest mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setInterval(10000); 
    mLocationRequest.setFastestInterval(5000); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
            .addLocationRequest(mLocationRequest); 

    SettingsClient settingsClient = LocationServices.getSettingsClient(activity);
    Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());

    // GPS已经开启的情况,直接请求定位更新
    task.addOnSuccessListener(activity, locationSettingsResponse -> {
        startLocationUpdates(activity);
    });

    // 定位设置未满足的情况
    task.addOnFailureListener(activity, exception -> {
        if (exception instanceof ResolvableApiException) {
            // 弹出系统对话框,引导用户开启GPS
            try {
                ResolvableApiException resolvable = (ResolvableApiException) exception;
                // 旧版用startResolutionForResult,新版推荐用Activity Result API
                resolvable.startResolutionForResult(activity, requestCode);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
                Toast.makeText(activity, "请求开启定位失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 设备不支持定位等无法解决的情况
            Toast.makeText(activity, "当前设备无法使用定位服务", Toast.LENGTH_SHORT).show();
        }
    });
}
步骤2:处理用户开启GPS后的回调

当用户在对话框中操作完成后,我们需要在回调里判断是否成功开启GPS,然后启动定位请求:

方式1:旧版onActivityResult(适合AndroidX之前的项目)

在你的Activity中重写该方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // 替换成你传入enableLoc的requestCode值
    if (requestCode == YOUR_LOCATION_REQUEST_CODE) { 
        if (resultCode == Activity.RESULT_OK) {
            // 用户成功开启GPS,开始获取定位
            startLocationUpdates(this);
        } else {
            Toast.makeText(this, "需要开启GPS才能获取定位", Toast.LENGTH_SHORT).show();
        }
    }
}

方式2:新版Activity Result API(推荐,AndroidX项目适用)

先在Activity的onCreate中注册回调:

private ActivityResultLauncher<IntentSenderRequest> locationSettingsLauncher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 注册定位设置结果回调
    locationSettingsLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    startLocationUpdates(this);
                } else {
                    Toast.makeText(this, "未开启GPS,无法获取定位", Toast.LENGTH_SHORT).show();
                }
            }
    );
}

然后修改enableLoc中弹出对话框的代码:

// 替换原来的resolvable.startResolutionForResult(activity, requestCode);
IntentSenderRequest intentSenderRequest = new IntentSenderRequest.Builder(resolvable.getResolution()).build();
locationSettingsLauncher.launch(intentSenderRequest);
步骤3:实现定位更新请求和结果接收

编写startLocationUpdates方法,用FusedLocationProviderClient注册LocationCallback来获取定位数据:

private FusedLocationProviderClient fusedLocationClient;
private LocationCallback locationCallback;

private void startLocationUpdates(Context context) {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);

    // 定义定位回调,接收定位结果
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            // 获取最新的定位数据
            Location currentLocation = locationResult.getLastLocation();
            if (currentLocation != null) {
                double latitude = currentLocation.getLatitude();
                double longitude = currentLocation.getLongitude();
                // 这里处理你的定位数据,比如显示、存储等
                Toast.makeText(context, "当前位置:" + latitude + ", " + longitude, Toast.LENGTH_SHORT).show();
                
                // 如果只需要一次定位,可以在这里停止更新
                fusedLocationClient.removeLocationUpdates(locationCallback);
            }
        }
    };

    // 发起定位更新请求
    try {
        fusedLocationClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.getMainLooper());
    } catch (SecurityException e) {
        // 没有定位权限,需要先请求权限
        e.printStackTrace();
        // 这里可以添加请求ACCESS_FINE_LOCATION权限的逻辑
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_LOCATION);
    }
}
必加注意事项
  1. 在AndroidManifest.xml中添加定位权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  1. 运行时必须请求ACCESS_FINE_LOCATION权限(危险权限),否则会抛出SecurityException。

内容的提问来源于stack exchange,提问作者vishal patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:33:39