android内存溢出 gps,java - 在关闭GPS的情况下打开应用时无法获取GPS当前位置 - 堆栈内存溢出...

使用此代码启用GPS并确保已授予位置权限。 最初,当GPS禁用时,onFailureListener将触发并弹出GPS启用对话框,但按ok后将不会触发onSuccessListener,因此您需要从onActivityResult发出当前位置请求,但是如果GPS启用,则在进入应用程序之前,onSuccessListener将触发并且您可以请求从那里获取当前位置。

LocationRequest mLocationRequest = new LocationRequest();

mLocationRequest.setInterval(10000);

mLocationRequest.setFastestInterval(5000);

mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()

.addLocationRequest(mLocationRequest);

SettingsClient client = LocationServices.getSettingsClient(HomeActivity.this);

Task task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(HomeActivity.this, locationSettingsResponse -> {

// Make your current location request here

});

task.addOnFailureListener(HomeActivity.this, e -> {

if (e instanceof ResolvableApiException) {

// Location settings are not satisfied, but this can be fixed

// by showing the user a dialog.

try {

// Show the dialog by calling startResolutionForResult(),

// and check the result in onActivityResult().

ResolvableApiException resolvable = (ResolvableApiException) e;

resolvable.startResolutionForResult(HomeActivity.this,

REQUEST_CHECK_SETTINGS);

} catch (IntentSender.SendIntentException sendEx) {

// Ignore the error.

}

}

});

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK && requestCode == REQUEST_CHECK_SETTINGS) {

// Make your current location request here

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值