为什么函数getLastKnownLocation在Android SDK上返回Null?

时间:2014-04-20 09:14:30

标签: java android eclipse gps

我在eclipse上使用android sdk,我想从设备获取位置,所以我在其他类中编写了一个程序(与main不同),我从主类中调用了这个类中的 mContext 函数: / p>

package com.example.deomanapp;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.example.deomanapp.MainActivity.PlaceholderFragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class Mhelper {

    public void mContext(Context context)
    {
        LocationManager lm;
        lm   = (LocationManager)context.getSystemService(context.LOCATION_SERVICE); 
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        String slongitude = String.valueOf((long) longitude);
        String slatitude = String.valueOf((long) latitude);

        Toast.makeText(context, slongitude, Toast.LENGTH_SHORT).show();

    }

}

问题是 getLongitude getLatitude 返回null,因此程序在此行上崩溃并显示此日志:

04-20 04:30:30.410: E/AndroidRuntime(5151): java.lang.NullPointerException
04-20 04:30:30.410: E/AndroidRuntime(5151):     at com.example.deomanapp.Mhelper.mContext(Mhelper.java:29)

此代码有什么问题?

PS:我读了其他问题,标题相同而且没有主题帮助(非他们有实际答案),因为:

1-I我在真实设备(非仿真器)上使用GPS开启和工作测试此程序,但该程序无法获取位置,尽管设备之前获取其位置并且必须显示 LastKnownLocation 即可。

2 - 我给了程序ACCESS_FINE_LOCATION和ACCESS_COARSE_LOCATION权限。

3 - 我甚至使用一个功能来查看GPS是否打开,当我关闭程序提醒我时。

2 个答案:

答案 0 :(得分:1)

这是一个愚蠢的问题,它是null因为它是NULL,我通过主要问题的评论理解它,我的解决方案是在sdk管理器中下载 android api image ,运行谷歌地图一次,通过 DDMS 向其发送GPS位置,然后运行该程序。

答案 1 :(得分:0)

我试图修改一些代码,希望它能满足您的需求。

您将在答案的底部找到我的LocationsCoreModule代码的实现:

LocationsCoreModule locationService;

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

    LocationRequest mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(5000);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(1000);

    locationService = new LocationsCoreModule(this, mLocationRequest);
    locationService.setLocationsListener(new LocationsCoreModuleCallback() {

        @Override
        public void locationClientConnected() {
              Location location = locationService.getLastLocation();
              double longitude = location.getLongitude();
              double latitude = location.getLatitude();
              String slongitude = String.valueOf((long) longitude);
              String slatitude = String.valueOf((long) latitude);

              Toast.makeText(getApplicationContext(), slongitude, Toast.LENGTH_SHORT).show();
        }
    });
}

如果您希望应用程序立即开始收听新的GPS位置:

    @Override
protected void onStart() {
    super.onStart();

    locationService.start(new LocationListener() {

        @Override
        public void onLocationChanged(Location arg0) {
            // TODO Auto-generated method stub

        }
    }, new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult arg0) {
            // TODO Auto-generated method stub

        }
    });
}

@Override
protected void onStop() {
    super.onStop();

    locationService.stop();
}

最后,LocationsCoreModule:

public class LocationsCoreModule implements
        GooglePlayServicesClient.ConnectionCallbacks {

    private static final String TAG = "LocationsCoreModule";

    public interface LocationsCoreModuleCallback {
        public void locationClientConnected();
    }

    private LocationsCoreModuleCallback locationsCoreModuleCallback;

    private com.google.android.gms.location.LocationListener locationListener;

    private Location lastLocation;

    private LocationClient mLocationClient;

    private final LocationRequest mLocationRequest;
    private final Context context;


    @Inject 
    public LocationsCoreModule(Context context, LocationRequest locationRequest) {
        this.context = context;
        this.mLocationRequest = locationRequest;


    }

    public void setLastLocation(Location lastLocation) {
        this.lastLocation = lastLocation;
    }

    public void setLocationsListener(
            LocationsCoreModuleCallback locationsCoreModuleCallback) {
        this.locationsCoreModuleCallback = locationsCoreModuleCallback;
    }

    public void start(
            com.google.android.gms.location.LocationListener locationListener,
            GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener) {
        this.locationListener = locationListener;
        mLocationClient = new LocationClient(context, this,
                connectionFailedListener);
        mLocationClient.connect();
    }

    public void stop() {
        if (mLocationClient != null) {
            // If the client is connected
            if (mLocationClient.isConnected() && locationListener != null) {
                /*
                 * Remove location updates for a listener. The current Activity
                 * is the listener, so the argument is "this".
                 */
                mLocationClient.removeLocationUpdates(locationListener);
            }

            // Disconnecting the client invalidates it.
            mLocationClient.disconnect();
        }
    }


    public boolean isConnected() {
        if (mLocationClient == null) return false;
        return mLocationClient.isConnected();
    }

    public Location getLastLocation() {

        if (lastLocation != null) {
            return lastLocation;
        }

        if (mLocationClient != null) {
            if (mLocationClient.isConnected()) {
                return lastLocation = mLocationClient.getLastLocation();
            }

            if (!mLocationClient.isConnecting())
                mLocationClient.connect();
        }

        return null;

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.d(TAG, "GooglePlayServices connected!");

        Location lastLocation = mLocationClient.getLastLocation();

        if (lastLocation == null)
            Log.e(TAG, "Lastlocation is null even after connected!!!!");

        if (locationsCoreModuleCallback != null) {
            locationsCoreModuleCallback.locationClientConnected();
            locationsCoreModuleCallback = null; // single shot
        }

    }

    public void requestLocationUpdates() {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            Log.d(TAG, "Requesting location updates");
            mLocationClient.requestLocationUpdates(mLocationRequest,
                    locationListener);
        }
    }

    public void stopLoactionUpdates() {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            mLocationClient.removeLocationUpdates(locationListener);
        }
    }

    @Override
    public void onDisconnected() {
        Log.d(TAG, "GooglePlayServices disconnected!");
    }

}