SmartLocationLibrary 位置始终为空

Posted

技术标签:

【中文标题】SmartLocationLibrary 位置始终为空【英文标题】:SmartLocationLibrary location is always null 【发布时间】:2019-04-20 08:44:22 【问题描述】:

我正在尝试学习 SmartLocationLibrary for android 以获取位置,而我从中获取的位置始终为空,因此当我尝试使用它执行某些操作时出现空对象引用错误。

我为 SmartLocatonLibrary 创建了一个实用程序类

public class LocationUtil implements OnLocationUpdatedListener, OnActivityUpdatedListener 

    private final String TAG = "LocationUtil: ";

    private Location location;

    private DetectedActivity activity;

    private LocationGooglePlayServicesProvider provider;

    private Context context;

    public LocationUtil(Context context) 
        this.context = context;
    

    /**
     * If lastLocation is not null then the location is set to last location recorded by phone
     */
    public void getLastLocation()
        Location lastLocation = SmartLocation.with(context).location().getLastLocation();

        if(lastLocation != null)
            location = lastLocation;
        

        DetectedActivity detectedActivity = SmartLocation.with(context).activity().getLastActivity();

        if(detectedActivity != null) activity = detectedActivity;

    

    /**
     * Basically this starts the location tracking
     * If you want one tick of location use .oneFix() on the smartLocation builder
     * If you want continous tracking just don't add the .oneFix()
     */
    public void startLocation()
        provider = new LocationGooglePlayServicesProvider();
        provider.setCheckLocationSettings(true);

        SmartLocation smartLocation = new SmartLocation.Builder(context).logging(true).build();

        smartLocation.location(provider)
                .continuous()
                .start(this);

        smartLocation.activity()
                .start(this);
    


    /**
     * This stops the tracking
     */
    public void stopLocation()
        SmartLocation.with(context).location().stop();
        Log.d(TAG, "stopLocation: Location Stopped");

        SmartLocation.with(context).activity().stop();
        Log.d(TAG, "stopLocation: Activity Recognition Stopped");

    


    @Override
    public void onActivityUpdated(DetectedActivity detectedActivity) 
        this.activity = detectedActivity;
    

    @Override
    public void onLocationUpdated(Location location) 
        this.location = location;
    

    //--------SETTERS----------

    public void setProvider(LocationGooglePlayServicesProvider provider) 
        this.provider = provider;
    


    //--------GETTERS----------


    public Location getLocation() 
        return location;
    

    public LocationGooglePlayServicesProvider getProvider() 
        return provider;
    

这是使用它的地图活动

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback 

    private final String TAG = "MAPY";

    private int LOCATION_PERMISSION_ID = 1001;

    private GoogleMap mMap;

    Location location;

    LocationUtil locationUtil = new LocationUtil(MapsActivity.this);

    Button centerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        centerButton = findViewById(R.id.centerCameraBtn);

        centerButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if(location != null)
                    mMap.moveCamera((CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()))));
            
        );
    

    @Override
    protected void onStop() 
        super.onStop();
        locationUtil.stopLocation();
    

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

        //Check for permissions if they are not granted request them
        if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(MapsActivity.this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_PERMISSION_ID);
            return;
         else
            locationUtil.startLocation();
        


        locationUtil.getLastLocation();

        Log.d(TAG, "onMapsReady.lat: " + location.getLatitude() + " onMapsReady.lng: " + location.getLongitude());

        location = locationUtil.getLocation();
        LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(currentLocation).title("My current location").snippet("This is a sinppet"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if(locationUtil.getProvider() != null)
            locationUtil.getProvider().onActivityResult(requestCode, resultCode, data);
        
    


我像图书馆的作者展示的那样做到了here,但它不起作用。有趣的是它昨天奏效了。我正在我的个人手机上测试它。位置、移动数据和 wifi 已打开并且工作正常。我获得了权限,我将权限添加到清单(FINE 和 COARSED)中,并且在我的依赖项中是

实现 'com.android.support:appcompat-v7:28.0.0' 实施 'com.android.support:support-v4:28.0.0' 实施 'com.android.support:support-media-compat:28.0.0' 实施 'io.nlopez.smartlocation:library:3.3.3' 实施 'com.google.android.gms:play-services-maps:16.0.0' 实施 'com.google.android.gms:play-services-location:16.0.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 实现 'com.android.support.constraint:constraint-layout:1.1.3'

我真的不知道怎么回事,请帮帮我。

【问题讨论】:

【参考方案1】:

好的,所以这不起作用,因为我想记录尚未初始化的位置变量的值。用调试器调试它表明我得到了位置。但更有趣的是,因为这是一个仅用于在主应用程序中测试库的项目,即使我正在做与这里相同的所有操作,相同的实用程序类也不会获取我的位置......

【讨论】:

以上是关于SmartLocationLibrary 位置始终为空的主要内容,如果未能解决你的问题,请参考以下文章

融合位置始终返回 null

如何创建一个始终指向该位置的组合?

位置返回始终为空 - android

iOS 13 中“始终允许”位置的问题

地理位置 Ionic 3 始终返回“”

我是不是需要获得后台位置更新的“始终”授权?