我无法在android中使用locationServices.getLastLocation

时间:2017-05-09 11:21:50

标签: android mapbox

我想在我的Android应用程序中获取lastlocation。这是在我的应用程序中通过mapbox的帮助完成的。但我无法导入" import com.mapbox.mapboxsdk.location.LocationServices;&#34 ;

apply plugin: 'com.android.application'

依赖{     编译组:' com.mapbox.mapboxsdk',名称:' mapbox-android-navigation',版本:' 0.1.0'

compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile('com.mapbox.mapboxsdk:mapbox-android-sdk:3.2.0@aar') {
    transitive = true
}
compile ('com.mapbox.mapboxsdk:mapbox-android-directions:1.0.0@aar'){
    transitive=true
}
compile 'com.google.android.gms:play-services:10.2.1'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile ('com.mapbox.mapboxsdk:mapbox-android-sdk:5.0.2@aar'){
    transitive=true
}
compile ('com.mapbox.mapboxsdk:mapbox-android-services:2.1.0@aar'){
    transitive=true
}
compile('com.mapbox.mapboxsdk:mapbox-android-sdk:4.0.0@aar') {
    transitive = true
}

}

1 个答案:

答案 0 :(得分:0)

我正在使用以下代码获取我应用中的最后一个位置:

public static Location getLastKnownLocation(Context context) {
    try {
        LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        return bestLocation;
    } catch (SecurityException e) {
        e.printStackTrace();
        return null;
    }
}

此代码仍需要改进:最好是请求权限而不是捕获安全异常: see this stackoverflow thread

不要忘记在清单上添加所需的权限:

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