首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Andorid:提示开启后获取位置

Andorid:提示开启后获取位置
EN

Stack Overflow用户
提问于 2018-08-02 20:03:55
回答 1查看 99关注 0票数 0

我想在应用程序启动时获取设备的当前位置。它工作得很好,但是如果位置被停用,它就会崩溃。所以我使用了一些代码来提示用户激活它,但似乎程序在位置被实际激活之前就到达了崩溃线。(在提示用户激活它之前)。

下面的enableLocation()方法负责提示用户和getDeviceLocation()获取位置。我尝试将getDeviceLocation()放在onstart方法中,将enableLocation()放在oncreate方法中,但仍然不起作用。有什么想法吗?

例如,在uber应用程序中,如果location被禁用,R.id.contrainer框架布局似乎会被一个虚拟片段(而不是SupportMapFragment)所取代。并且通过点击按钮来提示用户启用它。然后SupportMapFragment替换虚拟片段(根据我的理解)。但所有这些似乎都太多了。这是唯一的办法吗?

代码语言:javascript
复制
oncreate() {
....
    SupportMapFragment fragment;
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragment = new SupportMapFragment();
    fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
    fragment.getMapAsync(this);
..... 
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Prompt the user for permission.
    getLocationPermission();

    // Prompt the user to enable location if it is disabled
    // by using Task<LocationSettingsResponse>
    // and LocationSettingsRequest.Builder
    enableLocation();

    // Turn on the My Location layer and the related control on the map.
    updateLocationUI();

    // Get the current location of the device and set the position of the map.
    // uses Task.getResult which returns null because location
    // is yet to be activated despite chosing to do so above
    getDeviceLocation();
}

// inside getDeviceLocation();
@Override
public void onComplete(@NonNull Task<Location> task) {
       if (task.isSuccessful()) {
                // Set the map's camera position to the current location of the device.
                mLastKnownLocation = task.getResult(); // RETURNS NULL HERE
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(mLastKnownLocation.getLatitude(),
                LastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} 
EN

回答 1

Stack Overflow用户

发布于 2018-08-03 18:59:08

私有空getCurrentLocation() {

代码语言:javascript
复制
    gps = new GPSTracker(context, getActivity());
    if (gps.canGetLocation()) {
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) 
         return;
        }
        currentLatitude = gps.getLatitude();
        currentLongitude = gps.getLongitude();
    } else {
        showSettingsAlert();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51653176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档