【问题标题】:4 Ways get Location all return null with Device Location set to On (Wifi & GPS)设备位置设置为开启(Wifi 和 GPS)的 4 种获取位置的方法全部返回 null
【发布时间】:2017-12-01 03:28:14
【问题描述】:

编辑:我已将工作代码放在这里。每个人都可以复制粘贴来运行代码。现在有 4 种获取 Location 的方法,但结果为 null。

我已经尝试了超过 5 种有关位置的代码,但大多数情况下,有 3 种方法可以使用 Android 访问位置数据。所有这些代码都返回 null。设备位置(GPS 和 WIFI)已打开。已在 AndroidManifest.xml 上设置权限。我在真机和 AVD 模拟器上试过,结果一样:return null。有人可以告诉我代码有什么问题吗?都是工作代码(在我的电脑中)。

1。 LocationManager & LocationListener

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {}

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}

            @Override
            public void onProviderEnabled(String provider) {}

            @Override
            public void onProviderDisabled(String provider) {}
        };

        String coarse = "android.permission.ACCESS_COARSE_LOCATION";
        String fine = "android.permission.ACCESS_FINE_LOCATION";
        if (ContextCompat.checkSelfPermission(this, coarse) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{coarse}, 101);
        }
        if (ContextCompat.checkSelfPermission(this, fine) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{fine}, 102);
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, (android.location.LocationListener) locationListener);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            System.out.println("LATITUDE: " + location.getLatitude());
            System.out.println("LONGITUDE: " + location.getLongitude());
        } else {
            System.out.println("LOCATION IS NULL");
        }
    }
}

2。 FusedLocationProviderClient

public class MainActivity extends AppCompatActivity {
    private LocationRequest mLocationRequest;
    private FusedLocationProviderClient locationClient;

    private long UPDATE_INTERVAL = 10 * 1000;  /* 10 secs */
    private long FASTEST_INTERVAL = 2000; /* 2 sec */

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startLocationUpdates();
    }

    // Trigger new location updates at interval
    protected void startLocationUpdates() {

        // Create the location request to start receiving updates
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        // Create LocationSettingsRequest object using location request
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        LocationSettingsRequest locationSettingsRequest = builder.build();

        // Check whether location settings are satisfied
        // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
        settingsClient.checkLocationSettings(locationSettingsRequest);

        // new Google API SDK v11 uses getFusedLocationProviderClient(this)
        String coarse = "android.permission.ACCESS_COARSE_LOCATION";
        String fine = "android.permission.ACCESS_FINE_LOCATION";
        if (ContextCompat.checkSelfPermission(this, coarse) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{coarse}, 101);
        }
        if (ContextCompat.checkSelfPermission(this, fine) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{fine}, 102);
        }
        LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        // do work here
                        onLocationChanged(locationResult.getLastLocation());
                    }
                },
                Looper.myLooper());
    }

    public void onLocationChanged(Location location) {
        // New location has now been determined
        String msg = "Updated Location: " + location.getLatitude() + "," + location.getLongitude();
        System.out.println(msg);
    }
}

3。 FusedLocationApi

public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    protected static final String TAG = "main-activity";
    protected GoogleApiClient mGoogleApiClient;
    protected Location mLastLocation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        buildGoogleApiClient();
    }

    /**
     * Builds a GoogleApiClient. Uses {@code #addApi} to request the LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Runs when a GoogleApiClient object successfully connects.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        // Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.
        String coarse = "android.permission.ACCESS_COARSE_LOCATION";
        String fine = "android.permission.ACCESS_FINE_LOCATION";
        if (ContextCompat.checkSelfPermission(this, coarse) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{coarse}, 101);
        }
        if (ContextCompat.checkSelfPermission(this, fine) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{fine}, 102);
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            System.out.println("LATITUDE: " + mLastLocation.getLatitude());
            System.out.println("LONGITUDE: " + mLastLocation.getLongitude());
            // It is possible that the user presses the button to get the address before the
            // GoogleApiClient object successfully connects. In such a case, mAddressRequested
            // is set to true, but no attempt is made to fetch the address (see
            // fetchAddressButtonHandler()) . Instead, we start the intent service here if the
            // user has requested an address, since we now have a connection to GoogleApiClient.
        } else {
            System.out.println("LOCATION IS NULL");
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
}

4 SmartLocation 库:编译 'io.nlopez.smartlocation:library:3.2.9'

public class Location1Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        System.out.println("ON LOCATION1ACTIVITY");

        SmartLocation.with(this).location()
                .oneFix()
                .start(new OnLocationUpdatedListener() {
                    @Override
                    public void onLocationUpdated(Location location) {
                        if (location == null) {
                            System.out.println("LOCATION IS NULL");
                        } else {
                            System.out.println("LATITUDE: " + location.getLatitude());
                            System.out.println("LONGITUDE: " + location.getLongitude());
                        }
                    }
                });
    }
}

【问题讨论】:

  • 不行,Hitesh。我的代码:SmartLocation.with(this).location() .oneFix() .start(new OnLocationUpdatedListener() { @Override public void onLocationUpdated(Location l) { if (l == null) { Sout("LOC IS NULL"); } else { Sout("LAT: " + l.getLatitude()); Sout("LNG: " + l.getLongitude()); } } });
  • 你能达到你想要的吗?
  • 不工作。我使用了来自 github 的适当代码。我设置了 System.out.println,但 logcat 上没有打印任何内容。
  • 确保您的应用程序确实具有 ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION(两者)以获得准确的结果。不要忘记在运行时为 Android 6.0 及更高版本请求权限。

标签: android location


【解决方案1】:

找到解决方案! 我已将 AVD 映像降级为 Android 8.0(SDK 平台 26)Google Play Intel x86 Atom Sistem Image。以前,我使用 Android API 27 Google Play Intel x86 Atom System Image。现在所有上述代码都可以正常工作,除了代码 #1。

我的详细信息: AndroidManifest.xml 使用权限:

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

检查和请求 .java 文件的权限:

String coarse = "android.permission.ACCESS_COARSE_LOCATION";
String fine = "android.permission.ACCESS_FINE_LOCATION";
if (ContextCompat.checkSelfPermission(activity, coarse) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(activity, new String[]{coarse}, 101);
}
if (ContextCompat.checkSelfPermission(activity, fine) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(activity, new String[]{fine}, 102);
}

项目 build.gradle 依赖类路径:

classpath 'com.android.tools.build:gradle:3.0.1'

模块构建.gradle: 应用插件:'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "org.ts.gov.lesson3"
        minSdkVersion 21
        targetSdkVersion 26
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:support-v4:26.+'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'
    compile 'io.nlopez.smartlocation:library:3.2.9'
}

希望这对有同样问题的人有所帮助。我花了几天时间试图解决这个问题。如果您想知道为什么我的物理设备也无法使用该位置,我也一样。只需使用我的手机执行代码 #4,直到我使用 SDK 26 降级到 AVD Oreo 8.0。

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 2018-06-30
    • 2015-11-02
    • 2011-02-11
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多