Java Android位置管理器返回空指针异常

Java Android位置管理器返回空指针异常,java,android,nullpointerexception,Java,Android,Nullpointerexception,我有一个问题,我试图创建一个使用位置管理器但不是当前正在运行的活动的类。所以,当我从任何活动调用这个类时,它都是在后台完成的。我尝试扩展服务,但始终返回空指针错误 这一行代码返回错误 public class BackgroundGps extends Service{ UserObject uo = null; BackgroundGps(UserObject userObj){ uo = userObj; uo.setHeader("GPSUpdate"); } public

我有一个问题,我试图创建一个使用位置管理器但不是当前正在运行的活动的类。所以,当我从任何活动调用这个类时,它都是在后台完成的。我尝试扩展服务,但始终返回空指针错误

这一行代码返回错误

public class BackgroundGps extends Service{
UserObject uo = null;
BackgroundGps(UserObject userObj){
    uo = userObj;
    uo.setHeader("GPSUpdate");
}
public void locationListener(){
    LocationManager mlocManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListener = new LocationListener(){
        public void onLocationChanged(Location location){
            if(uo.getLatitude() == ("" + location.getLatitude()) && uo.getLongitude() == ("" + location.getLongitude())){}
            else{
                uo.setLatitude("" + location.getLatitude());
                uo.setLongitude("" + location.getLongitude());
                updateGPS();
            }
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
    };
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, mlocListener);
    mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 5, mlocListener);
}

谢谢

获取系统位置管理器的参考

 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager不会在设备上抛出空指针,而会在模拟器上抛出空指针

向位置管理器注册侦听器以接收位置更新。在这里,您可以根据需要使用网络提供商或GPS提供商等*

 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

您需要在当前的
上下文中调用
getSystemService()
。您在调用此类时是否传递当前的
上下文

您是否确实使用意图启动了服务


如果您没有并且只是从活动中创建
新BackgroundGps()
,则该服务没有上下文(null)。

您是否在模拟器或设备上运行?您可能正在从任何活动中运行BackgroundGps服务,请将活动的上下文传递到此服务,然后使用,