java - Android:无法发出位置请求对话框并在回调中获取位置

标签 java android location

我遵循了here的官方文档向用户显示位置对话框,因为如果没有位置,我们的应用程序将无法运行。问题是,即使当我按下对话框上的“确定”按钮时,有时任务监听器的 onFailure 也会被调用,更重要的是,即使 onSuccess(LocationSettingsResponse locationSettingsResponse) 确实被调用,我也无法立即获取位置详细信息,我所做的解决方法是创建一个单独的线程来循环获取详细信息。我需要知道一个更简单的方法来做到这一点。

这花了我 2 天多的时间,但我仍然无法弄清楚我的代码出了什么问题。

FusedLocationProviderClient client;
TextView textView;
boolean started = false;
double lat = 0;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = findViewById(R.id.text);
    client = LocationServices.getFusedLocationProviderClient(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.e(tag, "no perm");
        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
    } else
        work();
}

void work() {
    if (!isLocationEnabled()) createLocationRequest();
    else locationDetails();
}

int t = 0;


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.e(tag, "activity result");
    work();
}

void locationDetails() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    client.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        if(lat!=0)return;
                        lat = location.getLatitude();
                        textView.setText("location: lat" + lat + " lng" + location.getLongitude());
                        Log.e(tag, "happy");
                    } else {
                        repeatedRequests();
                        Log.e(tag, "null location");
                    }
                }
            });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
    } else work();
}

void createLocationRequest() {
    final LocationRequest mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    final SettingsClient settingsclient = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = settingsclient.checkLocationSettings(builder.build());

    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            repeatedRequests();
            Log.e(tag, "success");
        }
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                Log.e(tag, "failure" + e.getLocalizedMessage());
            //    repeatedRequests();
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException sendEx) {
                    Log.e(tag, "erorr " + sendEx.getLocalizedMessage());
                    // Ignore the error.
                }
            }
        }
    });
}

void repeatedRequests() {
    if (!started) {
        started = true;
        Log.e(tag, "Thread started");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (lat == 0) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    t++;
                    if (t > 50) break;
                    Log.e(tag, "repeat");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            locationDetails();
                        }
                    });
                }
            }
        }).start();
    }

}
boolean isLocationEnabled() {
    int locationMode = 0;

    try {
        locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);

    } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
        return false;
    }

    return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}

最佳答案

尝试设置mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 仅适用于您的三星,在我的情况下它可以工作,但请记住 locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) 在这种情况下将返回 false。

关于java - Android:无法发出位置请求对话框并在回调中获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138429/

相关文章:

java - Swing 中的重叠问题

c# - 将另一个窗体放在该窗体控件的顶部

android - 当我的 wi-fi 和移动数据关闭时,是否可以仅通过 GPS 从经纬度获取地址?

java - Spring 验证中 JSTL 等于 String

java - 如何将比较器与多个字段对象一起使用?

android - 在Windows 7上设置Android开发环境

android虚拟键盘监听器

android - 在 Android 上的 GPS 定位方面需要帮助

Java:Hibernate - 查询以从多个表中删除

android - 更改文本上的阴影大小